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;
Related videos on Youtube
Author by
user80666
Updated on September 18, 2022Comments
-
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 almost 12 yearsWhat sort of redirect? Do you want it to match subpaths? If so, what do you want to do with them (discard or preserve)?
-
user80666 almost 12 yearsthere 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 almost 12 yearsBut what do you mean by "go to"?
-
user80666 almost 12 yearssomeone types in site.com/test1, server sends redirect header and redirects them to / .
-
womble almost 12 yearsWhat response code?
-
-
user80666 almost 12 yearsShould these go into a specific location {} or just simply under server {} ?
-
ravi yarlagadda almost 12 yearsThey 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 almost 12 years@user80666 See edit.
-
user80666 almost 12 yearsThat 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 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 frompermanent
to simplyredirect
to send a 302.