nginx做http向https的自动跳转

在访问百度时,在浏览器输入www.baidu.com会自动跳转到https://www.baidu.com不用人工干预,nginx也可以做这样的自动跳转!

首先让nginx服务器监听两个端口,分别是80端口和443端口,注意监听443端口的时候需要配置证书的认证以及创建自签名证书!

关于证书的认证的以及创建自签名的证书,不再叙述(可以查看https://www.cnblogs.com/wxzhe/p/10125513.html了解证书的创建问题),这里只说明nginx的配置问题!

nginx的配置如下,只给出了两个server的配置,可以直接复制到http块中。

 server { #第一个server块,用于监听80端口 listen 80; server_name localhost; location /{ root html; index index.html index.htm; rewrite ^(.*)$ https://$host$1 permanent; #先把这一行注释掉,分别用80端口和443端口访问本机,若是都可以正常访问,添加上这一行即可! } }
    server { #第二个server块,用于监听443端口 listen
443 ssl; server_name localhost; ssl_certificate cert/server.pem; #证书的位置是相对于当前配置文件所在的位置的! ssl_certificate_key cert/server.key; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { root html; index index.html index.htm; } }

这时候在浏览器通过http访问时候,就会自动跳转到https访问!

 

相关文章