如何使用htaccess从www重定向到https www?

时间:2015-04-08 18:38:18

标签: apache .htaccess redirect mod-rewrite

我需要做以下事情: 我目前的地址如下:https://www.domain.com

我想用htaccess重定向: www.domain.com致https://www.domain.comhttp://domain.comhttps://www.domain.com

我在这里尝试了一些建议,但它最终得到了无限循环。 我试过了:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.domain.com [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]

任何帮助将不胜感激。

更新:我想我已经完成了以下工作:

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]

这是正确的方法吗?

4 个答案:

答案 0 :(得分:4)

您可以在单个规则中实现这两个重定向:

RewriteEngine On 

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

答案 1 :(得分:2)

您的域名条件前面应该!

### Redirect non-www => www ###
RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]

因为你想说,做下一个规则,如果这个条件匹配......并且条件应该是主机 NOT 匹配你想要的。

如果我把它与之前看过和使用的技术混合在一起,你可以试试这个:

### Redirect non-www => www ###
RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]

# redirect urls with index.html to folder
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index.html HTTP/
RewriteRule ^(([^/]+/)*)index.html$ https://%{HTTP_HOST}/$1 [R=301,L]

# change // to /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)//(.*) HTTP/ [NC]
RewriteRule ^.*$ https://%{HTTP_HOST}/%1/%2 [R=301,L]

答案 2 :(得分:1)

最好的方法是:

RewriteEngine On
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]

使用%{HTTP_HOST}时,您不需要编写域名

答案 3 :(得分:0)

非WWW到WWW和http到https解决方案:

## Redirecting HTTP to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

## Redirecting non WWW to WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.tld$ [NC]
RewriteRule ^(.*)$ http://www.domain.tld/$1 [R=301,L]
相关问题