【问题标题】:Custom 404 in NginxNginx 中的自定义 404
【发布时间】:2015-10-04 14:24:59
【问题描述】:

我正在尝试指定自定义 404 页面并保留 URL,但是使用下面的代码会给我错误 nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in...

location / {
    error_page 404 @404;  
}

location @404 {
   proxy_pass https://example.com/404.html;
}

有人知道解决办法吗?

【问题讨论】:

  • 为什么你需要为那个404.html使用代理?
  • 我想在不同的站点/域/服务器块之间共享 404 页面。即我想将来自example.com/404.html 的404 页面用于test.example.com 和其他使用不同服务器块的域。
  • 我明白了,因为保留了 URL。如果 nginx 不喜欢命名位置,请尝试不存在的位置:error_page 404 /404/non-exist; location /404/non-exist { ... }
  • 是的,完全是为了保留 URL。您能否将您的代码块放入答案中,以便其格式正确,如果它有效,我可以接受它作为答案?谢谢

标签: nginx proxy rewrite http-status-code-404 proxypass


【解决方案1】:

我已经在 nginx 1.6.2 上测试了你的配置。错误消息抱怨proxy_pass 中的 URL 指定了 path。仅指定 https://server 可以,但不能解决您的问题。

还引入了命名位置(如@fallback)以避免不得不使用不存在的位置(这可能会在以后变为现有并导致问题)。但我们也可以使用服务器本身不应该存在的位置,例如:

location / { error_page 404 /xx-404-xx; }
location /xx-404-xx { proxy_pass https://example.com/404.html; }

重定向到相对 URL 只会导致内部 nginx 重定向,它不会更改浏览器看到的 URL。

编辑:这是测试结果:

kenny:/etc/nginx/sites-enabled:# wget -S server.com/abc/abc
HTTP request sent, awaiting response...
  HTTP/1.1 404 Not Found
  Server: nginx/1.6.2
  Date: Thu, 16 Jul 2015 07:01:38 GMT
  Content-Type: text/html
  Content-Length: 5
  Connection: keep-alive
  Last-Modified: Thu, 16 Jul 2015 07:00:59 GMT
  ETag: "5037762-5-51af8a241434b"
  Accept-Ranges: bytes
2015-07-16 09:01:38 ERROR 404: Not Found.

来自 apache 访问日志:

1.2.3.4 - - [16/Jul/2015:09:01:38 +0200] "GET /test.html HTTP/1.0" 200 5 "-" "Wget/1.13.4 (linux-gnu)"

在 nginx 中,我有 proxy_pass 到 Apache 网络服务器上的一个 html 文件,其中只有“test\n”。如您所见,nginx 获取了它,从 Apache(Last-Mod,ETag)和Content-Length: 5 添加了标头,因此它从 Apache 接收了 html 文件,但 wget 不保存 404 错误的内容。此外,如果小于 1 kB,许多浏览器默认不会显示 404 错误(它们会显示自己的错误页面)。所以要么让你的 404 页面更大,要么你可以配置 nginx 以将其作为普通 html 使用“200”结果代码 (error_page 404 =200 /xx)。

我不知道您为什么会收到具有相同配置的外部重定向。尝试使用wget 来查看 nginx 发送了哪些标头。混合使用 http 和 https 作为代理也应该没有问题。尝试从您的配置中删除所有内容并仅测试此错误页面,可能是其他一些指令导致此错误(如使用其他 location 代替)。

【讨论】:

  • 谢谢!我刚刚尝试过,但它会将我重定向到 https://example.com/404.html/ 而不是保留 URL。
  • 它适用于我(我尝试使用 http 而不是 https)。对于测试 URL,我尝试了 /xxx 和 /xxx/abc 并且都在远程 apache 服务器上触发了 /404.html。
  • 嗯,如果我使用 http,我会得到一个 301 Moved Permanently nginx 页面,可能是因为我将 http 重定向到 https。如果我使用 https,我会在左上角看到一条白页,上面写着“重定向到 example.com/404.html”,然后它会将我重定向到该页面。
  • 我在答案中添加了更多信息
猜你喜欢
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
  • 2015-08-12
  • 2020-02-21
  • 2019-09-13
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
相关资源
最近更新 更多