【问题标题】:Redirect to https and www with one 301 redirect使用一个 301 重定向重定向到 https 和 www
【发布时间】:2017-08-25 02:17:18
【问题描述】:

全部

我想将所有请求重定向到https://www URL,例如

case1: http://www.example.com --301--> https://www.example.com
case2: https://example.com    --301--> https://www.example.com
case3: http://example.com     --301--> https://www.example.com

我的代码在 .htaccess 文件中

RewriteCond %{HTTPS} off     
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

在情况 1 和 2 中工作正常。但是,当我有一个 http 和非 www 请求 (case3) 时,它将需要两个 301 重定向才能登陆https://www

http://example.com 
--301--> 
https://example.com 
--301--> 
https://www.example.com

我们怎样才能强制 https 和 www 总是只有 1 301 重定向。

我对 Apache 和重写模块不是很熟悉。请帮忙!

【问题讨论】:

    标签: apache .htaccess mod-rewrite


    【解决方案1】:

    要在单个请求中重定向到https://www,您可以使用:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^www\. [OR]
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
     RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R=301]
    

    【讨论】:

    • 如果您想将所有请求重定向到 https 但非 www,您能帮我吗?
    • @Jerry 您可以修改代码,从 RewriteCondition 中删除 ! 并从 Rewrite destination 中删除 www(最后一行)。跨度>
    猜你喜欢
    • 2017-06-17
    • 2017-05-03
    • 2018-10-19
    • 2020-05-22
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    相关资源
    最近更新 更多