1
  • http://example.com: my site
  • http://example.net: the proxied backend

I'm trying to setup an nginx server block as both a static content server and a reverse proxy. Nginx should first check for static files and then redirect to the proxied application if no file exists. It is configured as such:

location @backend {
    proxy_pass http://example.net;
}

location / {
    try_files $uri $uri/ @backend;
}

However, with such a configuration accessing http://example.com returns a 403 Forbidden: it seems that nginx tries to serve a static folder, does not find an index.html and fails without proxying example.net. I then have to explicitly add a route for /:

location = / {
    proxy_pass http://example.net;
}

That way http://example.com/ is properly proxied to http://example.net. But such a configuration feels odd: is there a better way to proxy / ?

Charles
  • 263
  • 1
  • 3
  • 10

1 Answers1

2

The $uri/ clause is causing the problem.

If you do not need a trailing / to be added to URIs that represent a static directory, you could use:

location / {
    try_files $uri @backend;
}

Alternatively, your existing solution also works with a try_files instead of a duplicate proxy_pass:

location = / {
    try_files $uri @backend;
}

See this document for more.

Richard Smith
  • 11,859
  • 2
  • 18
  • 26