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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM