我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
当前回答
在.htaccess文件中添加以下代码:
Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^ https://[your domain name]%{REQUEST_URI} [R,L]
其中[您的域名]是您网站的域名。
你也可以重定向特定的文件夹从你的域名通过替换上面的最后一行代码:
RewriteRule ^ https://[your domain name]/[directory name]%{REQUEST_URI} [R,L]
其他回答
除非你需要mod_rewrite做其他事情,使用Apache核心IF指令更干净更快:
<If "%{HTTPS} == 'off'">
Redirect permanent / https://yoursite.com/
</If>
你可以在IF指令中添加更多的条件,比如确保一个没有www前缀的规范域:
<If "req('Host') != 'myonetruesite.com' || %{HTTPS} == 'off'">
Redirect permanent / https://myonetruesite.com/
</If>
使用mod_rewrite做任何事情都有很多熟悉的惯性,但看看这是否适合你。
更多信息:https://httpd.apache.org/docs/2.4/mod/core.html#if
要看到它的行动(尝试没有www。或https://,或用。net代替。com): https://nohodental.com/(我正在做的一个网站)。
如果你正在使用Apache, mod_rewrite是最简单的解决方案,网上有很多关于如何做到这一点的文档。例如:http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html
更新:尽管这个答案在几年前就已经被接受了,但请注意,Apache文档现在不建议使用这种方法。改用重定向。请看这个答案。
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
我发现了一种方法,强制我的网站的所有页面从http重定向到https的模拟页面,为我工作。
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
经过多次尝试,考虑没有www和有www,这是可行的
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (www\.)?yourdomain.com
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]