通过htaccess强制非www和https

时间:2011-06-14 16:55:37

标签: .htaccess mod-rewrite https no-www

我正在尝试强制用户重定向到非www网站,并强制https。

我有这样的工作,但在输入http时不强制https。

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://site.com\.net/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

关于我做错的任何想法?

3 个答案:

答案 0 :(得分:34)

尝试此规则:

RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]

答案 1 :(得分:5)

基于Gumbo的评论:"建立TLS / SSL连接并在证书传真到HTTP之前验证证书并进行HTTP重定向" 我尝试了一下(似乎有效):

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

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

请告诉我这种方法是否有问题。

答案 2 :(得分:0)

对我有用的唯一规则是以下

# match any URL with www and rewrite it to https without the www
    RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
    RewriteRule (.*) https://%2%{REQUEST_URI} [R=301,L]

# match non https and redirect to https
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

顺序很重要,在某些情况下会阻止第三次重定向。