You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx proxy_pass代理资源请求返回404,根文档可正常加载

问题分析

核心原因是Nginx的location匹配优先级导致静态资源请求未走proxy_pass转发。

你引入的_general.conf中定义了两个针对静态资源的正则匹配location ~*块:

  • 匹配css、js、图片等资源的location
  • 匹配svg、字体等资源的location

Nginx的location匹配规则是:正则表达式匹配优先级高于前缀匹配(location /属于前缀匹配),所以当请求service-worker.js这类静态资源时,会优先命中_general.conf里的正则location,而这些块未配置proxy_pass,Nginx会默认去本地文件系统查找资源,找不到就返回404。

解决方案

你可以选择以下两种方式解决:

方案1:给静态资源location添加转发配置

直接在_general.conf的两个静态资源location块中补充proxy_pass相关配置,让它们也将请求转发到上游服务器:

修改后的_general.conf相关代码:

# assets, media
location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
        expires 7d;
        access_log off;
        # 添加转发配置
        proxy_pass http://webapp;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

# svg, fonts
location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff|woff2)$ {
        add_header Access-Control-Allow-Origin "*";
        expires 7d;
        access_log off;
        # 添加转发配置
        proxy_pass http://webapp;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

方案2:移除静态资源的正则location

如果希望所有请求(包括静态资源)都统一通过location /转发,直接注释或删除_general.conf里的两个静态资源location块即可:

修改后的_general.conf相关代码:

# assets, media
# location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
#         expires 7d;
#         access_log off;
# }

# svg, fonts
# location ~* \.(?:svgz?|ttf|ttc|otf|eot|woff|woff2)$ {
#         add_header Access-Control-Allow-Origin "*";
#         expires 7d;
#         access_log off;
# }
验证修改

配置调整后,执行命令重新加载Nginx:

nginx -s reload

再测试静态资源请求:

curl -I http://localhost:5555/service-worker.js

此时应该能收到上游服务器返回的200响应。

内容的提问来源于stack exchange,提问作者Barry Chapman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 00:44:51