【问题标题】:Apache: Redirect all requests to https://www.domain.tldApache:将所有请求重定向到 https://www.domain.tld
【发布时间】:2017-11-05 14:14:49
【问题描述】:

我找不到适合我的解决方案。

这里是我的设置:

# Redirect non-www to www
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# Redirect http to https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

每个部分都很好,但不能一起使用。 https 重定向的部分总是重定向到https://domain.tld,所以没有www,它被忽略了。 有人知道解决方案吗?

提前致谢。

【问题讨论】:

    标签: http web https url-redirection no-www


    【解决方案1】:

    强制HTTPS 并包含WWW

    RewriteEngine On
    RewriteCond %{HTTP_HOST}#%{HTTPS}s !^www\.([^#]+)#(?:off|on(s)) [NC]
    RewriteRule ^$ http%2://www.%1%{REQUEST_URI} [R=301,L]
    

    应该一次性完成,否则您可以将规则分开,并且可能这样:

    # Rewrite to WWW
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*) https://www.%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
    
    # Rewrite HTTP to HTTPS
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*) https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
    

    如果对non-wwwwww 的重写不起作用,那么很可能在服务器上设置的其他地方(可能在httpd.conf 中)有一个VirtualHost 301 重定向......它看起来类似于这样:

    httpd.conf

    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
        RewriteRule ^(.*)$ https://example.com$1 [L,R=301]
    </IfModule>
    

    如果在httpd.conf 中设置了它,它可以覆盖.htaccess 中将non-www 重写为www

    【讨论】:

    • “不起作用”什么也没解释……这是什么行为?
    • http://domain.tld https://domain.tld and https://www.domain.tld redirect to http://www./http://www.domain.tld -&gt; 404 Page Not Found
    • 重写循环,仅 https 部分 -> ERR_TOO_MANY_REDIRECTS,仅 www 部分 -> 重写循环
    • 我的主机好像有问题,只有没有www才有可能。让我们看看支持者会怎么说。非常感谢您的帮助 l'L'l
    • 我再次编辑了答案;它可能不会重定向到www,但如果您在其他地方有 301 重定向(可能在虚拟主机设置中)...
    猜你喜欢
    • 2016-10-23
    • 2015-02-14
    • 2013-04-06
    • 2013-11-26
    • 2014-06-30
    • 2018-09-15
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多