【问题标题】:Nginx: setting the error page to a static fileNginx:将错误页面设置为静态文件
【发布时间】:2015-08-12 11:52:32
【问题描述】:

我有以下 nginx 配置:

server {
  listen          80;
  server_name     default;

  location / {
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:8080/;
  }

}

http://127.0.0.1:8080/ 的内部服务没有响应时,nginx 返回一个502 Bad Gatway 错误

我的问题:如何配置 nginx 以返回静态 html 文件,例如/var/www/error.html,什么时候出现这样的错误?


我尝试了什么

提示from here我试过这个:

server {
  listen          80;
  server_name     default;

  location / {
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:8080/;
  }

  error_page 404 502 /error.html;

  location = /error.html {
    internal;
    root /var/www;
  }

}

如果服务(在端口 8080 上)关闭,它工作正常,但是当服务启动并且我尝试访问 url /error.html nginx 匹配最后一个位置(返回给我静态文件)并且我想避免它。

【问题讨论】:

  • 为什么要访问/error.html
  • @AlexeyTen 在我的服务器上,我在/var/www/error.html 上有我的错误页面,我想在出现 502 错误时提供它。我不想访问/error.html,这只是一次尝试。我可以使用哪些替代品?
  • @AlexeyTen 我不想在我的服务启动时暴露错误页面。
  • 除非你把这个链接放在某个地方,否则没人会去你的host/error.html。只是不要这样做,一切都会好起来的
  • @AlexeyTen :D 是的,这是一个很好的解决方法,但它不是最好的解决方案。 :(

标签: nginx configuration system


【解决方案1】:

好吧,如果你真的不想暴露错误页面,你可以使用命名位置。

server {
  listen          80;
  server_name     default;

  location / {
    proxy_set_header Host $host;
    proxy_pass http://127.0.0.1:8080/;
    # probably you also need this
    # proxy_intercept_errors on;
  }

  error_page 404 502 @error;

  location @error {
    root /var/www;
    try_files /error.html /error.html;
  }
}

【讨论】:

  • 唯一的是我不需要proxy_intercept_errors,因为我的服务有它的内部错误页面,如果它正在运行,我想要那个页面。
  • 那么你在error_page指令中也不需要404
  • 好的,谢谢。我为我的各种测试添加了它,但可能你是对的,我不需要它。
  • 我发现在try_files 中添加$uri 也很有用,即:try_files $uri /error.html /error.html;。这样我可以在error.html中链接图片(和其他资源),例如我可以使用<img src="/images/logo.png" />
猜你喜欢
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
相关资源
最近更新 更多