Nginx 配置 HTTP 跳轉 HTTPS-Linux運維日誌

本文介紹 Nginx 訪問 HTTP 跳轉 HTTPS 的 4 種配置方式。html

rewrite

Nginx rewrite 有四種 flag:瀏覽器

  • break:在一個請求處理過程當中將原來的 url 改寫以後,再繼續進行後面的處理,這個重寫以後的請求始終都是在當前這一個 location 中處理
  • last:至關於一個新的 request,須要從新走一遍 server,提供了一個能夠轉到其餘 location 的機會
  • redirect:表示 302 temporarily redirect
  • permanent:表示 301 permanently redirect

要使用 HTTP 跳轉 HTTPS,固然是須要 301 跳轉,即便用 permanent 這個標籤:服務器

rewrite  ^(.*)  https://$server_name$1 permanent;

提醒:以上配置涉及到三個本文並未說起的點:rewrite 用法、全局變量、正則匹配。ui

301 狀態碼

Nginx 使用 ruturn ${http_code} 指定對應狀態碼的處理。這裏咱們使用 return 301 指定 301 重定向的目標:url

return  301  https://$server_name$request_uri;

497 狀態碼

當 server 只容許 HTTPS 請求時,基於 HTTP 的訪問會被 Nginx 返回 497 錯誤。這時咱們使用 error_page 將訪問重定向至 HTTPS 上:code

error_page  497  https://$server_name$request_uri;

meta

還有一種方式是,返回一個寫入 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>
相關文章
相關標籤/搜索