有没有办法使用重写模块根据主机标头根域进行动态重定向

Is there a way to use the rewrite module to dynamic redirect based on host header root domain

提问人:Paul 提问时间:8/30/2023 最后编辑:MrWhitePaul 更新时间:8/31/2023 访问量:25

问:

我有客户的规格。给定一个带有重写模块的 apache Web 服务器,找到一种基于主机头根域动态重定向的方法。

例如,如果请求来自重定向到www.example1.comexample1.customersite.com

与多级子域(最多 3 个)相同的事情应该重定向到 .my.redirect.to.example2.comexample2.customersite.com

这可以通过重写模块来完成吗?

Apache URL url-重写

评论

0赞 MrWhite 8/31/2023
没有子域(例如)怎么办?我假设应该通过重定向保留 URL 路径?“if request is coming from” - 大概你的意思是“去”,而不是“来自”?规则在哪里使用?在服务器配置中?https://example1.comwww.example1.com.htaccess

答:

0赞 MrWhite 8/31/2023 #1

我假设这是针对任何 URL 路径的,并且应该通过重定向来保留。因此,表单的 URL 将被重定向到 。subdomain.<example>.com/<url-path><example>.customersite.com/<url-path>

您可以使用 mod_rewrite 执行如下操作:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?:[^.]+\.){1,3}(example)\.com [NC]
RewriteRule ^ https://%1.customersite.com%{REQUEST_URI} [R=302,L]

服务器变量(使用语法访问)包含所请求标头的值。HTTP_HOST%{HTTP_HOST}Host

这仅允许 1 到 3 个子域。域顶点(无子域)或超过 3 个不会被重定向。

反向引用包含上述条件中捕获子模式的值。在这种情况下,它只包含字符串“example”以节省重复。%1

请注意,这是 302(临时)重定向。