这一篇来聊一聊nginx服务器http转成https ,首先我们得先去阿里云上购买SSL证书(0元),然后输入我们的域名,等待一段时间就会通过了,我们下载nginx对应的文件,解压后会有两个文件:.key文件和.pem文件 。
我们把这两个文件传到服务器上并重名一下,放到这nginx
的conf
文件夹里面。
修改一下nginx的配置文件下的 # HTTPS server 下的代码,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 server { listen 443 ssl; #域名,我的是gaosong.site server_name gaosong.site; # 两个文件所在位置 ssl_certificate ssl.pem; ssl_certificate_key ssl.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { #同http一样,这是我们网站的public目录 root /root/blog/public; index index.html index.htm; } }
然后使用上一个博客的测试配置文件是否正常的命令,如果ok的话就重启nginx服务器 。
1 2 3 [root@iZbp1b44670a4o3ks27kznZ nginx]# sbin/nginx -t nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
还有一个太他妈重要的东西,记得在阿里云那边开一下https的443端口!!!
这样我们就可以用https加域名访问了,美滋滋。
还有最后一个问题,如何让http的请求自动转换成https? 我们只需在http的server 下面增加一句话即可,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 # http的server server { listen 80; #我的域名为www.gaosong.site server_name www.gaosong.site; # 增加这一句话,然后重启nginx服务器就可以了 rewrite ^(.*) https://$server_name$1 permanent; location / { #我的博客的公共目录是/root/blog/public root /root/blog/public; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
这样就完成了http转https了,美滋滋呀!