Nginx重定向的參數問題
在給某網站寫rewrite重定向規則時,碰到了這個關於重定向的參數處理問題。默認的狀況下,Nginx在進行rewrite後都會自動添加上舊地址中的參數部分,而這對於重定向到的新地址來講多是多餘。雖然這也不會對重定向的頁面顯示結果形成多少影響,但當你注意到新地址中包含有多餘的「?xxx=xxx」時,內心總仍是會以爲不爽。並且可能影響到網站的搜索優化SEO。那麼該如何來處理這部分的內容呢?看了下面兩個簡單的例子你就會明白了。
例如:
把http://example.com/test.php?id=xxx 重定向到 http://example.com/xxx.html
把我鬱悶了很久,最後在谷大神那裏找到了一片文章解決了。
這是剛開始的規則:
if ($query_string ~* "id=(\d+)$") {
set $id $1;
rewrite /art_list\.php /article/category-$id.html permanent;
rewrite ^/goods\.php /goods/$id.html permanent;
rewrite ^/category\.php /products/$id.html permanent;
rewrite ^/child_cat\.php /category/$id.html permanent;
rewrite ^/art\.php /article/$id.html permanent;
rewrite ^/art_list\.php /article/category-$id.html permanent;
rewrite ^/artid\.php /help/$id.html permanent;
rewrite ^/article\.php /affiche/$id.html permanent;
}
發現問題:
重定向的地址都是 xxx.html?id=xxx
最後我修改了參數:
if ($query_string ~* "id=(\d+)$") {
set $id $1;
rewrite /art_list\.php /article/category-$id.html? permanent;
rewrite ^/goods\.php /goods/$id.html? permanent;
rewrite ^/category\.php /products/$id.html? permanent;
rewrite ^/child_cat\.php /category/$id.html? permanent;
rewrite ^/art\.php /article/$id.html? permanent;
rewrite ^/art_list\.php /article/category-$id.html? permanent;
rewrite ^/artid\.php /help/$id.html? permanent;
rewrite ^/article\.php /affiche/$id.html? permanent;
}
結果正常了。
注意,關鍵點就在於「?」這個尾綴。重定向的目標地址結尾處若是加了?號,則不會再轉發傳遞過來原地址的問號?後面的參數那部分。
假如又想保留某個特定的參數,那又該如何呢?能夠利用Nginx自己就帶有的$arg_PARAMETER參數自行補充來實現。
例如:
把http://example.com/test.php?para=xxx&p=xx 重寫向到 http://example.com/new.php?p=xx
能夠寫成:rewrite ^/test.php /new.php?p=$arg_p? permanent;
[全文結束]
參考文章:
原始的動態頁面須要給個301永久重定向到靜態頁面上,以告訴搜索引擎將原始的頁面的權重轉到新的靜態頁面下。
if ($query_string ~* "id=(\d+)$") {
set $id $1;
rewrite ^/goods\.php /goods/$id.html permanent;
}
這樣重定向後發現 當輸入/goods.php?id=254訪問的時候會跳轉到/goods/254.html?id=254下,
後面看見搜索引擎的收錄地址也添加了後面沒必要要的參數,必須去掉後面參數。那該怎麼來處理呢?
例如:
把http://examplecom/test.php?para=xxx 重定向到http://examplecom/new
若按照默認的寫法:rewrite ^/test.php(.*) /new permanent;
重定向後的結果是:http://examplecom/new?para=xxx
若是改寫成:rewrite ^/test.php(.*) /new? permanent;
那結果就是:http://examplecom/new
因此,關鍵點就在於「?」這個尾綴。假如又想保留某個特定的參數,那又該如何呢?能夠利用Nginx自己就帶有的$arg_PARAMETER參數來實現。
例如:
把http://examplecom/test.php?para=xxx&p=xx 重寫向到http://examplecom/new?p=xx
能夠寫成:rewrite ^/test.php /new?p=$arg_p? permanent;php