使用return代替rewrite做重定向
轉自:https://www.jianshu.com/p/26dc6c2b5f43
更多nginx文檔:https://weiliang-ms.github.io/nginx/
更多linux相關文檔:https://weiliang-ms.github.io/wl-awesome/
解釋說明
NGINX
中重寫url
的能力是一個非常強大和重要的特性,從技術角度講return
與rewrite
均能實現。
但使用return
相對rewrite
更簡單和更快,因爲計算RegEx
會產生額外的系統開銷。Return
指令可以立即停止處理請求(它直接停止執行)並將指定的代碼返回給客戶端,省略了正則計算的流程。- 如果你需要用
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;
}
...
}