Previously, I discussed the topic of Nginx supporting .htaccess files with Wang Yi in the Typecho development group. Wang Yi believed that Nginx can support .htaccess rules and is compatible with Apache rules. In my view, Nginx supports using the .htaccess file to store Nginx’s pseudo-static rules, but it is not compatible with .htaccess rules.
銆€銆€I have my reasons for saying this. I consulted Nginx’s official documentation: Doc 1/Doc 2. Doc 1 is the documentation for Nginx’s Rewrite module, detailing the composition of Nginx’s rewrite rules. In it, I found no mention of Apache rules. In Doc 2, the documentation explains why .htaccess files are not used and compares Nginx with Apache. As is well known, Nginx does not support .htaccess rules. Hongshu, the founder of OSChina, once published an article: Who Says Nginx Doesn’t Support .htaccess. In my opinion, Hongshu was muddying the waters and shifting the concept. What we were talking about were .htaccess rules, while Hongshu was talking about the .htaccess file itself.
銆€銆€Having said all that, let me analyze why Nginx does not support .htaccess, focusing on the following key aspects.
銆€銆€1. Performance Requirements: From Doc 2, we learn that when Apache processes pseudo-static rules, it searches for .htaccess files in each directory sequentially. This results in numerous lookups, impacting performance, which conflicts with Nginx’s design philosophy.
銆€ 銆€2. Determined by Software Model: Apache was designed for dynamic loading, which is evident from how it handles .htaccess files. Once you modify .htaccess, it takes effect immediately. Similarly, Apache loads modules dynamically. Nginx, on the other hand, uses hard-coded rules that require a reload to take effect. Although Tengine offers dynamic module loading, a configuration reload is still needed for changes to apply, making it a form of “pseudo-dynamic” behavior.
銆€銆€3. Pride of the Northern Bear: With the shadow of the US behind Apache, the bears might feel that compatibility would be somewhat subservient. Thus, they created their own version.
銆€銆€Regarding the feasibility analysis of applying .htaccess to Nginx: In my view, .htaccess cannot be commercialized on the LNMP platform. The main reasons are as follows:
銆€銆€1. Low Security.
銆€銆€Because Nginx loads the configuration file first and then runs, if you are on a shared host with a tinkering neighbor, and that guy makes a mistake in editing, your site will also become inaccessible, suffering collateral damage.
銆€銆€2. Inconvenient Operation.
銆€銆€Since Nginx loads the configuration file beforehand, it needs to be restarted after each modification. Would you give users the SSH password for convenient restarts? If you don’t provide the password and use PHP’s exec function instead, there’s a risk of cross-site attacks. If Chroot is enabled