通过.htaccess将http重定向到https无效

时间:2013-09-05 02:58:24

标签: apache .htaccess redirect ssl https

我在这里看到过这样的一些问题,但似乎没有答案可行。我似乎无法弄清楚这一点。这是我的代码:

# enable basic rewriting

RewriteEngine on

# enable symbolic links
Options +FollowSymLinks

# Primary Domain - Force the use of "https"
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

# Primary Domain - Force the use of "www"
RewriteCond %{http_host} ^example.org [nc]
RewriteRule ^(.*)$ https://www.example.org/$1 [r=301,nc]

# Primary Domain - .com to .org
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.org/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.org/$1 [R=301,L]

# Primary Domain - .net to .org
RewriteCond %{HTTP_HOST} ^example.net$ [NC]
RewriteRule ^(.*)$ https://www.example.org/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www.example.net$ [NC]
RewriteRule ^(.*)$ https://www.example.org/$1 [R=301,L]

每当我转到www.example.orghttp://www.example.org时,它都不会重定向。这让我感到沮丧。如果我去example.org或任何其他重定向,它可以工作。我设置错了吗?

另外,如果它显示“HTTP_HOST”,我会保留原样吗?我喜欢用我的http主机替换它吗?

1 个答案:

答案 0 :(得分:1)

Amie如果您想强制wwwhttps,您可以检查是否缺少www。或检查https是否 On然后重定向。所以无论哪种方式,它都会重定向。示例

# Primary Domain - Force the use of "https" and www
RewriteCond %{HTTP_HOST} !^www\. [OR]
RewriteCond %{HTTPS} !^on$
RewriteRule ^(.*)$ https://www.mydomain.org/$1 [R=301,L]

将mydomain.org替换为您的域名。

然后你就可以得到像这样的htaccess文件。我采用了最后两条规则并将它们组合在一起,因此您有一个较小的htaccess文件。

# enable basic rewriting
RewriteEngine on

# enable symbolic links
Options +FollowSymLinks

# Primary Domain - Force the use of "https" and www
RewriteCond %{HTTP_HOST} !^www\. [OR] 
RewriteCond %{HTTPS} !^on$
RewriteRule ^(.*)$ https://www.mydomain.org/$1 [R=301,L]

# Primary Domain - .com to .org Or .net to .org
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.(net|com)$ [NC]
RewriteRule ^(.*)$ https://www.mydomain.org/$1 [R=301,L]

  

另外,如果它显示“HTTP_HOST”,我会保留原样吗?就像我一样   用我的http主机替换它?

%{HTTP_HOST}是一个变量,它包含从浏览器发送的带有Http标头的主机。因此,如果有人请求http://mydomain.org/somepage.php变量%{HTTP_HOST}将包含mydomain.org。你不要改变它。您可以使用它来匹配事物或设置条件中的条件。希望这能回答你的问题。