【问题标题】:Redirect a subdomain url to a domain url with paramter使用参数将子域 url 重定向到域 url
【发布时间】:2017-05-12 09:24:00
【问题描述】:

我正在使用 htaccess mod-rewrite 将子域 url 重定向到带有参数的域 url,例如:

subdomain.example.com is redirect to example.com?id=subdomain
subdomain.example.com/page is redirect to example.com/page/?id=subdomain
subdomain.example.com/page1/page2 is redirect to example.com/page1/page2/?id=subdomain
subdomain.example.com/page1/page2?pol=abc is redirect to example.com/page1/page2/?id=subdomain&pol=abc

我在 htaccess 中使用此代码:

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

为此域启用了通配符。

当 url 是 subdomain.domain.com 时这很好用,但是当 url 是目录重定向时不起作用。例如,当我在网络浏览器中写地址 subdomain.example.com/page 时,我得到了相同的地址。

【问题讨论】:

    标签: apache .htaccess redirect


    【解决方案1】:

    我不认为你可以让它与一个规则一起工作。

    尝试以下方法:

    RewriteCond %{QUERY_STRING} .
    RewriteCond %{HTTP_HOST} ^(.+)\.example\.com
    RewriteRule ^(.*)$ http://example.com/$1?id=%1&%{QUERY_STRING} [R=302,L,NC]
    
    RewriteCond %{HTTP_HOST} ^(.+)\.example\.com
    RewriteRule ^(.*)$ http://example.com/$1?id=%1 [R=302,L,NC]
    

    您可以使用online htaccess tester 对其进行测试。

    解释:

    1. 行:检查查询字符串是否存在。

    2. 行:检查请求是否定向到子域。

    3. 行:使用从子域名和原始查询字符串构建的查询重写到新地址。

    4. 行:如果不满足之前的重写条件和规则,则继续执行与第3行相同的这一行。但不检查查询字符串是否存在。

    5. 行:以相同方式重写,但不添加原始查询字符串。

    [R=302,L,NC] 代表

    • R=302 - 使用 HTTP 代码 302 重定向 - 临时重定向,以便在您测试时浏览器不会缓存它
    • L - 如果满足此规则,则不处理进一步的规则
    • NC - 以不区分大小写的方式执行检查

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2011-05-04
      • 2012-05-25
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多