首页 > 解决方案 > 在 nginx、flask 中返回自定义错误页面

问题描述

我在 SO 中尝试了其他答案,例如:

使用 nginx 返回自定义 403 错误页面

nginx + uwsgi + flask - 禁用自定义错误页面

nginx 没有为我的 error_page 提供服务

参考:

http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_intercept_errors

http://nginx.org/en/docs/http/ngx_http_core_module.html#error_page

但仍然无法返回自定义错误页面 - nginx 不断返回自己的页面。

在本地环境中工作,flask 返回自定义 html 页面。

在 nginx 中发布时,不再赘述。

这就是我想要的:

  1. 如果用户点击/js/,路由将返回403,同时允许内部文件/js/myJS.js

  2. 如果文件 /js/myJS.js 不存在,则返回 404

  3. 如果出现问题,请说烧瓶中的 API 中断(它不应该 :))> 返回 500

我的烧瓶配置是这样的:

@application.errorhandler(404)
def error_404(e):
    application.logger.error('Page Not Found: %s', (request.path))
    #return render_template('404.html'), 404
    return render_template("404.html", error = str(e)), 404

// other errors are handled similarly

404.html模板,在var/www/mysite/templates文件夹内。

错误页面是静态文件,flask 没有提供任何资产,而是 html 模板。

现在,在我的nginx 配置中,我正在处理如下错误:

root var/www/mysite;
# update: tried to handle custom errors with proxy_intercept_errors on; 
# still no success
proxy_intercept_errors on;


# static is the directory that serve the subdirectory /js
# HOW COULD I RETURN 403 if /js is hit directly, but not /js/myfile.js ? 
# I tried to add deny all and allow only my server up, but did not worked out

location /static {
        expires 1M;
        alias /var/www/mysite/static;
        access_log off;
        add_header Cache-Control "public";
        allow #myserverip;
        deny all;
    }

    error_page 403 /403.html;
    location = /403.html {
        root /var/www/mysite/templates/;
        internal;
    }


    error_page 404 /404.html;
    location = /404.html {
        root /var/www/mysite/templates/;
        # internal;
        allow all;  
    }

    # also with the following no success: nginx white internal page is still displayed 
    error_page 404 http://example.com/404.html; 

我尝试设置内部或将其注释掉;我尝试设置允许所有(如上面SO答案中的答案),无论如何,nginx都会返回其自定义页面404 - 而不是来自我的模板文件夹。

我还尝试为后备设置一个文件夹,例如:

## Fallback Directory
location @error {
    root /var/www/error;
}

但仍然没有成功 - 总是来自 nginx 的白色 404 页面。


我的配置有什么问题?

我想更好地了解flask和nginx如何对话错误。

我知道一旦发布,nginx 将处理错误 - 但不了解烧瓶和 nginx 之间如何处理引发的错误:当用户点击“错误”资源的路由时会发生什么?是nginx拦截它吗?是烧瓶吗?是 uwsgi 吗?他们如何传球?

另外,请分享一个提示:我如何查询 nginx 中的错误页面,例如测试错误请求 403 和 500 ?

标签: nginxflaskerror-handlingserveruwsgi

解决方案


推荐阅读