.htaccess http://example.com, http://www.example.com 及https://example.com 到https://www.example.com

.htaccess http://example.com, http://www.example.com 及https://example.com 到https://www.example.com,.htaccess,mod-rewrite,redirect,https,.htaccess,Mod Rewrite,Redirect,Https,关于堆栈溢出的第二个问题!我们的目标是将我们网站的所有请求永久重定向到https://www.example.com。我们目前有以下代码用于重定向http://example.com和http://www.example.com至https://www.example.com,但是,在花了相当长的时间在堆栈溢出上寻找解决方案之后,我们还没有找到一种方法来重定向https://example.com至https://www.example.com。非常感谢你的帮助 RewriteEngine On

关于堆栈溢出的第二个问题!我们的目标是将我们网站的所有请求永久重定向到
https://www.example.com
。我们目前有以下代码用于重定向
http://example.com
http://www.example.com
https://www.example.com
,但是,在花了相当长的时间在堆栈溢出上寻找解决方案之后,我们还没有找到一种方法来重定向
https://example.com
https://www.example.com
。非常感谢你的帮助

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

最好用一条规则来处理这个问题:

RewriteEngine On

# add www and force https in same rule
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=302,L,NE]
  • 把这条规则作为你的第一条规则
  • 在测试浏览器缓存之前,请确保清除它
  • 测试后,将
    302
    更改为
    301

为了补充@anubhava针对Apache的优雅解决方案,我们最近在Nginx上找到了一种方法:

server {
        listen 80;
        server_name example.com;
        return 301 https://www.example.com$request_uri;
}
server {
        listen 80;
        server_name www.example.com;
        return 301 https://www.example.com$request_uri;
}
server {
        listen 443;
        server_name example.com;
        return 301 https://www.example.com$request_uri;
}

[L]标志导致mod_rewrite停止处理规则集。