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

NGINX配置疑问:如何实现根路径与其他路径对应不同文件夹?

NGINX Location配置问题解决

问题原因

你当前的配置中,访问根路径/时虽能精确匹配location = /,但try_files $uri /index.html里的/index.html会触发内部重定向,此时请求变为/index.html,会匹配到第二个location /,最终加载/usr/share/nginx/html/app/index.html,导致始终显示app文件夹的内容。

解决方法

修改第一个精确匹配的location,避免内部重定向到其他规则,直接在当前规则内处理根路径请求:

方案一:指定默认索引文件

location = / {
    root /usr/share/nginx/html/main;
    index index.html;
}

location / {
    root /usr/share/nginx/html/app;
    try_files $uri /index.html;
}

方案二:调整try_files参数

location = / {
    root /usr/share/nginx/html/main;
    try_files $uri index.html; # 省略前缀/,直接匹配当前root下的index.html
}

location / {
    root /usr/share/nginx/html/app;
    try_files $uri /index.html;
}

两种方案都能实现:访问/时加载main文件夹的HTML,访问其他任意路径时加载app文件夹的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:05:25