php - mod_rewrite : Demystifying RewriteBase (once and for all)

标签 php wordpress apache .htaccess mod-rewrite

我一直看到这个(为了简洁起见,我省略了 IfModuleRewriteEngine 指令):

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/

相关文章:

html - 如何使当前查看的列表标题加粗

mysql - WordPress 密码问题

linux - 在端口 8080 上阻止对 Jira 的访问

php - 如何在PHP中分割二进制数据并将其转换为数字?

PHP HTML 表单保留输入的数据和 isset()

javascript - 如何隐藏包含特定值的类?

python - 在 Windows 7 上的 wamp apache 中安装 python cgi

php - Alias 指令可能永远不会匹配,因为它与早期的 Alias 重叠

php - 将 key => value 添加到循环中的关联数组?

浏览器中显示的 PHP 代码