http://example.com,http://www.example.com和https://example.com到https://www.example.com

时间:2015-10-18 06:05:27

标签: .htaccess mod-rewrite redirect https

关于Stack Overflow的第二个问题!我们的目标是将我们网站的所有请求永久重定向到https://www.example.com。我们目前使用以下代码将http://example.comhttp://www.example.com重定向到https://www.example.com,但是,在Stack Overflow花了很长时间寻找解决方案之后,我们还没有找到办法还要将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]

2 个答案:

答案 0 :(得分:1)

最好在一条规则中处理这个问题:

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

答案 1 :(得分:0)

为了补充@ 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;
}