rewrite or return for simple redirection

Maxim Dounin mdounin at mdounin.ru
Mon Nov 24 14:39:25 UTC 2014


Hello!

On Fri, Nov 21, 2014 at 02:53:50PM -0800, neubyr wrote:

> On Fri, Nov 21, 2014 at 12:11 PM, Maxim Dounin <mdounin at mdounin.ru> wrote:

[...]

> > For such cases rewrite is better, IMHO.  In some cases it may be a
> > good idea to additionally isolate it with prefix location, like
> > this:
> >
> >     location /members/ {
> >         rewrite ^/members/(.*) /users/$1 redirect;
> >     }
> >
> >
> Thank you Maxim. In what cases prefix might be a good idea??

This mostly depends on other configuration in the server{} and 
expected workload.  That is, it doesn't make much sense to isolate 
rewrite if you just have a bunch of rewrites already isolated from 
other requests.  E.g., consider the following configuration:

    location / {
        rewrite ^/members/(.*) /users/$1  redirect;
        rewrite ^/images/(.*)  /static/$1 redirect;
        return 404;
    }

    location /users/ {
        ...
    }

    location /static/ {
        ...
    }

This configuration assumes that all the traffic in "location /" 
will be redirected, and most normal requests should be handled in 
other locations ("/users/", "/static/").  It doesn't make much 
sense to bother doing additional isolation with prefix locations 
as it's more or less already here.

On the other hand, consider the following configuration:

    location / {
        rewrite ^/members/(.*) /users/$1  redirect;
        rewrite ^/images/(.*)  /static/$1 redirect;

        proxy_pass http://backend;
    }

In this configuration all requests are handled in "location /".  
And for all normal requests to "/users/..." nginx will have to 
check all the rewrites.  This is just a waste of resources.  
Moreover, such a configuration may (and likely will) become hard 
to support eventually, and this is probably even more important 
thing to consider.  So it's usually good idea to use something 
like this instead:

    location / {
        proxy_pass http://backend;
    }

    location /members/ {
        rewrite ^/members/(.*) /users/$1  redirect;
    }

    location /images/ {
        rewrite ^/images/(.*)  /static/$1 redirect;
    }

See also this Igor's talk for additional hints on how to write 
scalable nginx configurations:

https://www.youtube.com/watch?v=YWRYbLKsS0I

-- 
Maxim Dounin
http://nginx.org/



More information about the nginx mailing list