我有以下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。


当前回答

类似于Amir Forsati的解决方案htaccess重定向到https://www,但对于变量域名,我建议:

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

其他回答

这是我为代理用户和非代理用户找到的最好的方法

RewriteEngine On

### START WWW & HTTPS

# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

### END WWW & HTTPS

要将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开始就可以使用了。

在你的。htaccess文件中设置

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

我使用了下面的代码从这个网站,它工作得很好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]

希望能有所帮助

michal的回答对我很有效,尽管做了一个小小的修改:

问题:

当您只有一个站点安全证书时,浏览器试图访问您的页面而没有https:// www。(或证书覆盖的任何域)将显示一个丑陋的红色警告屏幕,甚至在接收到安全正确的HTTPS页面的重定向之前。

解决方案

首先使用重定向到www(或证书覆盖的任何域名),然后才进行https重定向。这将确保您的用户不会遇到任何错误,因为您的浏览器看到的证书不包含当前url。

#First rewrite any request to the wrong domain to use the correct one (here www.)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]