我有以下htaccess代码:

<IfModule mod_rewrite.c>

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

</IfModule>

我希望我的网站被重定向到https://www。使用HTTPS,并强制执行www。子域名, 但当我访问http://www时。(没有HTTPS),它不会重定向到https://www与HTTPS。


当前回答

如果您正在使用CloudFlare或类似的CDN,您将得到一个无限循环错误的%{HTTPS}解决方案提供在这里。如果你是CloudFlare用户,你需要使用这个:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

其他回答

要将http://或https://重定向到https://www,您可以在所有版本的apache上使用以下规则:

RewriteEngine on

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

Apache 2.4

RewriteEngine on

RewriteCond %{REQUEST_SCHEME} http [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,L,R]

注意,%{REQUEST_SCHEME}变量从apache 2.4开始就可以使用了。

有很多解决方案。这里有一个apache wiki的链接,它直接处理了这个问题。

http://wiki.apache.org/httpd/RewriteHTTPToHTTPS

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in httpd.conf
# or .htaccess context

我使用了下面的代码从这个网站,它工作得很好https://www.freecodecamp.org/news/how-to-redirect-http-to-https-using-htaccess/

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

希望能有所帮助

如果你使用CloudFlare,请确保你使用这样的东西。

# BEGIN SSL Redirect
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
# END SSL Redirect

这将使您免于重定向循环,并将您的站点安全地重定向到SSL。

附注:如果检查mod_rewrite.c!

我试着第一个回答,它不工作… 这项工作:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress