Nginx 使用 try_files 将 https 上不存在的文件重定向到 http

Ali*_*i W 9 nginx

我已经搜索了一段时间的正确方法来做到这一点。

在 https 服务器上请求不存在的文件时重定向到 http 服务器并请求相同的文件。

例如。

https://example.org/some_missing_file.html - 重定向 -> http://example.org/some_missing_file.html

https://example.org/existing_file.html - 提供文件

https://example.org/SomeDir/missing_file - 重定向 -> http://example.org/SomeDir/missing_file

https://example.org/SomeMissingDir/ - 重定向 -> http://example.org/SomeMissingDir/missing_file

这个基于 if 的代码段有效

listen 443 ssl;

#... more config

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

但是“如果是邪恶的” - http://wiki.nginx.org/IfIsEvil

所以这是我对 try_files 版本的尝试 - 这不起作用。

   try_files $uri @redirect;

   location @redirect {
           rewrite ^ http:// example.org$request_uri permanent;
           break;
   }
Run Code Online (Sandbox Code Playgroud)

我已经尝试了很多变种;proxy_redirects,返回 302 - 当文件位于子目录中时,它们无法重定向或不起作用,或者如果为空则不重定向根。

有没有人有基于 try_files 的防弹替换?

(ps。由于链接检查器不了解example.org而导致的空格!)

VBa*_*art 19

server {
    listen 443 ssl;

    root /path/to/documents;

    location / {
        try_files $uri @redirect; 
    }

    location @redirect {
        return 301 http://example.org$request_uri;
    }
}
Run Code Online (Sandbox Code Playgroud)