Nginx Regular expression to match first segment of a url

时间:2015-07-28 16:28:45

标签: nginx rewrite

I have some urls like these:

domain.com/article/1234-newstitle
domain.com/article/1234-newstitle/
domain.com/article/1234-newstitle/abc
domain.com/article/1234-newstitle/xpto/abc
domain.com/article/1234-newstitle/qwerty/abc/xyz

I want to catch only the /1234-newstitle/ to redirect these urls and ignore everything after the 1º slash (whatever the number of segments) so I can have:

domain.com/news/newstitle-1234/

The best I could get is:

rewrite ^article/(\d+)-(.*)[^\/]* /new/$2-$1/ permanent;

but $2 matches everything after 1234-

How am I able to match only the first segment "1234-newstitle" and ignore the rest?

1 个答案:

答案 0 :(得分:0)

看起来你在连字符后有一个贪婪的比赛。试试这个:

rewrite ^/article/(\d+)-([^/]+) /new/$2-$1/ permanent;