Nginx regex rule for caching images override the root location block

configurationnginx

My nginx setup contains the following location rules:

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js|pdf)$ {
        expires 7d;
    }

    location /data/ {
            root /mnt/data;
    }

The problem is, when I try to access one of the following files (jpg | jpeg | png | gif | ico | css | js | pdf) in the /data/ folder I get 404 Not Found error, cause the first location rule overrides the second. I tried to do something like this:

    location ~* /data/.*\.jpg$ {
            root /mnt/data;
            expires 7d;
    }

But this doesn't seems to work. Could you please help me what solutions are available for me in this case?

Best Answer

Solutions are:

#1 Rule duplication

location ~*  \.(jpg|jpeg|png|gif|ico|css|js|pdf)$ {
    expires 7d;
}

location /data/ {
    root /mnt/data;

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js|pdf)$ {
        expires 7d;
    }
}

#2 Symlink

You can create a symlink: $document_root/data -> /mnt/data.