Nginx 301 redirect syntax error

165 Views Asked by At

I just found that my nginx syntax was not correct:

location /news { rewrite ^(.*)$ /blog redirect;}

I want to redirect mysite.com/news to mysite.com/blog but that code was redirecting more pages to blog.

Anyone can help me explaining the error and tell me how to correctly redirect?

thanks

2

There are 2 best solutions below

0
cnst On BEST ANSWER

The best practice would be to still use a location. If you don't want anything below /news to redirect to /blog (e.g., no need for a wildcard), then the following is what you want, and is probably the most efficient way to create a single alias:

location = /news {
    return 301 /blog;
}

Otherwise, if you do, in fact, want a wildcard:

location /news {
    rewrite ^/news(.*)  /blog$1 permanent;
}

P.S. Also note that redirect would cause 302 redirects; if you want 301, then the keyword is called permanent.

0
Hammer On

you don't need to put it inside the location block. Just a single rewrite rule is enough.

rewrite ^/news/?$ /blog redirect;