
我的 nginx.conf 中有以下內容:
location ~* /collections.*?products/([^/]+)/?$ {
rewrite ^/collections.*?products/([^/]+)/?$ /$1.html;
rewrite ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3;
rewrite ^([^_]*)_(.*)$ $1-$2 permanent;
}
重寫請求,例如
"/collections/products/someproduct/" to "/someproduct.html"
"/collections/products/some_product/" to "/some-product.html"
"/collections/products/some_other_product/" to "/some-other-product.html"
但是,只有當最後一個重寫指令(包含標誌)匹配並處理時,我才能獲得 301 重定向permanent
,例如我的第二個範例。在另外 2 個實例中,我得到了 302 個暫時重定向。如何處理此位置區塊中的這些多個重寫指令並返回 301 重定向,無論哪些指令匹配?如果我在所有重寫指令上放置永久標誌,它將在第一次匹配後停止處理。
答案1
您可以遞歸_
地-
且獨立於rewrite...permanent
.
例如:
location ~* /collections.*?products/([^/]+)/?$ {
rewrite ^(.*)_(.*)$ $1-$2 last;
rewrite ^/collections.*?products/([^/]+)/?$ /$1.html permanent;
}
僅當第一個未能找到更多下劃線rewrite
後才執行第二個。rewrite
看這個文件了解更多。
答案2
您可以將302
狀態代碼視為“異常”,並使用以下命令“捕獲”它http://nginx.org/r/error_page。
location ~* /collections.*?products/([^/]+)/?$ {
rewrite ^/collections.*?products/([^/]+)/?$ /$1.html;
rewrite ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3;
rewrite ^([^_]*)_(.*)$ $1-$2 permanent;
error_page 302 =301 @302to301;
}
location @302to301 {
return 300; # 300 is just a filler here, error_page dictates status code
#return 301 $sent_http_location;
}
技術和我的類似301-302-redirect-w-no-http-body-text.nginx.conf, 按照關於在沒有 HTTP 回應正文的情況下產生 301/302 重定向的相關問題。
請注意,在 中@302to301
,您可以在上面的兩個 return 語句之間進行選擇;但是,該return
程式碼在此處理程序的上下文中無關緊要,因為error_page
上面的指令可確保無論後續程式碼是什麼,所有302
程式碼都會變更為。301
換句話說,return
上述兩個語句之間的唯一區別是 HTTP 回應正文的內容,無論如何,瀏覽器都不會顯示 301 回應,因此,您最好選擇較短的無正文版本return 300
。