Home > Enterprise >  Nginx Match Image Filename Based On Part of URL?
Nginx Match Image Filename Based On Part of URL?

Time:09-17

For local development, I'm trying to serve static content out of a public directory. My images live in app/public/images, and my root is app/public. My images are looked up at /d/my_app_name/images/<image>.png. I'm matching the /d/my_app_name/images location, but trying to figure out how to then extract the file name and have nginx look up the appropriate filename from the images directory? My current settings:

    root /app/public;
    index index.php;


    location /d/my_app_name/images/ {
        root /images/; # <--- I guess this rule is making nginx look up a file that matches the entire relative path, rather than just the filename
    }

UPDATE I was able to get it to match and look up the filename only from what appears to be the right directory, but I'm still getting a not found error. I'm assuming that the relative path shown in the error is relative to the root, in which case that file/directory should exist.

    root /app/public;
    index index.php;

    location /d/my_app_name/images/ {
         alias /images/;
    } 

When I go to localhost:8380/d/my_app_name/images/my_image.png it is looking up the correct png file in the app/public/images directory, but it's still saying it doesn't exist.

[error] 8#0: *1 open() "/images/my_image.png" failed (2: No such file or directory), client: 192.168.176.1, server: devbox, request: "GET /d/my_app_name/images/my_image.png HTTP/1.1", host: "localhost:8380"

Images are kept in /app/public/images directory.

CodePudding user response:

I think you have inverted location and root paths.

I can suggest you to change your location block as follow:

location /images/ {
     root /d/my_app_name/images/; # override global root to your specific path where your images are hosted
}

More configurations examples can be found on the official documentation.

CodePudding user response:

You can use a simple alias which tells Nginx to search for all the files in another path. Root would only work if your location was just images and is actually used in the documentation: https://nginx.org/en/docs/http/ngx_http_core_module.html#alias

root /app/public; #Use full path, ex: /home/username/repo/app/public/
index index.php;

location /d/my_app_name/images/ {
    alias /app/public/images/; # Use full path, ex: /home/username/repo/app/public/
}
  • Related