1

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;
}
2

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, and rewrite to redirect the client to the external URL.

For example:

location /forums/uploads/
    try_files $uri @rewrite;
}
location @rewrite {
    rewrite ^/forums/uploads(.*)$ https://cdn.example.com$1 redirect;
}

See this document for more.

I don't think it's possible, but a check for a non 404 on the CDN would be great also.

Nginx takes no part in resolving the URL after it is redirected to the CDN.

  • Thanks. This almost worked though I needed to make a few small changes. – Christian Jan 16 at 23:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.