【问题标题】:Redirecting *.domain.com to www.domain.com with HTTP or HTTPS prefix使用 HTTP 或 HTTPS 前缀将 *.domain.com 重定向到 www.domain.com
【发布时间】:2012-03-15 16:14:50
【问题描述】:

下面的代码是一个重定向脚本,如果我的网站的访问者不在 www.domain.com 上(例如,如果他们在 domain.com 或 somesub.domain.com 上),它会将他们重定向到 www.domain.com。我对其进行了修改,将它们重定向到 HTTPS 或 HTTP,具体取决于他们键入或(热)链接到的链接。

它正在工作,但我猜可能有更简单的方法可以做到这一点,或者还有一些改进的空间。有人可以对此进行仔细检查/评论吗?非常感谢。

# redirect any HTTP traffic that is not http://www.domain.com/*
RewriteEngine On
RewriteCond %{SERVER_PORT} ^80$
RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]

# redirect any HTTPS traffic that is not https://www.domain.com/*  
RewriteEngine On
RewriteCond %{SERVER_PORT} ^443$
RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]

【问题讨论】:

    标签: apache .htaccess redirect


    【解决方案1】:
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
    RewriteCond %{HTTPS}s ^on(s)|
    RewriteRule .* http%1://www.domain.com/$0 [R=301,L]
    

    【讨论】:

    • 感谢您的回答!您能解释一下新的第 3 行和修改的第 4 行吗?我想了解它的作用..
    • %{HTTPS} 在 https 的情况下包含 on。因此,通过在 https 的情况下添加 s 它将匹配 on(s) 并且 %1 将包含 s 并且 %1 将是空的,如果不是。所以在第 4 行你要么有 http,要么有 https.
    • 完美运行,非常感谢您提供更好的脚本和有用的信息!
    • 我知道这是旧的,但你能解释一下| 管道字符在这个正则表达式中的作用吗?
    • @billynoah 没有|(或)在使用常规 http 时,RewriteCond 将不匹配,因此不会应用 RewriteRule。通过使用|(或)你说'字符串必须以ons或(|)不是'。因此条件始终为真,但 %1 将根据使用的是 https 还是 http 具有不同的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多