【问题标题】:htaccess redirect subdomain to directoryhtaccess 将子域重定向到目录
【发布时间】:2018-04-04 15:01:18
【问题描述】:

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

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

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

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

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

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

但是! example.com/discover/foo 应该转到example.com/bar/foo(英文和法文的网址结尾相同)

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

Redirect 301 /discover/foo /bar/otherfoo

成功将example.com/discover/foo 重定向到example.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]

【问题讨论】:

    标签: .htaccess redirect subdomain


    【解决方案1】:

    首先是这些规则:

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

    应该是这样的:

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

    为了捕获机器人对子域的 www 和非 www 请求。

    还有这条规则:

    Redirect 301 /discover/foo /bar/foo
    

    将同时捕获对域和子域的请求,并在此处使用 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]
    

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

    【讨论】:

    • 谢谢!但是关于最后两行,这会将发现/之后的任何内容重定向到 bar/ 对吗?我怎样才能更具体?我正在更新我的示例,因为有时,蛞蝓可能会有所不同(而不是保持“foo”)
    • @CécileHabran 我在想你想用 bar 替换任何 discover ,现在测试一下
    • Mh,适用于英语(没有子域)但不适用于 fr。我从 htaccess 中删除了所有 301 重定向,但它只显示 404。第一个重定向 RewriteCond %{HTTP_HOST} ^(www\.)?fr\.example\.com [NC] RewriteRule (.*) http://example.com/fr/$1 [L,R=301] 有效
    • 我已经清除了它,但我又清除了它并在另一个浏览器中进行了测试。 RewriteCond %{HTTP_HOST} ^(www\.)?(fr)\.example\.com [NC] RewriteRule ^discover/foo http://example.com/%2/bar/foo [L,R=301] 什么都不做:/
    • 我编辑了这个问题,因为它可能有用,它是一个 wordpress 安装
    猜你喜欢
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 2012-09-07
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多