Nginx OpenSSL创建自签证书实现HTTP转HTTPS
创建自签证书
参考:https://blog.csdn.net/qq_15092079/article/details/82149807
安装Nginx并支持SSL
参考:https://www.cnblogs.com/BINGJJFLY/p/10168366.html
80端口跳转指定端口
修改nginx配置文件
vim /usr/local/nginx/conf/nginx.conf
添加80监听
upstream www.test.com { server 127.0.0.1:8080 weight=1; } server { listen 80; server_name www.test.com; location / { proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://www.test.com; } }
HTTP转HTTPS
添加443监听
server { listen 443 ssl; server_name www.test.com;
# 设置证书路径 ssl_certificate /home/ssl/test.crt; # 设置私钥路径
ssl_certificate_key /home/ssl/test.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://www.test.com; } }
用户直接输入域名也跳转HTTPS
调整80监听
server { listen 80; server_name www.test.com;
location / { rewrite ^(.*)$ https://$host$1 permanent; } }
需求可能是部分路径走Http部分走Https
方案一:利用Nginx通配路径
server { listen 80; server_name www.test.com; location / { # 不需要转Https的路径不走重定向 if ($request_uri ~ /ssl/get(.*)$) { proxy_pass http://www.test.com; break; } rewrite ^(.*)$ https://$host$1 permanent; } } upstream www.test.com { server 127.0.0.1:8080 weight=1; } server { listen 443 ssl; server_name www.test.com; ssl_certificate /home/ssl/test.crt; ssl_certificate_key /home/ssl/test.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://www.test.com; } }
方案二:添加新的二级域名
server { listen 80; server_name www.ssl.com; location / { proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://www.ssl.com; } } upstream www.ssl.com { server 127.0.0.1:8080 weight=1; }
遇到的问题
谷歌浏览器HTTPS请求方式访问系统时,浏览器会默认缓存这种方式,再次以HTTP方式请求时浏览器会默认转成HTTPS请求方式,清除浏览器缓存后方能以HTTP请求方式请求