我想将所有http请求重定向到https,并将所有www请求重定向到非www

时间:2013-04-24 23:46:27

标签: .htaccess mod-rewrite

这是我当前的.htaccess文件:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
</IfModule>

我想将所有http请求重定向到https,并将所有www请求重定向到非www,并将所有文件请求重定向到index.php

例如:

http://www.example.comhttps://example.com

https://www.example.comhttps://example.com

http://example.com/file.phphttps://example.com/index.php

除了www部分,一切似乎都在工作..请帮忙吗?

2 个答案:

答案 0 :(得分:2)

  

http://www.example.comhttps://example.com
  https://www.example.comhttps://example.com
  http://example.com/file.phphttps://example.com/index.php

也许这会奏效:

RewriteEngine On

# Remove www from https requests. 
# Next 3 lines must be placed in one .htaccess file at SSL root folder, 
# if different from non-ssl.
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST}  ^www\.(.+) [NC]
RewriteRule ^(.*) https://%1/$1 [R=301,L]

# Redirect all http to https
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (?:www\.)?(.+)  [NC]
RewriteRule ^(.*) https://%1/$1     [R=301,L]

如果不起作用,请尝试替换

RewriteCond %{HTTPS} offon

RewriteCond %{HTTP:X-Forwarded-SSL} offon

答案 1 :(得分:1)

您可以添加一个处理www部分的附加规则

RewriteCond %{HTTP_HOST} ^www\.(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [L,R]

RewriteCond会抓取www.之后的所有内容,并将RewriteRule中的内容用作%1

如果一切正常,您可以将R更改为R=301

在启用301的情况下

从不测试,请参阅此答案 Tips for debugging .htaccess rewrite rules 详情。