Reputation: 2271
I am using nginx to server static image files. Within my directory, all images are stored with an extension _.txt (basically renamed to .txt). For example: background.png will be stored as background.png.txt
How do I redirect the lookup for domain.com/images/background.png to look for /static/images/background.png_.txt
Here is my nginx config so far...
location /images/ {
alias /static/images/;
access_log off;
}
Upvotes: 0
Views: 1328
Reputation: 773
This works on my server. It just takes the request for something in the images directory and checks if it exists, then checks if it exists with the .txt
extension, and finally gives a 404 error if those aren't found.
location /images/ {
default_type "image/gif";
try_files $uri $uri.txt $uri =404;
}
Just make sure you don't duplicate the location/images
block. Add it if it's not there, but it should be already, so just add the try_files
line to it.
As I wrote in a comment, I'd be surprised if your server doesn't already search in static
when going to the images directory. However, if the code I shared doesn't work, you could add the path for your modified image files to the block, e.g.:
location /images/ {
root /home/username/path_to_site/domain.com/static/images;
default_type "image/gif";
try_files $uri $uri.txt $uri =404;
}
Edit
If you examine the response headers, some browsers show images served this way as content-type:text/plain
. One hack to override this is to specify types directly in the images location block:
location /images/ {
default_type "image/gif";
try_files $uri $uri.txt $uri =404;
types {
text/plain gif;
image/jpg jpeg jpg;
image/png png;
image/gif gif;
image/x-icon ico;
}
}
These types are defined elsewhere in nginx, but this is easier if you don't want to do surgery in the guts of your server. The important line is text/plain gif;
. This is defining any text files found in the images directory as image/gif
.
Final thoughts: This might be better done as a rewrite, however maybe someone else knows the details of that method.
Upvotes: 2