是的,一台 Nginx 服务器完全可以支持两个(甚至更多)前端项目的访问。这是 Nginx 的典型应用场景之一。关键在于通过 合理的配置(如 server 块、location 路由、端口或域名区分)将不同请求分发到对应的前端项目。
以下是几种常用且推荐的实现方式:
✅ 方式一:基于不同域名(推荐,生产环境首选)
# /etc/nginx/conf.d/project1.conf
server {
listen 80;
server_name project1.example.com;
root /var/www/project1;
index index.html;
location / {
try_files $uri $uri/ /index.html; # 支持前端路由(如 Vue Router history 模式)
}
}
# /etc/nginx/conf.d/project2.conf
server {
listen 80;
server_name project2.example.com;
root /var/www/project2;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
✅ 优点:清晰隔离、便于管理、符合标准;支持 HTTPS(配合 Let’s Encrypt)
⚠️ 前提:需配置 DNS 或本地 hosts 文件解析对应域名(开发时可用 127.0.0.1 project1.test)
✅ 方式二:基于不同路径(子路径部署,适合单域名场景)
server {
listen 80;
server_name example.com;
# 主站(可选)
location / {
root /var/www/main;
try_files $uri $uri/ /index.html;
}
# 项目1 → 访问 http://example.com/app1/
location /app1/ {
alias /var/www/project1/;
try_files $uri $uri/ /app1/index.html;
}
# 项目2 → 访问 http://example.com/app2/
location /app2/ {
alias /var/www/project2/;
try_files $uri $uri/ /app2/index.html;
}
}
⚠️ 注意:
- 使用
alias(不是root)时末尾/很关键; - 前端构建时需设置
publicPath: '/app1/'(Vue CLI)或base: '/app1/'(Vite),确保静态资源路径正确; try_files中的 fallback 要匹配子路径(如/app1/index.html)。
✅ 方式三:基于不同端口(简单开发调试用)
server {
listen 8080;
server_name localhost;
root /var/www/project1;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
server {
listen 8081;
server_name localhost;
root /var/www/project2;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
✅ 适合本地开发快速验证;
❌ 不推荐用于生产(端口暴露不友好,防火墙/CDN 限制多)。
🔧 补充建议
- ✅ 静态资源优化:添加
expires、gzip、add_header等提升性能; - ✅ SPA 路由支持:所有
location /均需try_files $uri $uri/ /index.html;防止刷新 404; - ✅ HTTPS 支持:每个
server可单独配 SSL(listen 443 ssl+ssl_certificate); - ✅ 日志分离:为每个项目配置独立
access_log和error_log,便于排查; - ✅ 权限与安全:确保 Nginx 进程有读取前端目录的权限(如
chown -R www-data:www-data /var/www/project1)。
✅ 总结
| 方式 | 适用场景 | 是否推荐 | 备注 |
|---|---|---|---|
| 不同域名 | 生产、多项目上线 | ✅ 强烈推荐 | 标准、专业、易扩展 |
| 不同路径 | 单域名整合管理 | ✅ 推荐 | 需前端配合 publicPath |
| 不同端口 | 本地开发调试 | ⚠️ 仅限开发 | 不适合公网/生产环境 |
只要配置得当,一台 Nginx 完全可以优雅地托管数十个前端应用 👍
需要我帮你生成某个具体场景(如 Vue + Vite 项目部署到 /admin/ 路径)的完整配置示例吗?
ECLOUD博客