49

I know about the HttpRewriteModule, but I don't really know how to handle regex and I would need to redirect all URLs within a certain directory to another, specifically:

From: example.com/component/tag/whatever

To: example.com/tag/whatever

Could some one tell me how to do this in Nginx?

2 Answers 2

70

Do you mean something like:

rewrite ^/component(.*)$ $1 last;
6
  • I think this will do it, thank you so much. I'm awful at regular expressions; I will have to try to learn them...
    – javipas
    Commented Aug 18, 2011 at 12:05
  • 1
    regex101.com/r/qJ5gU1/1 has explanation on the right side
    – Jon
    Commented Mar 25, 2015 at 11:13
  • 11
    You may need to replace last by break. (Last will try to resolve other locations after the rewrite). Commented Apr 11, 2015 at 9:57
  • 7
    It only worked for me with break and not with last.
    – Guillaume
    Commented Jun 20, 2017 at 9:38
  • 3
    last = stop rewriting this request and search for a new matching location block, and break = stop rewriting this request and continue execution within the current location block
    – NoChecksum
    Commented Jan 28, 2019 at 17:44
5

Depending where you define the rewrite directive you have two ways to implement it:

A. In the server context

server {
    ...
    rewrite ^/component(.*)$ $1 last;
    ...
}

B. In the location context

location /component {
    rewrite ^/component(.*)$ $1 break;
}

Teo, why did you change the flag last to break? Because, if this directive is put inside of a location context, the last flag will make nginx to run 10 cycles and return the 500 error.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .