2
votes

I'd like to serve uploaded images via Nginx, so the Express-App can concentrate on other tasks. In this case the usual alias-approach seems not quite enough though.

Files/Images on Harddrive:

The Images are renamed and stored under randomized strings. This is how the files-folder looks on the harddrive:

/srv/expressap/uploads/files/images

33134ijnas9d8.jpg
81j917asdlkas.png
ja982p1031la0.png
...

Requested Urls to get Images

htto://www.project.com/files/images/33134ijnas9d8/puppy.jpg
htto://www.project.com/files/images/81j917asdlkas/mittens.png
htto://www.project.com/files/images/ja982p1031la0/snuggles.png

Question

This - obviously - doesn't work since 'puppy.jpg' is not the actual filename the image '33134ijnas9d8.jpg'

location /files/images {
   alias /srv/expressap/uploads/files/images
}

How would the location-section look like to serve the actual image under the given url?

How to 1) get the id-string from the url?

2) Serve the image based on the id-string?

1

1 Answers

3
votes

You need to use regexp for this, Nginx supports them.

location ~* ^/files/images/(\w+)/.+\.(jpg|png|gif)$ {
   alias /srv/expressap/uploads/files/images/$1.$2;
}

~* - regexp case-insensitive modifier

(\w+) - any word-like sequence without spaces

$1, $2 - references to the matching groups in brackets

Details about using regexps with alias here.

So, you mostly need to extract some parts of the $uri by means of a regexp and pass them to the alias directive. You may test your regexp here, though I didn't test it with Nginx, implementation may differ.