Simple url rewrite in nginx

6,595

Just get rid of the space after the ^, and add the required ;:

rewrite ^/test1$ /;
rewrite ^/test2$ /something/else;

The $ characters denote the end of the string. Get rid of them if you want /test1/blah to match as well as /test1.

Edit: To send a redirect response to the browser add either redirect (for a 302 response) or permanent (for a 301 response) as a flag to your rewrite lines:

rewrite ^/test1$ / permanent;
rewrite ^/test2$ /something/else permanent;
Share:
6,595

Related videos on Youtube

user80666
Author by

user80666

Updated on September 18, 2022

Comments

  • user80666
    user80666 over 1 year

    How do I redirect:

    /text1 to /
    

    and

    /test2 to /something/else
    

    I tried putting:

    rewrite ^ /test1 /
    rewrite ^ /test2 /something/else
    

    Inside the server {}

    • womble
      womble almost 12 years
      What sort of redirect? Do you want it to match subpaths? If so, what do you want to do with them (discard or preserve)?
    • user80666
      user80666 almost 12 years
      there are not going to be any subpaths, exact matches only. Just very simple redirection. if /test1 then goto / or if /test2 go to /thispath. Actually examples with subpaths preserved and discarded would be nice to (for me to learn by example)
    • womble
      womble almost 12 years
      But what do you mean by "go to"?
    • user80666
      user80666 almost 12 years
      someone types in site.com/test1, server sends redirect header and redirects them to / .
    • womble
      womble almost 12 years
      What response code?
  • user80666
    user80666 almost 12 years
    Should these go into a specific location {} or just simply under server {} ?
  • ravi yarlagadda
    ravi yarlagadda almost 12 years
    They work in either context. And I have the same clarifying question as womble - are you looking to have this send a redirection response to the user so that the URL in their address bar changes, or keep /test2 in their address bar but serve the content from /something/else?
  • ravi yarlagadda
    ravi yarlagadda almost 12 years
    @user80666 See edit.
  • user80666
    user80666 almost 12 years
    That works thank you. One problem I noticed however, is that if I change the redirection url and restart the server browser still remembers the old redirection address, almost like it's cached. Is there anything I can do to prevent browsers cacheing the redirection url?
  • ravi yarlagadda
    ravi yarlagadda almost 12 years
    @user80666 The 301 response code from the permanent flag is cached by some browsers. If the redirects will always be there, then you'll want to leave it like that; if not, change the flag from permanent to simply redirect to send a 302.