Nginx中如何配置二级目录?

阅读 859
avatarAI BotBETA

答案:

在 Nginx 中配置二级目录需要通过 location 块和 alias/root 指令实现。以下是典型配置示例:

server {
    listen 80;
    server_name www.baidu.com;

    # 项目A:通过 /a 访问
    location /a/ {
        alias /path/to/project_a/;  # 使用 alias 时路径需以斜杠结尾
        index index.html;
        try_files $uri $uri/ /a/index.html;  # 单页应用可能需要此配置
    }

    # 项目B:通过 /b 访问
    location /b/ {
        alias /path/to/project_b/;
        index index.html;
    }

    # 如果是反向代理(如后端服务)
    location /api/ {
        proxy_pass http://localhost:3000/;  # 末尾斜杠表示去除 /api 前缀
        proxy_set_header Host $host;
    }
}

关键细节说明:

  1. alias vs root

    • alias 会完全替换匹配的路径(如 /a/ -> /path/to/project_a/
    • root 会追加路径(如 /a/ + root /path/to/ = /path/to/a/
  2. 斜杠问题
    locationalias 必须统一有无末尾斜杠,否则可能引发 404 错误。
  3. 重载配置
    修改后执行 nginx -s reload 使配置生效。
  4. 静态资源路径冲突
    如果项目内的静态资源引用使用绝对路径(如 /static/),需确保资源路径包含二级目录(改为 /a/static/)。
  5. 多个项目冲突
    避免不同项目的路由互相覆盖,优先通过精确匹配(location = /a/)或调整匹配顺序。
2 个回答
✓ 已被采纳

通过别名匹配, location /cms要放在location /的上面.

location /a {
  alias /www/wwwroot/www.baidu.com/a;
  try_files $uri $uri/ /cms/index.html;
  index index.html index.htm index.htm.gz;
  add_header Cache-Control "public, max-age=86400";
}

在 Nginx 中配置二级目录主要通过 location 指令来实现。以下是一个基本的配置示例:

server {
    listen 80;
    server_name www.baidu.com;

    # 配置 /a 目录
    location /a {
        alias /path/to/a/;
        index index.html;
        try_files $uri $uri/ /a/index.html;
    }

    # 配置 /b 目录
    location /b {
        alias /path/to/b/;
        index index.html;
        try_files $uri $uri/ /b/index.html;
    }

    # 配置 /c 目录
    location /c {
        alias /path/to/c/;
        index index.html;
        try_files $uri $uri/ /c/index.html;
    }
}

几个关键点说明:

  1. location 指令用于匹配 URL 路径
  2. alias 指定实际的文件系统路径
  3. try_files 用于设置文件查找顺序
    也可以使用 root 替代 alias :
server {
    listen 80;
    server_name www.baidu.com;

    # 使用 root 配置
    location /a {
        root /path/to;  # 实际路径将是 /path/to/a/
        index index.html;
    }
}

root 和 alias 的区别:

  • root :最终路径等于 root 路径 + location 路径
  • alias :最终路径等于 alias 路径
    建议:
  1. 确保目录权限正确
  2. 注意路径末尾的斜杠
  3. 如果是 SPA 应用,记得配置适当的 try_files
  4. 可以在各个 location 中配置不同的缓存策略
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏