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

Angular单页应用部署Nginx后直接访问子路径出现404问题

解决Angular单页应用Nginx部署下直接访问子路径404的问题

你的问题核心是Angular作为单页应用(SPA),前端路由在浏览器直接访问子路径时,Nginx会尝试寻找对应物理文件,而这些路径并没有实际的文件存在,导致404。当前Nginx配置中的try_files规则错误,没有正确引导所有路径到index.html。

正确的Nginx配置修改

将location /块的配置替换为以下内容:

location / {
  try_files $uri $uri/ /index.html;
}

完整的default.conf配置如下:

server {
  listen 80;
  sendfile on;
  default_type application/octet-stream;

  gzip on;
  gzip_http_version 1.1;
  gzip_disable      "MSIE [1-6]\.";
  gzip_min_length   1100;
  gzip_vary         on;
  gzip_proxied      expired no-cache no-store private auth;
  gzip_types        text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
  gzip_comp_level   9;

  root /var/www/html;

  location / {
    try_files $uri $uri/ /index.html;
  }
}

配置说明

  • $uri:先尝试匹配请求对应的物理文件(比如静态资源js、css、图片等)
  • $uri/:如果请求是目录路径,尝试匹配目录
  • /index.html:如果以上都匹配不到,就返回根目录的index.html,交给Angular的前端路由处理

生效配置

修改配置后,需要重启Docker中的Nginx容器,确保新配置生效:

# 替换为你的容器名称
docker restart your-nginx-container-name

如果使用Docker Compose部署,执行:

docker-compose up -d --force-recreate

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:45:37