以下是一个使用Nginx作为反向代理服务器,将前端请求转发到后端服务的配置示例及详细说明:
server {
listen 80;
server_name example.com; # 替换为你的域名或IP
# 前端静态文件服务(假设前端打包后放在/dist目录)
location / {
root /usr/share/nginx/html/dist;
index index.html;
try_files $uri $uri/ /index.html; # 支持前端路由(如Vue/React的history模式)
}
# 代理转发API请求到后端
location /api/ {
proxy_pass http://backend-server:8000/; # 后端服务地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 可选:WebSocket代理(如需要)
location /ws/ {
proxy_pass http://backend-server:8000/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
前端静态文件服务
root
指定前端资源目录(如Vue/React打包后的dist
文件夹)。try_files
确保前端路由(如/about
)不会返回404,而是由前端处理。API请求代理
/api/
开头的请求会被转发到后端服务(如http://localhost:8000
)。proxy_set_header
传递原始请求的IP和Host信息,确保后端能获取真实客户端IP。WebSocket支持
Upgrade
和Connection
头。server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location / {
# ...(同上)
}
location /api/ {
proxy_pass http://backend-server:8000/;
# ...(其他代理配置)
}
}
# HTTP强制跳转HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
upstream backend {
server backend1:8000;
server backend2:8000;
server backend3:8000;
}
server {
location /api/ {
proxy_pass http://backend/;
# ...(其他代理配置)
}
}
location /api/ {
proxy_pass http://backend-server:8000/;
add_header 'Access-Control-Allow-Origin' '$http_origin';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
}
检查Nginx配置语法
nginx -t
重新加载配置
nginx -s reload
查看日志
/var/log/nginx/error.log
/var/log/nginx/access.log
404错误
root
路径是否正确。proxy_pass
地址无误。502 Bad Gateway
前端路由刷新404
try_files $uri $uri/ /index.html;
已配置。根据你的实际需求调整proxy_pass
地址、路径和HTTPS证书路径即可。如果需要更复杂的配置(如缓存、限流),可以进一步扩展Nginx规则。