nginx 如何強制跳轉 https

本項目 nginx 作爲代理服務

項目上線,客戶說要加個安全證書 ,於是安全證書是加上了,可是htttp和https都能訪問網站,客戶要求不行必須強制用帶有https的地址訪問

開整

這是 http 和https 都能訪問的 nginx.conf  關鍵配置

 
 
    server {

        listen       80;
        listen       443 ssl;
        
        server_name  xxxxon.com www.xxx.com;
        
        
        ssl_certificate      /usr/local/server/cert/xxx.com_bundle.pem;
        ssl_certificate_key  /usr/local/server/cert/xxx.com.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            proxy_pass http://1x6.1x.1xx.138:8888;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

    }
 

因爲監聽了兩個端口號 導致http和https都能訪問   注:443是監聽ssl證書的端口 80是默認端口

改成以下這樣即可

 
    server {

        listen       80;
        
        server_name  xxxx.com www.xxxx.com;
        
        return 301 https://$server_name$request_uri;
    }
    
    server {

        listen       443 ssl;
        
        server_name  xxxx.com www.xxxx.com;
        
        
        ssl_certificate      /usr/local/server/cert/xxxx.com_bundle.pem;
        ssl_certificate_key  /usr/local/server/cert/xxxx.com.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            proxy_pass http://xxx.xx.xxx.xxx:8888;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }

    }
 

第一個服務端口是監聽80,重定向到帶有https 的協議的端口 也就是下面那一個443端口 

第二個本來就是 ssl端口 不用管控

 

已解決

 

還有一種方式告訴大家,也是無意間知道的 ,用mate頁面刷新的方式

創建個html頁面 ,插入這一句

<html>
<meta http-equiv="refresh" content="0;url=https://baidu.com/">
</html>

當你打開這個頁面的時候 ,自然會重定向到帶有安全證書的百度頁面

這種方式你們可以自由發揮

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章