2019年4月9日 星期二

Nginx HTTP 自動轉址到 HTTPS

[情況1]:HTTP 和 HTTPS 使用不同 PORT
例如,分別使用預設的 80、443 PORT
http://example.com 的網址要強制轉到 https://example.com
可直接在 HTTP 的設定中,return 301 轉址到 HTTPS
server {
    listen 80;
    
    server_name example.com;

    #301永久轉址,轉址時,改變Request Method為GET,無法保留POST資料
    return 301 https://$host$request_uri;
    #308永久轉址,轉址時,不改變Request Method,能保留POST資料
    #return 308 https://$host$request_uri;
}
server {
    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    server_name example.com;
}



[情況2]:將原本 HTTP 使用的 PORT,直接改給 HTTPS 使用。
修改前後 HTTP、HTTPS 使用相同的 PORT,例如都使用 8080 PORT
處理方式:若在 HTTPS 的 PORT 上,使用 HTTP 訪問,會出現 error_page 497 的錯誤。當發生此錯誤時,將頁面轉址到 HTTPS 的網址。
server {
    listen 8080 ssl;
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;

    server_name example.com;

    #預設302暫時轉址,轉址時,改變Request Method為GET,無法保留POST資料
    error_page 497 https://$host:$server_port$request_uri;
    #改為307暫時轉址,轉址時,不改變Request Method,能保留POST資料
    #error_page 497 =307 https://$host:$server_port$request_uri;
}



[301、308、302、307 重新導向差異]
301:永久轉址,轉址時,改變Request Method為GET,無法保留POST資料。
308:永久轉址,轉址時,不改變Request Method,能保留POST資料。
302:暫時轉址,轉址時,改變Request Method為GET,無法保留POST資料。

3 則留言: