nginx针对url参数重写URI

nginx针对url参数重写URI

场景:

原url:

http://blog.tuine.me/article/show?id=1&type=php&cat_id=2

修改为:

http://blog.tuine.me/article/show/1?type=php&cat_id=2
ngixn rewrite:
不写last和break - 那么流程就是依次执行这些rewrite 
1. rewrite break - url重写后,直接使用当前资源,不再执行location里余下的语句,完成本次请求,地址栏url不变 
2. rewrite last - url重写后,马上发起一个新的请求,再次进入server块,重试location匹配,超过10次匹配不到报500错误,地址栏url不变 
3. rewrite redirect – 302临时重定向,地址栏显示重定向后的url,爬虫不会更新url
4. rewrite permanent – 301永久重定向, 地址栏显示重定向后的url,爬虫更新url

方案一:

if ( $uri ~ ^/article/show$) {
    #注意此处带问号和不带问号的区别,带问号不会携带请求参数      
    #rewrite ^/ $uri/$arg_id?type=$arg_type&cat_id=$arg_cat_id? redirect;#1
    #rewrite ^/ $uri/$arg_id redirect; #2
}

存在问题:

如果用#1,动态参数时会出问

如果用#2,参数中还会携带id=1,出现重复。

方案二:

if($request_uri ~* "/article/show\?id=([0-9]+)&(.*)") {
    set $myid $1;#注意$1不能直接使用
    set $myque $2;
    rewrite ^/  /article/show/$myid?$myque? redirect;
}

可以完美解决。


补充匹配参数正则:

#包含某参数则跳转
if ($query_string ~ "type=(blog)(.*)$"){ 
    rewrite ^/article/blog.css http://www.tuine.com/;       
}
if ($query_string ~ "type=(blog|www)(.*)$" ){ 
    rewrite ^/ http://www.tuine.com/;     
}
if ($request_uri ~ "/(.*).html\?type=blog" ){
    rewrite ^/ http://www.tuine.com/;     
}
if ($request_uri ~ "/(.*).html\?type=blog" ){ 
    rewrite ^/(.*).html /article/blog.css;       
}

发表评论