Apache 处理 .htaccess 指令的顺序

Apache 处理 .htaccess 指令的顺序

我昨天在 WordPress 网站上工作,主要是进行 Web 性能优化(在共享主机上)。

有一次我注意到我的.htaccess文件有多余的、可能相互矛盾的指令:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# From the HTML5 Boilerplate
# https://github.com/h5bp/html5-boilerplate/blob/master/.htaccess
# Apache Server Configs v2.0.0 | MIT License
# https://github.com/h5bp/server-configs-apache

...

# BEGIN WordPress
RewriteEngine on
#
# Unless you have set a different RewriteBase preceding this
# point, you may delete or comment-out the following
# RewriteBase directive:
RewriteBase /
#
# if request is for image, css, or js file
RewriteRule \.(gif|jpe?g|css|js|ico)$ - [L,NC]
# or if URL resolves to existing file
RewriteCond %{REQUEST_FILENAME} -f [OR]
# or if URL resolves to existing directory
RewriteCond %{REQUEST_FILENAME} -d
# then skip the rewrite to WP
RewriteRule ^ - [S=1]
# else rewrite the request to WP
RewriteRule . /index.php [L]
#
# END wordpress

我省略了 HTML5 Boilerplate 中的内容.htaccess(省略号),因为我认为代码不相关(我几乎没有触及它,大部分时候都按原样使用它,而且它在足够多的网站上运行良好,我知道它没有问题。作为参考,在这里能找到它

由于该.htaccess文件顶部有默认的 WordPress 指令,底部有“改进的”指令,那么哪个适用?

我搜索了 Stackoverflow 和这里,发现了几个关于这一点的问题,但没有一个真正回答了指令的处理顺序。应该使用文件顶部的那个还是底部的那个?

这是一个清晰、具体的例子,但我经常会得到.htaccess具有重复代码和冗余的文件,因此,对我来说,一个更通用的“经验法则”答案比仅适用于这个实例的答案更有用……例如,我经常会得到具有不同语法的 gzip ( compress/ mod_deflate) 指令,但我不知道它们的顺序是否重要。

我认为这个站点是基于 Apache 2.2 的,希望有帮助。

谢谢

答案1

由于RewriteRule . /index.php [L]将捕获除之外的每个请求/,并且无论如何都会转到index.php,第二组规则(文件底部)永远不会适用。

事实上,这并不完全正确,但他们所做的就是尝试跳过index.php静态文件的重写(无论如何这都不会发生)。

这可能是复制粘贴错误,或者是 Wordpress 的自动.htaccess文件管理(这是一个糟糕的功能)做了不该做的事情。删除第二组规则,它不太准确,不太清晰,而且只会让人感到困惑。

相关内容