apache - htaccess 将 RewriteBase 设置为请求 URI 的开头

标签 apache .htaccess mod-rewrite

如何将 .htaccess 文件中的 RewriteBase 设置为 REQUEST_URI 的第一部分(domain.com/path 或 domain.com/path/to/file 将 RewriteBase 设置为/path)?

最佳答案

您无法动态设置 RewriteBase,但您可以手动从 %{REQUEST_URI} 中提取第一个路径,然后手动将其添加到 绝对 URL 路径目标。示例:

RewriteBase /
RewriteCond %{REQUEST_URI} ^/([^/]+)
RewriteRule ^foo$ /%1/bar.html [L]

这里,如果该规则位于 URL 路径 /a/b/c 的 htaccess 文件中,并且您请求 /a/b/c/foo ,该规则会将其重写为 /a/bar.html

或者,如果您有很多规则并且绝对需要 % 反向引用,您可以将其设置为 htaccess 文件最顶部的环境变量:

RewriteBase /
RewriteCond %{ENV:first_uri_path} ^$
RewriteCond %{REQUEST_URI} ^/([^/]+)
RewriteRule ^ - [E=first_uri_path:%1]

# then your rules:
RewriteCond %{HTTP_HOST} www\.(.*)
RewriteRule ^foo$ /%{ENV:first_uri_path}/bar.php?domain=%1 [L]

不确定这个解决方案对您来说有多可行,具体取决于您实际计划使用“动态 RewriteBases”做什么。

关于apache - htaccess 将 RewriteBase 设置为请求 URI 的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17816947/

相关文章:

php - 在 php.ini 上编辑不起作用

Python 记录器不适用于带有 apache 的 django

.htaccess - 通过 .Htaccess 进行 URL 重定向在 Php Codeigniter 中不起作用

apache - mod 重写不适用于 laravel 和 bitNami

apache - Htaccess 将目录重定向到另一个目录,但允许主文件夹 URL 保持不变

apache - RewriteEngine 每次都在 <IfModule mod_rewrite.c> 中打开?

PHP 不会解析 MySQL 语句

apache - Ghost后端抛出代理错误

.htaccess - 如果页面 url 包含特定单词,如何禁用 SSL

.htaccess 301 http ://redirect to https://not being indexed by Google