场景
-
两个前端项目app和app1,两个后端接口项目api和api1
-
拥有域名
domain.com -
app 项目打包后的静态文件在 /var/www/app/
-
app1 项目打包后的静态文件在 /var/www/app1/
-
api 后端服务运行在 localhost:4000
-
api1 后端服务运行在 localhost:4001
目标
| 项目名 | 访问路径 |
|---|---|
| app | http://domain.com | http://www.domain.com |
| app1 | http://app1.domain.com |
| api | http://api.domain.com |
| api1 | http://api.domain.com/api1 |
实现
- 安装 Nginx
sudo apt update
sudo apt install nginx
- 确保权限(非必须)
sudo chown -R $USER:$USER /var/www/app/
sudo chown -R $USER:$USER /var/www/app1/
-
创建 Nginx 配置文件
- 在
/etc/nginx/sites-available/中创建配置文件app和api
sudo nano /etc/nginx/sites-available/app sudo nano /etc/nginx/sites-available/api - 在
-
分别添加以下配置内容
# /etc/nginx/sites-available/app
server {
listen 80;
server_name domain.com;
# 将非www重定向到www
return 301 http://www.domain.com$request_uri;
}
server {
listen 80;
server_name www.domain.com;
location / {
root /var/www/app; # app 项目的根目录
index index.html index.htm; # 默认首页文件
try_files $uri $uri/ /index.html; # Vue 应用的 HTML5 History 模式
}
}
server {
listen 80;
server_name app1.domain.com;
location / {
root /var/www/app1; # app1 项目的根目录
index index.html index.htm; # 默认首页文件
try_files $uri $uri/ /index.html; # Vue 应用的 HTML5 History 模式
}
}
说明:一般情况下设置
try_files $uri $uri/ =404;先尝试查找请求的 URI 对应的文件,接着会尝试查找该 URI 对应的目录,如果前两个都查找失败,Nginx 将返回一个 404 Not Found 错误。 但为了确保 Vue 的 History 路由模式能够正常工作,改为try_files $uri $uri/ /index.html;,所有未匹配的请求都重定向到主 HTML 文件(通常是 index.html),以便让 Vue 接管路由。
# /etc/nginx/sites-available/api
server {
listen 80;
server_name api.domain.com;
location / {
proxy_pass http://localhost:4000; # api
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /api1/ {
proxy_pass http://localhost:4001/; # api1
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
- 使用符号链接启用配置
sudo ln -s /etc/nginx/sites-available/app /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/api /etc/nginx/sites-enabled/
- 测试 Nginx 配置并重启
sudo nginx -t
# 重启 Nginx
sudo systemctl restart nginx
# 也可以仅重新加载配置
sudo systemctl reload nginx
# 查看 Nginx 状态
sudo systemctl status nginx
- DNS 配置
| 域名 | 记录类型 | 主机名 | 值 |
|---|---|---|---|
| 主域名(domain.com) | A | @ 或 domain.com | 服务器 IP 地址 |
| 子域名(domain.com) | A | www | 服务器 IP 地址 |
| 子域名(app1.domain.com) | A | app1 | 服务器 IP 地址 |
| 子域名(api.domain.com) | A | api | 服务器 IP 地址 |
| 子域名(api1.domain.com) | A | api1 | 服务器 IP 地址 |