我一直看到这个(为了简洁起见,我省略了 IfModule
和 RewriteEngine
指令):
RewriteBase /somedir/ #1
RewriteRule ^index\.php$ - [L] #2
RewriteCond %{REQUEST_FILENAME} !-f #3
RewriteCond %{REQUEST_FILENAME} !-d #4
RewriteRule . /somedir/index.php [L] #5
来自documentation (以及我的经验):
When using the rewrite engine in .htaccess files the per-directory prefix [...] is automatically removed for the RewriteRule pattern matching and automatically added after any relative (not starting with a slash or protocol name) substitution encounters the end of a rule set. See the RewriteBase directive for more information regarding what prefix will be added back to relative substitutions.
现在,上面的第 5 行不是相对替换(注意前导斜杠),因此第 1 行没有效果,因为没有为“添加前缀”绝对”替换。
那么我的问题是,指令 #1 和指令 #5 的一部分之间是否存在冗余?
最佳答案
Then my question is, isn't there redundancy between directive #1 and part of #5?
不,这实际上并不是冗余。这只是因为您在此处使用绝对 URL,这告诉 mod_rewrite
引擎在重写中使用绝对 URL 而不是相对 URL。
如果你的第五行变成:
RewriteRule . index.php [L]
然后RewriteBase
将生效并用于将URI重写为:/somedir/index.php
使用 RewriteBase
的主要优点是,您不需要在存在的所有规则中不断重复 /somedir/
相同的 .htaccess
文件。
如何动态获取RewriteBase
:
RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$
RewriteRule ^(.*)$ - [E=BASE:%1]
关于WP:
Wordpress 可以安全地从 RewriteRule 中删除绝对路径,因为它们无论如何都使用绝对路径。但问题是,很多 WP 插件都会覆盖该 .htaccess 文件,因此他们只是不想依赖 RewriteBase 行的存在。
关于php - mod_rewrite : Demystifying RewriteBase (once and for all),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21797956/