Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx, try_files proxy and named location with 404 fallback

Tags:

nginx

proxy

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?

like image 369
leepowell Avatar asked Nov 29 '13 15:11

leepowell


1 Answers

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.

like image 105
neoascetic Avatar answered Oct 19 '22 09:10

neoascetic