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

Angular应用中Nginx无法正常加载JS和CSS文件问题求助

解决Angular应用Nginx静态文件加载问题的配置方案

修正后的nginx.conf配置

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log debug;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" $request_time';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    keepalive_timeout  65;
    client_max_body_size 10m;

    server {
        listen       80;
        server_name  localhost;

        # 指向Angular编译后的静态文件目录
        root   /usr/share/nginx/html;
        index  index.html index.htm;

        # 处理/app路径下的请求:优先返回真实静态文件,不存在则走Angular路由
        location /app {
            try_files $uri $uri/ /app/index.html;
        }

        # 处理根路径请求(按需保留)
        location / {
            try_files $uri $uri/ /index.html;
        }
    }

    include /etc/nginx/conf.d/*.conf;
}

关键修改说明

  • MIME类型配置前置:把include /etc/nginx/mime.types移到http块顶部,确保Nginx能正确识别JS、CSS等静态文件的类型,避免浏览器因类型错误无法解析文件。
  • 根目录归属调整:将root和index移到server块内,让所有location继承正确的静态文件根路径,避免路径匹配混乱。
  • try_files逻辑优化:$uri优先匹配真实存在的静态文件(如*.js、*.css),只有当文件不存在时才返回index.html,既满足Angular单页路由需求,又保证静态文件正常加载。
  • 编译路径匹配:如果应用部署在/app子路径,Angular编译时必须添加--base-href /app/参数(例如ng build --prod --base-href /app/),确保静态资源请求路径正确。

额外检查项

  • 确认Docker镜像中,Angular编译后的dist目录内容已正确复制到/usr/share/nginx/html/app(子路径部署)或/usr/share/nginx/html(根路径部署)。
  • 查看/var/log/nginx/error.log,若仍有404错误,检查静态文件实际路径与Nginx配置的root是否匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:20:26