[Answered ]-Nginx – permanent redirect to amazon s3 if one media file doesnot exist locally

2👍

This works for me:

    root /home/myuser/myproject/public/;    

    location @media {
        return 301 $scheme://image.example.com$request_uri;
    }

    location /media/ {
        try_files $uri @media;
    }

I’m holding collected static and media files in public directory inside django project, so MEDIA_ROOT will be in this example /home/myuser/myproject/public/media/, but I’m pretty sure that you can just use your approach with alias inside /media/ location.

Quick explanation: @media is an named location, which by default is not used anywhere in nginx, but you can use it by yourself somewhere. For example, last parameter of try_files can be an named location.

Nginx will try to fetch file from /media/ url, when it fails, it will fallback to @media named location, and that is an redirect to subdomain.

You can also use that fallback in 404 handler instead of try_files:

location /media/ {
    error_page 404 = @media;
}

Leave a comment