【轉】nginx調優之使用return代替rewrite做重定向

使用return代替rewrite做重定向

轉自:https://www.jianshu.com/p/26dc6c2b5f43

原文地址:https://github.com/trimstray/nginx-admins-handbook/blob/master/doc/RULES.md#beginner-use-return-directive-instead-of-rewrite-for-redirects

更多nginx文檔:https://weiliang-ms.github.io/nginx/
更多linux相關文檔:https://weiliang-ms.github.io/wl-awesome/

解釋說明

  1. NGINX中重寫url的能力是一個非常強大和重要的特性,從技術角度講returnrewrite均能實現。
    但使用return相對rewrite更簡單和更快,因爲計算RegEx會產生額外的系統開銷。
  2. Return指令可以立即停止處理請求(它直接停止執行)並將指定的代碼返回給客戶端,省略了正則計算的流程。
  3. 如果你需要用regex驗證URL或者需要獲取原始URL中的元素(顯然不在相應的NGINX變量中),那麼你應該使用rewrite

使用樣例

  • 不建議實現方式
server {

...

location / {

    try_files $uri $uri/ =404;

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

}

...

}
  • 建議實現方式
server {

  ...

  location / {

    try_files $uri $uri/ =404;

    return 301 https://example.com$request_uri;

  }

  ...

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