前后端分离架构是指将前端应用(通常是JavaScript框架如React、Vue等)和后端服务(如Java Spring、Node.js等)分开部署,通过API进行通信的架构模式。
# Ubuntu/Debian
sudo apt update
sudo apt install nginx
# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx
project/
├── frontend/ # 前端项目
├── backend/ # 后端项目
└── nginx.conf # Nginx配置文件
server {
listen 80;
server_name yourdomain.com;
# 前端静态文件服务
location / {
root /path/to/frontend/dist;
index index.html;
try_files $uri $uri/ /index.html;
}
# 后端API代理
location /api/ {
proxy_pass http://localhost:8080/; # 后端服务地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, no-transform";
}
}
upstream backend_servers {
server backend1.example.com:8080;
server backend2.example.com:8080;
server backend3.example.com:8080;
}
server {
# ...其他配置...
location /api/ {
proxy_pass http://backend_servers/;
# ...其他proxy设置...
}
}
location /ws/ {
proxy_pass http://backend_servers;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
server {
listen 443 ssl;
server_name yourdomain.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# ...其他配置...
}
# HTTP重定向到HTTPS
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
前端部署:
npm run build
)后端部署:
Nginx操作:
# 测试配置
sudo nginx -t
# 重新加载配置
sudo systemctl reload nginx
# 启动/停止/重启
sudo systemctl start|stop|restart nginx
404错误(前端路由):
try_files $uri $uri/ /index.html
跨域问题:
静态资源缓存:
性能优化:
通过以上配置,你可以建立一个高效、安全的前后端分离架构,利用Nginx作为反向代理和静态文件服务器。