Apache mod_rewrite中REQUEST_URI的处理与陷阱
参考以下配置规则: 复制代码 代码如下: RewriteEngine on # sitemap index xml rewrite RewriteRule ^sitemap_([a-zA-Z0-9_\-]+)\.xml$ /sitemap/$1 # redirected all invalid request the the index bootstrap RewriteRule !\.(htm|txt|xml|css|js|swf|gif|jpg|png|ico)$ index.php [L] 假设用户访问 sitemap_index.xml ,经过上述两条 RewriteRule 处理后,传递给入口文件 index.php 的 $_SERVER['REQUEST_URI'] 依然显示为 /sitemap_index.xml 。然而,业务逻辑期望该值为 /sitemap/index ,以便 index.php 能够正确执行 URL 路由解析。
为实现这一目标,存在两种可行的解决方案。
第一种方案是结合 mod_proxy 模块,将第一条重写规则修改为: 复制代码 代码如下: # sitemap index xml rewrite RewriteRule ^sitemap_([a-zA-Z0-9_\-]+)\.xml$ /sitemap/$1 [P,L] 此配置会在服务器内部生成一个新的 HTTP 请求,从而使 REQUEST_URI 的值更新为新的 /sitemap/index 。不过,这种方式的缺点是会引发额外的 HTTP 请求开销。
第二种方案是将第一条规则调整为: 复制代码 代码如下: # sitemap index xml rewrite RewriteRule ^sitemap_([a-zA-Z0-9_\-]+)\.xml$ /sitemap/$1 [E=REQUEST_URI:/sitemap/$1] 或者: 复制代码 代码如下: # sitemap index xml rewrite RewriteRule ^sitemap_([a-zA-Z0-9_\-]+)\.xml$ index.php [E=REQUEST_URI:/sitemap/$1,L] 随后通过 $_SERVER['REDIRECT_REQUEST_URI'] 变量获取到 /sitemap/index 的值。需要注意的是,当使用 E 参数设置环境变量时,mod_rewrite 会自动为变量名添加 REDIRECT_ 前缀。
值得注意的是,在 Rewrite 处理过程中,REQUEST_URI 的值始终维持为原始的请求 URI。但在 mod_setenvif 模块提供的 SetEnvIf 或 SetEnvIfNoCase 指令中,所使用的 Request_URI 属性所对应的却是经过重写处理后的地址,而非原始的 GET/POST 请求 URI。
因此,若在 httpd.conf 或 httpd-vhosts.conf 中使用 复制代码 代码如下: SetEnvIfNoCase Request_URI "sitemap" ... 来针对 sitemap 设置环境变量,该配置将无法生效。因为此时传入 SetEnvIfNoCase 进行判断的 Request_URI 实际上是 index.php,而不是 sitemap_index.xml 或 sitemap/index 。若需获取原始的 Request_URI 信息,必须在重写规则的最开始阶段进行保存,例如在规则开头加入: 复制代码 代码如下: SetEnvIfNoCase Request_URI "(^/sitemap_.*\.xml)" MY_REQUEST_URI_BF_REWRITE=$1 然后在后续需要的地方使用: 复制代码 代码如下: SetEnvIfNoCase MY_REQUEST_URI_BF_REWRITE "sitemap" ...