8

I've searched for the correct way to do this for a while.

On an https server when a non-existent file is requested redirect to the http server and request the same file.

eg.

https:// example.org/some_missing_file.html - redirect -> http:// example.org/some_missing_file.html

https:// example.org/existing_file.html - serve file

https:// example.org/SomeDir/missing_file - redirect -> http:// example.org/SomeDir/missing_file

https:// example.org/SomeMissingDir/ - redirect -> http:// example.org/SomeMissingDir/missing_file

This if based snippet works

listen 443 ssl;

#... more config

if (!-e $request_filename) {
    rewrite ^ http:// example.org$request_uri permanent;
    break;
}

But "if is evil" - http://wiki.nginx.org/IfIsEvil

So this is my attempt at a try_files version - which doesn't work.

   try_files $uri @redirect;

   location @redirect {
           rewrite ^ http:// example.org$request_uri permanent;
           break;
   }

I've tried numerous variations of this; proxy_redirects, return 302's - they fail to redirect or don't work when a file is in a subdir, or don't redirect the root if empty.

Does anyone have a bullet proof try_files based replacement?

(ps. spaces due to link checker not knowing about example.org!)

17
server {
    listen 443 ssl;

    root /path/to/documents;

    location / {
        try_files $uri @redirect; 
    }

    location @redirect {
        return 301 http://example.org$request_uri;
    }
}
| improve this answer | |
  • Thanks - yes that does it. Do you know why the "location / { try_files $uri @redirect; }" allows this to work? where without location / { it doesn't? – Ali W Jul 28 '12 at 4:30
  • 1
    To be precise, try_files in the server context works for those requests that do not fall into any location. Since you have not showed complete configuration, so I assumed that you had locations that could catch all requests. – VBart Jul 28 '12 at 11:28

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.