Nginx 配置 HTTPS(多域名)


平常開發要求比較低, 依然在用 HTTP, 但到了微信小程序就不行了, 騰訊和蘋果都對 API 提出了 HTTPS 的要求. 尤其是蘋果, 不僅要求 HTTPS, 還要求 TLS 協議版本要在 1.2 以上, 這又被稱為 App Transport Security(ATS).

關於自己的標准是否滿足 ATS, 可以使用此工具檢測: ATS(App Transport Security)檢測.

-w769

服務器配置

使用 Nginx 進行 HTTPS 配置, 服務器幾乎不用做改動, 依舊是祖傳的 8080 端口, 以我所使用的 Spring Boot 為例, 僅僅是在 application.yml 中增加了兩行配置而已.

server:
    port: 8080
    tomcat:
        protocol_header: x-forwarded-proto
    use-forward-headers: true
    address: 127.0.0.1

證書申請/購買

在域名的基本信息頁, 點擊免費開啟 SSL 證書, 輸入相應的域名, 點擊「申請」即可申請免費的 DV SSL 證書, 還需要做一些簡單的信息補全等, 即可提交申請. 如果備案信息都齊全的話, 很快就可以驗證成功, 在證書管理頁面即可查看證書.
-w1026

-w1174

選擇下載證書for Nginx, 證書一式兩份, 后綴分別為 pemkey, 下載完上傳到服務器.

域名映射

我選擇為兩個子域名申請證書, 同時將這兩個域名映射到同一個IP.

-w1181

Nginx 配置

首先, 需要把 http 都轉發到 https, 需要使用 rewrite, 這樣, 當訪問 http://example.cn 會自動轉發到 https://example.cn.

	server {
	   	listen 80; # redirect to 443
	    	server_name AAA.example.cn www.AAA.example.cn;
	    	rewrite ^(.*)$  https://$host$1 permanent; 
	}

        server {
                listen 80; # redirect to 443
                server_name BBB.example.cn www.BBB.example.cn;
                rewrite ^(.*)$  https://$host$1 permanent;
        }

然后就是真正的 https 部分了, 雖然域名不同, 但都監聽 443 端口, 但有着不同的 server_name, 這樣當收到請求時就可以根據請求的 server_name 不同來轉發到不同的服務.

而服務自身像往常一樣只要繼續監聽 80908091 即可.

	server {
            	listen 443 ssl;
            	server_name AAA.example.cn www.AAA.example.cn;    

            	ssl_certificate "/home/yushan/demontf/2076603_AAA.example.cn.pem";   
            	ssl_certificate_key "/home/yushan/demontf/2076603_AAA.example.cn.key";    
            
            	location / {
                			proxy_pass http://127.0.0.1:8090;
                			proxy_set_header X-Real-IP $remote_addr;
                			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                			proxy_set_header Host $http_host;
                			proxy_set_header X-NginX-Proxy true;
                			proxy_redirect default;
		}
	}


	server {
    		listen 443 ssl; # redirect to https
    		server_name BBB.example.cn www.BBB.example.cn;
    		
    		ssl_certificate "/home/yushan/demontf/2005538_BBB.example.cn.pem";
    		ssl_certificate_key "/home/yushan/demontf/2005538_BBB.example.cn.key";
    		
    		location / {
    		              proxy_pass http://127.0.0.1:8091;
    		              proxy_set_header X-Real-IP $remote_addr;
    		              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    		              proxy_set_header Host $http_host;
    		              proxy_set_header X-NginX-Proxy true;
    		              proxy_redirect default;
    		}
	}

配置修改好之后, 需要重啟 Nginx.

參考

Nginx 配置 HTTPS 服務器 | Aotu.io「凹凸實驗室」
阿里雲+Https+Nginx+SpringBoot | tt_study


免責聲明!

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



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