mod_rewrite 将 docroot 的子目录作为子域
我尝试使用 mod_rewrite 将 123.example.com/456/file.html
的请求重定向到 example.com/123/456/file.html
。重写是必要的,因为新目录可能会动态创建。我试图通过它进行推理,但似乎无法找到可行的解决方案。
首先,如果我使用下面的重写规则,我会得到 所有 404,因为它成功运行第二条规则,执行内部重定向,继续再次运行规则,并且第一条规则匹配,因为它正在寻找 < code>123/123/456/file.html,导致 404。
RewriteCond %{HTTP_HOST} ^(\d+)\.
RewriteCond %{DOCUMENT_ROOT}/%1/$1 !-d
RewriteCond %{DOCUMENT_ROOT}/%1/$1 !-f
RewriteRule (.*) - [R=404,L]
RewriteCond %{HTTP_HOST} ^(\d+)\.
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -d [OR]
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -f
RewriteRule (.*) /%1/$1 [L]
如果我将 404 移到最后,我会得到以下信息:
RewriteCond %{HTTP_HOST} ^(\d+)\.
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -d [OR]
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -f
RewriteRule (.*) /%1/$1 [L]
RewriteCond %{DOCUMENT_ROOT}/$1 !-d
RewriteCond %{DOCUMENT_ROOT}/$1 !-f
RewriteRule ^(.*)$ - [R=404,L]
它几乎可以按照我的需要工作它,但当您输入 123.example.com/123/
时不会出现 404,即使它应该是无效的。由于第一条规则未重写路径,因此 $1
的计算结果为 123/
而不是无效路径 123/123/
,这使得请求成功,无需运行任何重写规则。
我觉得我已经非常接近让它发挥作用了。任何帮助表示赞赏。
I'm attempting to use mod_rewrite to redirect requests to 123.example.com/456/file.html
to example.com/123/456/file.html
. The rewrite is necessary because new directories may be created on the fly. I've tried to reason through it but can't seem to come to a working solution.
First, if I use the below rewrite rules I get a 404 for everything because it runs the second rule successfully, does internal redirection, proceeds to run the rules again and the first rule matches because it's looking for 123/123/456/file.html
, causing a 404.
RewriteCond %{HTTP_HOST} ^(\d+)\.
RewriteCond %{DOCUMENT_ROOT}/%1/$1 !-d
RewriteCond %{DOCUMENT_ROOT}/%1/$1 !-f
RewriteRule (.*) - [R=404,L]
RewriteCond %{HTTP_HOST} ^(\d+)\.
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -d [OR]
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -f
RewriteRule (.*) /%1/$1 [L]
If I move the 404 to be last, I get the following:
RewriteCond %{HTTP_HOST} ^(\d+)\.
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -d [OR]
RewriteCond %{DOCUMENT_ROOT}/%1/$1 -f
RewriteRule (.*) /%1/$1 [L]
RewriteCond %{DOCUMENT_ROOT}/$1 !-d
RewriteCond %{DOCUMENT_ROOT}/$1 !-f
RewriteRule ^(.*)$ - [R=404,L]
It almost works as I need it, but doesn't 404 when you enter 123.example.com/123/
, even though it should be invalid. Since the path wasn't rewritten by the first rule, $1
evaluates to 123/
instead of the invalid path 123/123/
, which makes the request succeed without any rewrite rules running.
I feel like I'm very close to getting this to work. Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的第一组规则之前添加以下 RewriteCond ,如下所示,以防止内部重定向
Add the following RewriteCond before your first set of Rules as below to prevent internal redirection