Cyrus
Cyrus

Reputation: 131

Rewrite regexp in nginx

This is the nginx config:

location @rewrite {
    rewrite ^/threads/ /thread.php?$uri&$args last;
}

That code works fine, but I want to use another route now.

OLD: /threads/123-yyy-yyy-yyy
NEW: /xxx-xxx-xxx/123-yyy-yyy-yyy

I've tried some like:

rewrite ^\/[\w]+\/([\d]+-[\w]+)?$ /thread.php?$1&$args last;
rewrite ^/[\w]+/([\d]+-[\w]+)?$ /thread.php?$1&$args last;
rewrite ^/\w+/(\d+-\w+)?$ /thread.php?$1&$args last;
rewrite ^/\w+/(\d+-\w+)$ /thread.php?$1&$args last;

But the page is not found, so I guess there is something wrong in my regex. Might it be $uri/$1 parameter?

Upvotes: 0

Views: 396

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15662

  1. You don't need to add &$args to your rewrite rules. As nginx rewrite documentation states,

If a replacement string includes the new request arguments, the previous request arguments are appended after them. If this is undesired, putting a question mark at the end of a replacement string avoids having them appended, for example:

rewrite ^/users/(.*)$ /show?user=$1? last;
  1. \w metacharacter includes a-z, A-Z, 0-9 and underscore(_). It doesn't include dash character. You can try this regex:

    rewrite ^\/[-\w]+\/([\d]+-[-\w]+)$ /thread.php?$1 last;
    

Upvotes: 1

Related Questions