nginx重写规则删除-和_ [英] nginx rewrite rule to remove - and _

查看:104
本文介绍了nginx重写规则删除-和_的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下问题,我需要使用nginx重写规则:

i need a nginx rewrite rule for the following problem:

我的Urls包含多个连字符,最后带有下划线

I have Urls that include several hyphen and eventually underscores

示例请求:会给出404错误 因此需要301-重定向到:

would give a 404 error so in need a 301- redirect to:

http://www.example.com/cat/cat2/200-AB-a-12-12-123.312/cat-cat/cat/dog-I

因此,所有下划线都应替换为连字符,并且一次只能有一个连字符.

So all underscores should be replaced with hyphens and there should be only one hyphen a time.

简短版本: 将-替换为-,并将_替换为- 但通过将_替换为-,此-_-将变为---,并且必须再次调用规则.

short version: replace --- with - and replace _ with - but by replacing _ with - this -_- will become --- and rule one would have to be called again.

有可能在一条规则中做到这一点吗?如果不是这样的话,:)我绝对不知道如何使用nginx

Is it possible to to that in one rule? and if not how to do it any other way :)i have absolutely no idea how to do that with nginx

任何帮助表示赞赏:)

推荐答案

% nginx -c $PWD/test.conf
% curl -I localhost:8080/cat/cat2/200-AB---a-12_12-123.312/cat-_-cat/cat/dog---I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.3.13
Date: Wed, 20 Feb 2013 00:09:50 GMT
Content-Type: text/html
Content-Length: 185
Location: http://localhost:8080/cat/cat2/200-AB-a-1212-123.312/cat-cat/cat/dog-I
Connection: keep-alive

% cat test.conf
events { }

#error_log  logs/error.log debug;

http {
    server {
        listen 8080;
        location /cat/cat2/ {
            # replace up to 3 inconsecutive
            # uderscores per internal redirect
            rewrite "^(.+?)_+(?:(.+?)_+)?(?:(.+?)_+)?(.+)$" $1$2$3$4 last;

            # replace up to 3 inconsecutive multiple
            # hyphens per internal redirect
            rewrite "^(.+?-)-+(?:(.+?-)-+)?(?:(.+?-)-+)?(.+)$" $1$2$3$4 last;

            return 301 $uri;
        }
    }
}

这篇关于nginx重写规则删除-和_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆