I'm trying to redirect only static file requests from a particular directory prefix when they 404.
I've tried using try_files and it may well work still but it hasn't for me so far.
This is the scenario;
Request is for https://example.com/forums/uploads/file.jpg File 404's Redirect to https://cdn.example.com/file.jpg
It's the change in path that I'm finding tricky.
I don't think it's possible, but a check for a non 404 on the CDN would be great also.
Solution (Based on accepted answer);
location ~* /forums/uploads {
try_files $uri @rewriteimages;
}
location @rewriteimages {
rewrite ^/forums/uploads(.*)$ https://cdn.example.com$1 redirect;
}
You want to check for the existence of a local file and redirect the client to an external URL if that file does not exist.
You can use
try_files
to test for the existence of a local file, andrewrite
to redirect the client to the external URL.For example:
See this document for more.
Nginx takes no part in resolving the URL after it is redirected to the CDN.