我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
我试图重定向所有不安全的HTTP请求在我的网站(例如http://www.example.com)到HTTPS (https://www.example.com)。我如何在.htaccess文件中做到这一点?
我用的是PHP。
当前回答
这将会有帮助。
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
此外,参考这更多的细节。如何重定向Http到Https?
其他回答
在.htaccess文件中使用以下代码自动将访问者重定向到站点的HTTPS版本:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
如果你有一个现有的。htaccess文件:
不要重复“重写引擎”。
确保以RewriteCond和RewriteRule开头的行立即跟随已经存在的RewriteEngine On。
如果你正在使用Apache, mod_rewrite是最简单的解决方案,网上有很多关于如何做到这一点的文档。例如:http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html
我尝试了所有我能在互联网上找到的。htaccess配置,但没有一个有效。 然后,我意识到Apache不鼓励使用mod_rewrite。
我的解决方案是在以下文件夹下编辑apache配置文件: /etc/apache2/sites-enabled
您将有一个名为000-default.conf的强制文件和一个名为000-default-le-ssl.conf的ssl配置文件(如果您从letsencrypt/certbot安装了ssl证书)。但是,这些文件的名称可能不同,这取决于您在设置网站时提供的文件名。
在000-default.conf中,我在<VirtualHost *:80>中编辑了以下内容:
<VirtualHost *:80>
ServerName example.com
Redirect / https://example.com/
</VirtualHost>
在000-default-le-ssl.conf中,我在<VirtualHost *:80>中编辑了以下内容:
<VirtualHost *:80>
ServerName example.com
Redirect / https://example.com/
</VirtualHost>
不需要其他重定向。
保存文件,然后使用sudo service apache2 restart重启apache服务器
更新:尽管这个答案在几年前就已经被接受了,但请注意,Apache文档现在不建议使用这种方法。改用重定向。请看这个答案。
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
经过多次尝试,考虑没有www和有www,这是可行的
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (www\.)?yourdomain.com
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]