网站启用SSL自动301跳转到HTTPS教程
12502021-03-26
Apache自动跳转到 HTTPS
打开网站根目录 .htaccess文件(如果不存在则新建)
Markup
RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R,L]
或者:
PHP
RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^(.*) https://%{SERVER_NAME}/$1 [R,L]
301跳转:(推荐)
Markup
<IfModule mod_rewrite.c>RewriteEngine on RewriteBase / RewriteCond %{SERVER_PORT} !^443$ RewriteRule (.*) https://%{SERVER_NAME}/$1 [R=301,L]</IfModule>
再或者:
PHP
<IfModule mod_rewrite.c>RewriteEngine On RewriteBase /RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]</IfModule>
站点绑定多个域名,只允许www.talklee.com 跳转
Markup
RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteCond %{HTTP_HOST} ^talklee.com [NC,OR] RewriteCond %{HTTP_HOST} ^www.talklee.com [NC] RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R,L]
###把网址更改为自己的###
高级用法 (可选)
Markup
RewriteEngine on # 强制HTTPS RewriteCond %{HTTPS} !=on [OR] RewriteCond %{SERVER_PORT} 80 # 某些页面强制 RewriteCond %{REQUEST_URI} ^something_secure [OR] RewriteCond %{REQUEST_URI} ^something_else_secure RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L] # 强制HTTP RewriteCond %{HTTPS} =on [OR] RewriteCond %{SERVER_PORT} 443 # 某些页面强制 RewriteCond %{REQUEST_URI} ^something_public [OR] RewriteCond %{REQUEST_URI} ^something_else_public RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
Nginx 自动跳转到HTTPS
方法一:
Markup
rewrite ^(.*)$ https://$host$1 permanent;
方法二:
适用于 80端口和443 配置在同一个 server{}内
Markup
if ($server_port = 80) { rewrite ^(.*)$ https://$host$1 permanent; }
其他情况, 站点绑定很多域名,只让某个域名跳转:
Markup
set $redirect_https 1; if ($server_port = 80) { set $redirect_https "${redirect_https}2"; } if ($http_host = 'www.talklee.com') { set $redirect_https "${redirect_https}3"; } if ($http_host = 'talklee.com') { set $redirect_https "${redirect_https}3"; } if ($redirect_https = "123") { rewrite ^(.*)$ https://$host$1 permanent; }
配置示例:
Markup
server { listen 80; server_name www.talklee.com; rewrite ^ https://$http_host$request_uri? permanent; } server { listen 443; ssl on; ssl_certificate /etc/ssl/cacert.pem; ssl_certificate_key /etc/ssl/privkey.pem; server_name www.talklee.com; server_tokens off; location / { fastcgi_param HTTPS on; fastcgi_param HTTP_SCHEME https; } }
关于配置有些网站因为开启了伪静态某些规则已经存在,那么删除相同的代码即可,然后保存,查看是否跳转成功,未成功的可以留言给我,一起研究一起学习。Nginx可能比较难,因为不能向Apache那样可以新建文本来实现,nginx只能在配置文件修改,如果有有错误就可能导致网站无法打开或者出现500等错误代码,所以修改配置文件之前一定要先备份,备份,再备份。