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

Nginx配置问题:如何在HTML文件旁部署静态资源文件夹

Nginx配置问题:无法加载static目录资源

文件结构

ui
 --index.html
 --nginx.conf
 --static
   --css
   --script

当前Nginx配置

upstream api {
      server api:8060;
    }

    server {
        listen 100;
        charset utf-8;
        server_name  localhost;

        root   /usr/share/nginx/html/ai;
        index  index.html index.htm;
        include /etc/nginx/extra-conf.d/*.conf;

        gzip on;
        gzip_types text/css text/javascript application/x-javascript application/json;

        # backend urls
        location /ai/ {
        try_files $uri /index.html;

        # static files
        location /static/ {
            proxy_pass http://api;
        }

        }

问题现象

UI加载时出现404错误:

GET http://localhost:8080/static/css/css/common-page.css net::ERR_ABORTED 404 (Not Found)

修复方案

你的配置存在两个核心问题:

  1. location /static/嵌套在location /ai/内部,只有请求路径以/ai/开头才会触发这个规则,但静态资源请求是/static/开头,根本不会匹配到。
  2. 静态资源是本地ui/static下的文件,你却配置了proxy_pass http://api,把请求转发到后端API,而不是从本地文件系统读取。

修改后的Nginx配置如下:

upstream api {
    server api:8060;
}

server {
    listen 100;
    charset utf-8;
    server_name localhost;

    root /usr/share/nginx/html/ai;
    index index.html index.htm;
    include /etc/nginx/extra-conf.d/*.conf;

    gzip on;
    gzip_types text/css text/javascript application/x-javascript application/json;

    # 处理本地静态资源:直接读取root目录下的static文件夹内容
    location /static/ {
        try_files $uri =404;
    }

    # 处理前端SPA路由,所有/ai/开头的请求转至index.html
    location /ai/ {
        try_files $uri /index.html;
    }

    # 如需转发后端API请求,单独配置(示例)
    # location /api/ {
    #     proxy_pass http://api;
    #     proxy_set_header Host $host;
    #     proxy_set_header X-Real-IP $remote_addr;
    # }
}

关键修改说明

  • 把location /static/从/ai/的嵌套位置移出来,作为独立规则,确保/static/开头的请求能被正确匹配。
  • 删除proxy_pass http://api,改用try_files $uri =404,让Nginx直接从本地root路径下的static文件夹读取资源。
  • 确认部署时/usr/share/nginx/html/ai目录下存在static文件夹(对应本地ui/static),路径映射要正确。

另外注意:你请求用的是8080端口,但Nginx配置监听的是100端口,要确保端口映射正确,否则也会导致访问失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:15:29