Nginx 配置完全指南:反向代理、负载均衡、HTTPS
Nginx 是最流行的 Web 服务器。本文介绍 Nginx 的核心配置。
安装
# Ubuntu
sudo apt install nginx
# 启动
sudo systemctl start nginx
sudo systemctl enable nginx
反向代理
server {
listen 80;
server_name example.com;
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 / {
root /var/www/html;
index index.html;
try_files $uri $uri/ /index.html;
}
}
负载均衡
upstream backend {
server 192.168.1.1:8080 weight=3;
server 192.168.1.2:8080 weight=2;
server 192.168.1.3:8080 backup;
}
server {
location /api/ {
proxy_pass http://backend;
}
}
HTTPS 配置
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
location / {
root /var/www/html;
}
}
# HTTP 跳转 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
Gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1000;
常见配置
跨域配置
location /api/ {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE';
add_header Access-Control-Allow-Headers 'Content-Type, Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
proxy_pass http://backend;
}
限流
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
最佳实践
- 使用 HTTPS:保护数据安全
- 开启 Gzip:减少传输体积
- 设置缓存:提升访问速度
- 限流防刷:保护后端服务
总结
Nginx 是功能强大的 Web 服务器。掌握反向代理、负载均衡、HTTPS 等配置,可以构建高性能的 Web 架构。