1

I have the following location that handles my assets:

location ~ \.(?:css|js|jpe?g|png) {
  root /var/static;
}

So if a request is

www.example.com/img/file.png

the file.png will be taken from

/var/static/css/file.png

That's correct. But in some cases I need to handle the following request:

 www.example.com/css/file1.png

And take it from the img directory

 /var/static/img/file1.png

How should I change my location?

2
  • I'm confused. Why aren't you using the css dir for .css and img for the .png in the first place?
    – Nathan C
    Jun 18, 2013 at 19:47
  • May you provide an example? And what if I'll have the following route www.mysite.com/img/folder/file.png ?
    – Erik
    Jun 18, 2013 at 19:49

2 Answers 2

1

First of all, don’t use the root directive to do this. The alias is the correct directive. The root is only meant for complete server blocks.

You can use try_files if nginx should check the other directory in case the file doesn’t reside in the first directory. If this isn’t the case, you’ll have to find a repeating pattern to which you can apply the regular expression.

Well and at this point a problem arises. If we want to use try_files we can’t use alias because of a long standing bug. For your specific use case we’ll fall back to using the root directive because we can’t achieve it otherwise.

And last but not least, Melvyn is right. You should correct your file system. Use the regular expressions for old links and redirect them with a 301 to the new location.

Example based on your question

server {
    listen 80;
    server_name _;
    root /var/www;

    location / {

        location ~* ^/[^/]*/(.*)\.(css|js|jpe?g|png)$ {
            root /var/static;
            try_files $uri /img/$1.$2 =404;
        }

    }
}
2
  • But I may have more that 2 subdirs or none of them. Is it possible to construct uniserval regexp? And where is your alias directive?
    – Erik
    Jun 19, 2013 at 19:26
  • I extended my answer and please read my complete answer regarding alias. It’s all there. Jun 20, 2013 at 7:31
0

Your example isn't correct at all.

location ~ \.(?css|js|jpe?g|png) {
  root /var/static;
}

and a request www.example.com/img/file.png will be taken from /var/static/img/file.png.

The question mark after the ( doesn't belong there either. Something else is wrong in your site if a request for /img/file.png is taken from the /var/static/css. Finally, you should really move the images into the correct directory, rather then using regexes to fix deviations from naming conventions. Or just make a dir /var/static/media and be done with it.

2
  • I've edited my question
    – Erik
    Jun 19, 2013 at 11:02
  • This answer is not very supportive and doesn't seem to try to answer the OP's question at all.
    – Machado
    Feb 28, 2022 at 19:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .