http-redirectnginxurl-rewritinghttp-status-code-301ngx-http-rewrite-module

Nginx 301 redirect syntax error


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


Solution

  • 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.