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

NGINX配置:为网站不同路径设置独立根目录

NGINX 多路径目录映射配置

要实现你需要的URL路径与本地目录的对应关系,可以通过NGINX的location指令来配置,以下是完整的server块示例:

server {
    listen 80;
    server_name domain.com;

    # 主站根目录:domain.com/ -> /var/www/html/domain.com/website
    location / {
        root /var/www/html/domain.com/website;
        index index.html index.htm index.php; # 根据站点类型调整索引文件
        try_files $uri $uri/ =404;
    }

    # 博客路径:domain.com/blog/ -> /var/www/html/domain.com/blog
    location /blog/ {
        alias /var/www/html/domain.com/blog/;
        index index.html index.htm index.php;
        try_files $uri $uri/ =404;
    }

    # 结账页面路径:domain.com/checkout/ -> /var/www/html/domain.com/checkout
    location /checkout/ {
        alias /var/www/html/domain.com/checkout/;
        index index.html index.htm index.php;
        try_files $uri $uri/ =404;
    }

    # 下载路径:domain.com/download/ -> /var/www/html/domain.com/download
    location /download/ {
        alias /var/www/html/domain.com/download/;
        index index.html index.htm;
        try_files $uri $uri/ =404;
    }

    # 论坛路径:domain.com/forum/ -> /var/www/html/domain.com/forum
    location /forum/ {
        alias /var/www/html/domain.com/forum/;
        index index.html index.htm index.php;
        try_files $uri $uri/ =404;
    }
}

关键说明:

  • root vs alias:主站根路径用root,因为/会匹配所有未被其他location捕获的请求,root会把请求路径追加到指定目录后;子路径用alias,它会直接将匹配的URL路径替换为指定本地目录,避免路径拼接错误。
  • index指令:根据各目录下的站点类型调整索引文件,比如PHP站点需加上index.php。
  • try_files指令:处理静态文件和目录访问,若请求的文件或目录不存在则返回404。

配置完成后,执行以下命令验证配置并重启NGINX:

nginx -t
systemctl restart nginx

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:22:05