Nginx:/用于静态内容和代理应用程序

  • http://example.com :我的网站
  • http://example.net :代理后端

我正在尝试将nginx服务器块设置为静态内容服务器和反向代理。 Nginx应该首先检查静态文件,然后在没有文件存在的情况下redirect到代理应用程序。 它是这样configuration的:

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

但是,使用这种访​​问http://example.com的configuration会返回一个403 Forbidden :似乎nginx试图提供一个静态文件夹,没有find一个index.html并且没有代理example.net失败了。 然后我必须明确地添加一个路由为/

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

这样http://example.com/被正确代理到http://example.net 。 但是这样的configuration感觉很奇怪:还有更好的代理方式吗?

$uri/子句导致了这个问题。

如果您不需要将尾部/添加到表示静态目录的URI,则可以使用:

 location / { try_files $uri @backend; } 

或者,您现有的解决scheme也可以使用try_files而不是重复的proxy_pass

 location = / { try_files $uri @backend; } 

请参阅此文档了解更多