本文介绍了Nginx,try_files代理和具有404备用广告的命名位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,它只会影响我正在处理的一个本地应用程序-使用这种方法的其他应用程序似乎可以正常工作(Ghost).这是从我的Nginx服务器配置中获得的:

I have an odd issue which is only affecting one local app I'm working on - other apps with this approach seem to work fine (Ghost). This is from my Nginx server config:

location @node_proxy {
  proxy_set_header        X-Real-IP            $remote_addr;
  proxy_set_header        X-Forwarded-For      $remote_addr;
  proxy_set_header        X-Forwarded-Proto    $scheme;
  proxy_set_header        X-NginX-Proxy        true;
  proxy_set_header        Host                 $host;
  proxy_redirect          off;
  proxy_pass              http://127.0.0.1:5000;
}

location / {
  try_files @node_proxy =404;
}

正如我所说,我的Ghost运行与此相同,并且运行良好.但是,对于此配置,它导致每个请求均为404-似乎从未命中代理.我检查了日志,这证实了我的怀疑,访问日志或错误日志中没有条目.

As I said, I have Ghost running identically to this and it performs fine. However for this config it results in every request being a 404 - it seems to never hit the proxy. I've checked logs and this confirms my suspicions, no entries in the access or error logs.

在这种情况下,我要代理的应用程序只是一个简单的基于Express的节点应用程序,因此没有什么复杂的.访问http://127.0.0.1:5000,我看到了预期的结果.

The app I'm proxying through to in this instance is just a simple Express based node app, so nothing complex. Visiting http://127.0.0.1:5000 I see the expected results.

如果我将配置更改为:

location / {
  proxy_set_header        X-Real-IP            $remote_addr;
  proxy_set_header        X-Forwarded-For      $remote_addr;
  proxy_set_header        X-Forwarded-Proto    $scheme;
  proxy_set_header        X-NginX-Proxy        true;
  proxy_set_header        Host                 $host;
  proxy_redirect          off;
  proxy_pass              http://127.0.0.1:5000;
}

它可以按预期工作,但是我想使用命名位置,以避免重复代理声明.

It works as expected, however I'd like to make use of the named location so as to avoid having to repeat proxy declarations.

我错过了明显的事情吗?

Have I missed something obvious?

推荐答案

尝试这种黑客手段:

location @root {
    ...
}

location / {
    error_page 418 = @root; return 418; # redirect to @root
}

似乎不可能从常规位置跳到命名位置.您也可以尝试try_files @root @root,但是Igor Sysoev(nginx的作者)说error_page更好,因为它使用的资源更少.

Seems like it is impossible to jump to named location from a regular one. You also can try try_files @root @root, however Igor Sysoev (nginx's author) says that error_page is better since it uses less resources.

这篇关于Nginx,try_files代理和具有404备用广告的命名位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 06:08