【问题标题】:Nginx Location based try files?基于 Nginx 位置的尝试文件?
【发布时间】:2020-06-27 22:28:58
【问题描述】:

我在这里阅读此页面https://help.sorryapp.com/en/articles/2783542-install-maintenance-pages-on-nginx 有一个很好的想法,即存在文件意味着 nginx 将路由到维护 html 页面。

但是通过 nginx 文档阅读,似乎位置块中的 if 语句并不理想,而是使用 try 文件。将上面的内容重写为 nginx 想要的方式的正确方法是什么? https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

我假设是这样的:但是重写呢?

try_files /my/file/path/maint.on
error_page 503 @maintenance_page;
location @maintenance_page {
    rewrite ^(.*)$ /maintenance_page.html break;

?

更新 1

这是我当前的配置片段,由于某种原因,即使 maint.on 文件不存在,它也会导致 404。

      location / {
         if (-f /opt/staytus/staytus/maint.on) {
            return 503;
        }
        port_in_redirect off;
                proxy_pass http://example.com:8787/;
        }

 error_page 503 @Performing-Maintenance;

    location @Performing-Maintenance {
        rewrite ^(.*)$ Performing-Maintenance.html break;
    }
}

对这个问题有什么想法吗?

【问题讨论】:

    标签: nginx centos


    【解决方案1】:

    正如同一篇文章所述,

    如果在位置上下文中,可以在内部完成的唯一 100% 安全的事情是:

    • return ...;
    • rewrite ... last;

    所以您找到的示例可以被认为是完全安全的。 (我想说在if 块内使用来自ngx_http_rewrite_module 的任何指令是安全的,该块将此列表扩展到breakreturnrewriteset)。你不能用 try_files 指令做你想做的事,因为它需要在最后一个 uri 之前至少有一个 file 参数(或命名位置的名称或 HTTP错误代码)参数,如果列表中没有任何文件/目录实际存在,则将使用该参数。好吧,我可以想象类似的东西

    location / {
        try_files /maintenance.html @default;
    }
    
    location @default {
        ...
    }
    

    但你不能让它服务于某个位置,比如

    location = /maintenance.html {
        ...
    }
    

    ,它只会返回maintenance.html 文件的内容。如果maintenance.html 页面将引用一些额外的资产(如CSS、JS 等),那么所有用户浏览器对该资产的请求都将导致maintenance.html 内容(因为该文件存在并通过了try_files 检查)。仅供参考,这个指令

    location / {
        try_files $uri $uri/index.php =404;
    }
    ...
    location ~ \.php$ {
        ...
    }
    

    不会通过 PHP 位置处理程序提供 $uri/index.php 文件(它只返回其原始内容),而这

    location / {
        index index.php;
        try_files $uri $uri/ =404;
    }
    

    会的。

    但是,由于每个传入请求都会进行额外的stat 内核调用,您提供的示例会对性能产生一些影响(尤其是在高负载服务器上)。我推荐this 使用 nginx 启用维护模式的方法。

    【讨论】:

    • 嗯,但是您的链接选项让我每次都在维护模式下编辑 nginx/sites-enabled conf?
    猜你喜欢
    • 1970-01-01
    • 2015-03-10
    • 2020-07-27
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2012-09-24
    • 2017-07-15
    相关资源
    最近更新 更多