mod_rewrite 将子域名中的破折号替换为下划线并进行重定向

3

这是我想要做的事情:

  • 我想要将所有子域名中的破折号 (-) 替换为下划线 (_)。
  • 在替换所有破折号后,我想要重定向到一个名为重写子域名的子目录。

例如: http://subdomain-with-dashes.rotarytest.de/a-directory/an-image.png 重写后应该是 http://rotarytest.de/subdomain_with_dashes/a-directory/an-image.png

这是我目前拥有的代码,请查看代码中的注释

RewriteEngine on

# replace dashes with underscores
# this works, but only for the last dash
RewriteCond %{HTTP_HOST} ^(.*)-(.*)$
RewriteRule ^(.*)$ http://%1_%2/$1 [L,R=301]


# if a subdomain is called, redirect to subdirectory
# this code works but only when i have one dash in my subdomain
RewriteCond %{HTTP_HOST} ^(.*)\.rotarytest\.de$
RewriteRule ^(.*)$ http://rotarytest.de/%1%{REQUEST_URI} [L,R=301]

我尝试了在stackoverflow或网上找到的几乎所有解决方案,但它们都没有正确运行。有人能帮忙吗?谢谢您提前。

当规则3只是将此子域重定向到mydomain.de/subdomain-name时,这有什么意义? - Gerben
正如您在我的下面评论中所看到的,我首先想用下划线替换破折号,然后将重写的子域名重定向到一个文件夹:http://mydomain.de/subdomain_previously_with_dashes/a-directory/an-image.png - jmartsch
1个回答

0

您需要允许浏览器不断重定向以去除破折号。如果您不需要将URI中的破折号替换为下划线,则不需要前两个规则,因为它们不适用于主机名。请使用以下规则替换前两个规则:

RewriteCond %{HTTP_HOST} ^(.*)-(.*)$
RewriteRule ^(.*)$ http://%1_%2/$1 [L,R=301]

那只能部分地起作用。破折号被替换为下划线,但是我接下来的规则应该适用于重写后的URI,以便我获得http://mydomain.de/subdomain_previously_with_dashes/a-directory/an-image.png。因此,我删除了您规则中的L标签,但是破折号没有被替换。 - jmartsch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接