htaccess 将子域重定向到目录

htaccess redirect subdomain to directory

我需要帮助在我的 htaccess 文件中编写正确的重写规则。

我需要将 fr.example.com 之类的内容重定向到 example.com/fr,因为我们最近更改了整个网站并且多语言系统的管理方式不同。结构和页面也是如此。

我用这段代码成功地做到了:

RewriteCond %{HTTP_HOST} ^fr\.example\.com [NC]
RewriteRule (.*) http://example.com/fr/ [L,R=301]

我现在的问题是为页面写一些更具体的东西,例如:

fr.example.com/discover/foo 应该转到 example.com/fr/bar/foo(不同的路径,没有任何一致)

但是! example.com/discover/foo 应该转到 example.com/bar/foo(url 的结尾在英语和法语中是相同的)

现在,由于我有一些常见的 301 重定向,法语 url 无法正确重定向并导致英文页面。例如那个:

Redirect 301 /discover/foo /bar/otherfoo

成功重定向 example.com/discover/fooexample.com/bar/otherfoo 但也重定向 fr.example.com/discover/otherfoo

如何为英语和法语编写两个不同的规则?我将不得不编写一堆不同的规则,因为从旧子域到新目录的一切都非常不同,我不介意。

谢谢!

编辑

请注意,这是针对 wordpress 安装的,htaccess 开头为:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

首先是这些规则:

RewriteCond %{HTTP_HOST} ^fr\.example\.com [NC]
RewriteRule (.*) http://example.com/fr/ [L,R=301]

应该是这样的:

RewriteCond %{HTTP_HOST} ^(www\.)?fr\.example\.com [NC]
RewriteRule (.*) http://example.com/fr/ [L,R=301]

为了捕获 bot www 和 non-www 对子域的请求。

还有这条规则:

Redirect 301 /discover/foo /bar/foo

将捕获对域和 sub-domains 的请求,这里使用 mod_rewrite 是正确的,而不是 mod_alias 所以,将此行替换为 :

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC]
RewriteRule ^discover/foo http://example.com/bar/foo [L,R=301]
RewriteCond %{HTTP_HOST} ^(www\.)?(fr)\.example\.com [NC]
RewriteRule ^discover/foo http://example.com/%2/bar/foo [L,R=301]

注意:清除浏览器缓存然后测试。