在Nginx中配置多个前端项目可以通过以下几种方式实现,我将详细介绍每种方法。
server {
listen 8080;
server_name localhost;
location / {
root /path/to/project1;
index index.html;
try_files $uri $uri/ /index.html;
}
}
server {
listen 8081;
server_name localhost;
location / {
root /path/to/project2;
index index.html;
try_files $uri $uri/ /index.html;
}
}
server {
listen 80;
server_name project1.example.com;
location / {
root /path/to/project1;
index index.html;
try_files $uri $uri/ /index.html;
}
}
server {
listen 80;
server_name project2.example.com;
location / {
root /path/to/project2;
index index.html;
try_files $uri $uri/ /index.html;
}
}
server {
listen 80;
server_name example.com;
location /project1/ {
alias /path/to/project1/;
index index.html;
try_files $uri $uri/ /project1/index.html;
}
location /project2/ {
alias /path/to/project2/;
index index.html;
try_files $uri $uri/ /project2/index.html;
}
# 可选:设置默认项目
location / {
root /path/to/default-project;
index index.html;
try_files $uri $uri/ /index.html;
}
}
server {
listen 80;
server_name example.com;
location ~ ^/(project1|app1)(/|$) {
alias /path/to/project1/;
index index.html;
try_files $uri $uri/ /project1/index.html;
}
location ~ ^/(project2|app2)(/|$) {
alias /path/to/project2/;
index index.html;
try_files $uri $uri/ /project2/index.html;
}
}
路径配置区别:
root
时,Nginx会将location路径附加到root路径后alias
时,location路径会被alias路径完全替换单页应用(SPA)配置:
try_files $uri $uri/ /index.html;
这行配置对于Vue、React等前端框架非常重要,确保路由能正确工作
静态资源缓存: 可以添加缓存控制:
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public";
}
配置验证: 修改配置后,使用以下命令检查并重载:
nginx -t # 测试配置
nginx -s reload # 重载配置
跨域问题: 如果需要API代理,可以添加:
location /api/ {
proxy_pass http://api-server/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
选择哪种配置方式取决于你的具体需求,基于URL路径的配置通常是最灵活和常用的方案。