Nginx – Serving images from two different directories with Nginx

directoryfilesnginxPHPregex

This should be basic… I'm brand new, and no amount of googling and searching stack exchange is helping.

I have a website that I want to be able to serve images from, from different directories. I think the easiest way to do that would be to map something like website.com/i/image.jpg to a folder at root/i/, and put the images in there and be done with it.
So something like this should work, no?

location /i/ {
  /i/$uri;}

I don't know, I'm having a really hard time understanding nginx syntax.
But I also want to keep the URL as short as possible, and I believe I could do some fancy logic with regex where I can call images from /i/ while not messing with images that get called from root, or other folders. But I am just so stumped at syntax.

I saw on some other posts on stackexchange people trying to capture a string, and I realized that if I make all the image's names fit a certain pattern, I could attack it with a regex location that should match 100% of the time, so I can keep the url short and still separate the images from ones that I have no use with (I would explain their difference in purpose but I feel like it would be off topic).

Anyway, I saw the post with

location ~ "^/s/([0-9a-zA-Z]{4,6})$" {...

and realized this could be close to what I need. All of my files for this location will be 6 characters long, a-z only, and followed by any extension. I thought this would be simple, and I could do something like

location ~ "^([a-z]{6})$" {...

But no matter how I mess with the syntax, I just can't get it to run.
Can anyone shine some light on this?

Best Answer

This is my suggestion based on ALex_hha's answer and the details in farfie's comment above.

server {
    listen      8989;
    server_name www.example.net;

    root /vhosts/www.example.net/public_html;

    location ~ "^/([a-z]{6})(.*)\.(jpg|png|svg)$" {
        rewrite ^/([a-z]{6})(.*)\.(jpg|png|svg)$" /vhosts/www.example.net/static/$1$2.$3;
    }
}

The key is to use nginx rewrite directive to capture essential parts from the URI so that it can be mapped to any directory.

The root directive only changes the document root, and the URI is appended to the document root as-is, which in this case is not what you want.