Setting up nginx for serving assets in production - what's the precise "location" section should be?

I have all the assets outside of the folder of my application - in

/opt/my_app123/assets/{static, uploads}/{images, fonts, videos, sitemap.xml, etc}

I can’t figure out how I should setup nginx to get it to serve them. I’ve found several solutions for ruby, but all of them assume that I have assets at “/assets/” being the virtual path. But I don’t, my virtual path for assets is “/”, namely “my_domain.com/images/image1.png”

But the nginx location sections for “/” is already occupied for other settings:

server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    server_name my_domain.com;
    [..........]

     location / {
        proxy_set_header        Host $host;
        proxy_set_header        X-Real-IP $remote_addr;
       proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header        X-Forwarded-Proto $scheme;
       [...................]

How should I setup it up for serving assets from both /opt/my_app123/assets/static and /opt/my_app123/assets/uploads ? so that

For instance:

/opt/my_app123/assets/static:

https://my_domain/images/image1.png

And

/opt/my_app123/assets/uploads:

https://my_domain/uploaded_assets/images/some_uploaded_img.png

or

https://my_domain/uploaded_assets/videos/video1.mp4

https://my_domain/uploaded_assets/files/some_file.pdf

Like this:

   location /uploaded_assets/ {
            alias /opt/my_app123/assets/uploads/;
            autoindex off;
    }

Put it before the / location block.

Ok, that’s a part on the answer

location ~ ^/(images|fonts|videos)/ {
            alias /opt/my_app123/assets/static/;
            autoindex off;
}

If something like this instead?

   location ~* ^.+\.(css|js|cur|gif|gz|ico|jpg|jpeg|js|png|svg|woff|woff2)$ { ......
1 Like

I get “403 forbidden” in production for all the assets