大网数据广告活动
服务器运维问答

Nginx: / for both static content and proxied application

· 52CE 我爱测

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 t…

问题原文

原帖链接 · Charles · CC BY-SA 3.0

  • 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 / ?

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 3.0

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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-10-05)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。