我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
当前回答
如果你正在使用亚马逊Web服务弹性负载均衡器,它接受https流量并通过http将其路由到你的服务器,这里描述了将所有http流量重定向到https的正确方法:https://aws.amazon.com/premiumsupport/knowledge-center/redirect-http-https-elb
使用X-Forwarded-Proto报头(包含http或https),它总是包含在来自负载均衡器的http请求中,如下所述:https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html
在httpd.conf文件中:
<VirtualHost *:80>
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
</VirtualHost>
或者在你的根文件。htaccess中:
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
好处:它不会尝试重定向本地开发机器上的http流量。
其他回答
如果你正在使用Apache, mod_rewrite是最简单的解决方案,网上有很多关于如何做到这一点的文档。例如:http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html
我建议用301重定向:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
要将所有http请求重定向到https,您可以使用:
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]
如果mod-rewrite没有启用,并且你在apache 2.4上,你也可以在If指令中使用Redirect将http请求重定向到https。
Apache 2.4。
<if "%{HTTPS} !~ /on/">
Redirect / https://www.example.com/
</if>
如果你正在使用亚马逊Web服务弹性负载均衡器,它接受https流量并通过http将其路由到你的服务器,这里描述了将所有http流量重定向到https的正确方法:https://aws.amazon.com/premiumsupport/knowledge-center/redirect-http-https-elb
使用X-Forwarded-Proto报头(包含http或https),它总是包含在来自负载均衡器的http请求中,如下所述:https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html
在httpd.conf文件中:
<VirtualHost *:80>
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
</VirtualHost>
或者在你的根文件。htaccess中:
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
好处:它不会尝试重定向本地开发机器上的http流量。
我发现了一种方法,强制我的网站的所有页面从http重定向到https的模拟页面,为我工作。
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]