Nginx rewrite urls with special characters

自闭症网瘾萝莉.ら 提交于 2019-11-30 09:47:15

问题


I just got a list of urls that needs to be rewritten into nginx

example.com/cms.php/inspiration?fullsize > /
example.com/shop/?category_id=27 > /garden/cushion.html
example.com/shop/?2008=1&vare_id=10553&variant_id=2232 > /garden/cushion/black.html

I tried with the following

Simple rewrite

rewrite /shop/?category_id=27 /garden/cushion.html permanent;

Location rewrite

location /shop/?category_id=27 {
    rewrite /shop/?category_id=27 /garden/cushion.html;
}

And with location where I commented special signs

location /shop/\?category_id=27 {
    rewrite /shop/\?category_id=27 /garden/cushion.html;
}

I add them directly into server {...} in the nginx configuration


回答1:


Firstly, anything from the ? onwards is the query string and is not part of the normalised URI used by the rewrite and location directives.

One way to achieve your objective is to test the $request_uri variable using a map directive.

For example:

map $request_uri $redirect {
    default                                     0;
    /cms.php/inspiration?fullsize               /;
    /shop/?category_id=27                       /garden/cushion.html;
    /shop/?2008=1&vare_id=10553&variant_id=2232 /garden/cushion/black.html;
}
server {
    ...
    if ($redirect) { return 301 $redirect; }
    ...
}

See this document for more, and this caution on the use of if.



来源:https://stackoverflow.com/questions/43236108/nginx-rewrite-urls-with-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!