Nginx, try_files proxy and named location with 404

2019-05-03 09:53发布

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;
}

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.

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.

If I change my config to:

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?

标签: nginx proxy
1条回答
可以哭但决不认输i
2楼-- · 2019-05-03 10:30

Try this kind of hack:

location @root {
    ...
}

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

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.

查看更多
登录 后发表回答