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

Dokku中配置Nginx实现多静态站点路径访问遇403错误的解决

解决Nginx子路径映射静态文件的403错误(Dokku/Docker场景)

问题根源

你当前的配置没有指定Nginx在访问子路径时自动加载索引文件,且路径匹配逻辑存在疏漏:

  • 访问example.com/first时,Nginx会定位到/app/first/dist目录,但默认不会自动寻找index.html,而是尝试返回目录列表(默认禁用),因此触发403错误。
  • 访问example.com/first/dist正常,是因为此时Nginx明确进入了dist目录,能自动识别到index.html。

正确配置方案

以下是两种可行的配置写法,任选其一即可:

写法一:带末尾斜杠的精确匹配

location /first/ {
  alias /app/first/dist/;
  # 指定默认索引文件
  index index.html;
  # 处理文件/目录不存在的情况,fallback到index.html(适配SPA)
  try_files $uri $uri/ /first/index.html;
}

location /second/ {
  alias /app/second/dist/;
  index index.html;
  try_files $uri $uri/ /second/index.html;
}

写法二:不带斜杠的兼容匹配

location /first {
  alias /app/first/dist;
  index index.html;
  try_files $uri $uri/ /first/index.html;
  # 兼容不带斜杠的访问
  rewrite ^/first$ /first/ permanent;
}

location /second {
  alias /app/second/dist;
  index index.html;
  try_files $uri $uri/ /second/index.html;
  rewrite ^/second$ /second/ permanent;
}

关键配置说明

  • index index.html;:强制Nginx在访问目录时自动加载index.html,避免返回目录列表(403)。
  • try_files:处理静态资源不存在的情况,自动跳转至子路径的index.html,适合单页应用路由场景。
  • 末尾斜杠:确保location和alias的路径拼接逻辑正确,防止出现类似/app/first/distfile这种错误路径。

Dokku部署注意事项

将修改后的nginx.conf放在项目根目录的.dokku/nginx.conf.d/文件夹下,Dokku会自动加载该自定义配置;或者通过命令指定配置路径:

dokku nginx:set <你的应用名> custom-config-path /path/to/your/nginx.conf

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 09:01:15