nginx location overwrites alias

Luistar15 asked:

I have an alias “/temp” that works ok, but when I add another location block, the alias returns 404.

Working config: http://mysite.com/temp/blank.gif -> OK

server {
    # ...
    location /temp {
        alias  /var/www/temp;
    }
    # ...
}

Error config: http://mysite.com/temp/blank.gif -> 404

server {
    # ...
    location /temp {
        alias  /var/www/temp;
    }
    location ~ \.(?:jpg|png|gif)$ {
        expires  30d;
    }
    # ...
}

Here is my full config: http://pastebin.com/yExq0nMY

How can I solve it?

My answer:


Use a nested location for this.

nginx matches only one location block at the server level, so you have to nest them in this circumstance. For full details, see the official documentation: How nginx processes a request.

server {
    # ...
    location /temp {
        alias  /var/www/temp;
        location ~ /temp/\.(?:jpg|png|gif)$ {
            expires  30d;
        }
    }
    location ~ \.(?:jpg|png|gif)$ {
        expires  30d;
    }
    # ...
}

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.