nginx将http升级到https并且同时支持http和https两种请求、http自动转向https

1、http升级到https

1.1、检查 Nginx 是否支持 SSL

/usr/local/nginx/sbin/nginx  -V
configure arguments中是否有--with-http_ssl_module
如:
nginx version: nginx/1.13.4
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --with-http_ssl_module

1.2、为nginx添加SSL 模块

1)进入nginx安装目录执行:
./configure --with-http_ssl_module 
然后,注意不要make install
make
2)备份原 Nginx 执行脚本
mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old
3)将新版本 Nginx 编译脚本放到可执行文件目录下
cd objs/ cp nginx /usr/local/nginx/sbin/
4)进行平滑升级
make upgrade
再次检查是否安装成功:
/usr/local/nginx/sbin/nginx -V 

1.3、修改nginx配置

cd /usr/local/nginx/conf
vim nginx.conf 
server{
        listen 88;
        listen 443 ssl;
        ssl on;
        ssl_certificate     /etc/nginx/nginx.nopasswd.crt;   ##证书.crt
        ssl_certificate_key /etc/nginx/nginx.nopasswd.key;   ##证书.key
        server_name  ****;
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
                root   html;
        }
        location / {
               try_files $uri $uri/ /index.html;
               root  /var/www/test;
              index  index.html index.htm;
        }
        location ~ /api/(.*)$ {
            proxy_pass http://****/$1?$query_string;
            proxy_set_header Host $http_host;
            proxy_set_header X-Forward-For $remote_addr;
        }
    
    }

注意:https需要SSL证书,可以到阿里云或腾讯云申请免费版,有效期一年

2、同时支持http和https两种请求

server{
        listen 88;
        listen 443 ssl;
        # ssl on;
        ssl_certificate     /etc/nginx/nginx.nopasswd.crt;
        ssl_certificate_key /etc/nginx/nginx.nopasswd.key;
......

将ssl on;注释就可以了,其中http访问88端口,而https访问443端口(http默认80端口,https默认443端口)

3、http自动转向https

nginx配置新增server的配置

 server {
        listen 80;
        server_name 你的域名;
        rewrite ^(.*)$ https://$host$1 permanent;
}

 

posted @ 2019-11-25 14:04  Jade_g  阅读(7324)  评论(0编辑  收藏  举报