user2025805
user2025805

Reputation: 21

nginx rewrite rule to remove - and _

i need a nginx rewrite rule for the following problem:

I have Urls that include several hyphen and eventually underscores

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

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.

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

any help appreciated :)

Upvotes: 1

Views: 2414

Answers (1)

VBart
VBart

Reputation: 15110

% 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;
        }
    }
}

Upvotes: 1

Related Questions