nginx配置http(80)自动跳转到https(443)分两种情况,一是,单个域名80端口重定向到443端口,二是,泛域名的80端口重定向到443端口,如何启用https访问可参考网址:针对这两种情况分别进行介绍。
1. 单域名配置
将访问单域名 www.example.com 的80端口重定向到443端口,只需在80端口配置中增加一条跳转命令:rewrite ^(.*)$ https://${server_name}$1 permanent;
即可实现访问单域名http自动跳转到https的功能,配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| server { listen 80; server_name www.example.com; rewrite ^(.*)$ https://${server_name}$1 permanent; }
server { listen 443 ssl; server_name www.example.com;
ssl_certificate /opt/cert/www.example.com.pem; ssl_certificate_key /opt/cert/www.example.com.key; ssl_session_timeout 5m; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=31536000";
location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
|
2. 泛域名配置
将访问泛域名*.example.com的80端口重定向到443端口,只需在80端口配置中增加一条跳转命令:return 301 https://$http_host$request_uri;
即可实现泛域名http自动跳转到https的功能,配置如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| server { listen 80; server_name *.example.com; return 301 https://$http_host$request_uri; }
server { listen 443 ssl; server_name *.example.com;
ssl_certificate /opt/cert/www.example.com.pem; ssl_certificate_key /opt/cert/www.example.com.key; ssl_session_timeout 5m; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=31536000";
location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
|
检查配置文件
重启nginx服务