需要在同一个域名下部署多个项目,这个时候就需要配置二级目录
http://www.baidu.com/a
http://www.baidu.com/b
http://www.baidu.com/b
需要在同一个域名下部署多个项目,这个时候就需要配置二级目录
http://www.baidu.com/a
http://www.baidu.com/b
http://www.baidu.com/b
答案:
在 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;
}
}
关键细节说明:
alias
vs root
alias
会完全替换匹配的路径(如 /a/
-> /path/to/project_a/
)root
会追加路径(如 /a/
+ root /path/to/
= /path/to/a/
)location
和 alias
必须统一有无末尾斜杠,否则可能引发 404 错误。nginx -s reload
使配置生效。/static/
),需确保资源路径包含二级目录(改为 /a/static/
)。location = /a/
)或调整匹配顺序。在 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;
}
}
几个关键点说明:
server {
listen 80;
server_name www.baidu.com;
# 使用 root 配置
location /a {
root /path/to; # 实际路径将是 /path/to/a/
index index.html;
}
}
root 和 alias 的区别:
1 回答1.7k 阅读✓ 已解决
1 回答2.8k 阅读
1 回答2.2k 阅读
1 回答1k 阅读✓ 已解决
1 回答1.6k 阅读
1 回答1.9k 阅读
1 回答682 阅读
通过别名匹配, location /cms要放在location /的上面.