Nginx学习记录
Nginx学习记录:前端项目部署、负载均衡与代理配置
适合前端开发者快速入门Nginx,涵盖静态资源部署、负载均衡和反向代理场景
一、核心概念速记
功能 | 作用 |
---|---|
静态资源部署 | 将前端构建产物(HTML/CSS/JS)托管到服务器 |
反向代理 | 隐藏真实服务端口,解决跨域问题(如代理API请求) |
负载均衡 | 将流量分发到多个服务器实例,提升并发能力和容错性 |
二、安装与启动
Ubuntu安装
sudo apt update
sudo apt install nginx
MacOS安装
brew install nginx
常用命令
# 启动
sudo systemctl start nginx# 重载配置(不改端口时用)
sudo systemctl reload nginx# 重启(修改端口时用)
sudo systemctl restart nginx # 停止
sudo systemctl stop nginx
三、配置目录结构
/etc/nginx/
├── nginx.conf # 主配置文件
├── sites-available/ # 可用的站点配置
├── sites-enabled/ # 已启用的站点(软链接到sites-available)
├── conf.d/ # 其他配置片段
└── ...
四、常用配置详解
1. 前端静态项目部署
server {listen 80; # 监听80端口server_name example.com; # 域名或IP# 静态资源根目录root /var/www/my-frontend-app/dist;# 首页文件index index.html;# 单页应用路由支持location / {try_files $uri $uri/ /index.html;}# 静态资源缓存location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {expires 30d; # 缓存30天add_header Cache-Control "public, no-transform";}
}
启用步骤:
# 创建软链接
sudo ln -s /etc/nginx/sites-available/frontend.conf /etc/nginx/sites-enabled/# 测试并重载配置
sudo nginx -t && sudo nginx -s reload
2. 反向代理API请求
server {listen 80;server_name api.example.com;location / {# 代理到本地Node服务proxy_pass http://localhost:3000;# 关键请求头转发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 /socket.io/ {proxy_pass http://localhost:3000;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";}
}
3. 负载均衡配置
http {# 定义服务集群(名称为backend)upstream backend {# weight=权重,值越大分配越多请求server 192.168.1.100:8080 weight=3;server 192.168.1.101:8080 weight=2;server 192.168.1.102:8080 backup; # 备用服务器}server {listen 80;server_name app.example.com;location / {# 请求转发至backend集群proxy_pass http://backend;}}
}
负载均衡策略:
轮询(默认)
:均匀分发请求weight
:按权重分配ip_hash
:固定IP访问同一节点(解决会话问题)least_conn
:优先发往连接数最少的节点
五、调试与优化
配置测试与日志
# 检查配置语法
sudo nginx -t# 查看访问日志
tail -f /var/log/nginx/access.log# 查看错误日志
tail -f /var/log/nginx/error.log
Gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript;
六、常见问题排查
问题 | 解决方案 |
---|---|
403 Forbidden | 检查目录权限:chmod -R 755 /path/to/project |
502 Bad Gateway | 确认后端服务是否正常运行 |
静态资源不更新 | 文件名添加哈希值:main.abc123.css |
跨域问题 | 检查proxy_set_header 配置是否完整 |
七、高级功能扩展
功能 | 使用场景 |
---|---|
HTTPS支持 | 使用Let’s Encrypt证书+listen 443 ssl |
HTTP2支持 | 在SSL配置后添加http2 参数 |
请求限流 | 配置limit_req_zone 模块 |
安全头设置 | 添加CSP/XSS防护头 |
部分内容参考官方配置示例:Nginx Config Examples