本文介紹 Nginx 訪問 HTTP 跳轉 HTTPS 的 4 種配置方式。html
Nginx rewrite 有四種 flag:瀏覽器
要使用 HTTP 跳轉 HTTPS,固然是須要 301 跳轉,即便用 permanent 這個標籤:服務器
rewrite ^(.*) https://$server_name$1 permanent;
提醒:以上配置涉及到三個本文並未說起的點:rewrite 用法、全局變量、正則匹配。ui
Nginx 使用 ruturn ${http_code} 指定對應狀態碼的處理。這裏咱們使用 return 301 指定 301 重定向的目標:url
return 301 https://$server_name$request_uri;
當 server 只容許 HTTPS 請求時,基於 HTTP 的訪問會被 Nginx 返回 497 錯誤。這時咱們使用 error_page 將訪問重定向至 HTTPS 上:code
error_page 497 https://$server_name$request_uri;
還有一種方式是,返回一個寫入 meta 標籤的 html 頁面,讓瀏覽器跳轉。和上面三種方式不一樣,此方案不在 Nginx 上進行跳轉,節約服務器資源,而缺點是不能寫入 $request_uri 變量,只能跳轉到固定地址。server
server { ... index meta.html; error_page 404 meta.html; }
在要返回的 meta.html 中寫入:htm
<html> <meta http-equiv="refresh" content="0; url=${你要跳轉的目標地址}"> </html>
本站就使用這個方案,因此我是這樣寫的:資源
<html> <meta http-equiv="refresh" content="0; url=https://sometimesnaive.org/"> </html>