编程 Nginx最强配置清单(反向代理/限流/SSL/负载均衡)

2025-07-26 10:43:48 +0800 CST views 269

#Nginx最强配置清单(反向代理/限流/SSL/负载均衡)

本文介绍了Nginx的强大配置,包括负载均衡、反向代理、限流、安全防护、性能优化和日志管理等功能。通过示例代码,读者可以学习如何配置Nginx以实现高效的反向代理、SSL加密、请求限流、IP访问控制、静态资源缓存等。还涉及了高级功能如灰度发布和地理位置限制,帮助用户提升网站的安全性和性能。

一、核心功能配置

1. 负载均衡配置

upstream backend {
  # 轮询策略(默认)
  server 192.168.1.101:8080 weight=5 max_fails=3 fail_timeout=30s;
  server 192.168.1.102:8080 weight=5 max_fails=3 fail_timeout=30s;
  
  # 备用服务器
  server 192.168.1.103:8080 backup;
  
  # 长连接优化
  keepalive 32;
}

server {
  location / {
    proxy_pass http://backend;
    
    # 重要头部信息传递
    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_connect_timeout 5s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
    
    # 缓冲区优化
    proxy_buffer_size 4k;
    proxy_buffers 8 16k;
  }
}

策略说明

  • weight:权重分配
  • ip_hash:基于IP的哈希分配(会话保持)
  • least_conn:最少连接数优先
  • fair:响应时间优先(需要第三方模块)

2. 反向代理配置

server {
  listen 443 ssl http2;  # 启用HTTP/2
  server_name example.com;
  
  # SSL配置
  ssl_certificate /etc/nginx/ssl/cert.pem;
  ssl_certificate_key /etc/nginx/ssl/key.pem;
  ssl_protocols TLSv1.2 TLSv1.3;
  ssl_prefer_server_ciphers on;
  ssl_session_cache shared:SSL:10m;
  ssl_session_timeout 10m;
  
  location /api/ {
    proxy_pass http://backend-api/;
    
    # WebSocket支持
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }
}

二、安全防护配置

1. 限流配置

# 定义限流区域(内存区10MB,每秒10个请求)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;

server {
  location /api/ {
    # 应用限流(突发20个请求)
    limit_req zone=api_limit burst=20 nodelay;
    
    # 限制单个IP并发连接数
    limit_conn perip 10;
    
    proxy_pass http://backend-api/;
  }
}

2. 访问控制

# IP黑白名单
geo $block {
  default 1;  # 默认禁止
  192.168.1.0/24 0;  # 允许内网
  10.0.0.0/8 0;      # 允许内网
}

server {
  if ($block) {
    return 403 "Forbidden";
  }
  
  # 限制HTTP方法
  limit_except GET POST { deny all; }
}

3. 安全头部

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

三、性能优化配置

1. 静态资源缓存

location ~* \.(?:jpg|jpeg|png|gif|ico|css|js|woff2)$ {
  expires 365d;
  access_log off;
  add_header Cache-Control "public, immutable";
  
  # 开启gzip
  gzip_static on;
  gzip_proxied any;
}

2. 连接优化

# 全局连接优化
keepalive_timeout 75s;
keepalive_requests 10000;
client_header_timeout 15s;
client_body_timeout 15s;
send_timeout 15s;

# TCP优化
tcp_nopush on;
tcp_nodelay on;
types_hash_max_size 2048;
server_names_hash_bucket_size 128;

四、日志管理

1. JSON格式日志

log_format json_combined escape=json
  '{'
    '"timestamp":"$time_iso8601",'
    '"remote_addr":"$remote_addr",'
    '"remote_user":"$remote_user",'
    '"request":"$request",'
    '"status":"$status",'
    '"body_bytes_sent":"$body_bytes_sent",'
    '"request_time":"$request_time",'
    '"http_referer":"$http_referer",'
    '"http_user_agent":"$http_user_agent",'
    '"http_x_forwarded_for":"$http_x_forwarded_for"'
  '}';

access_log /var/log/nginx/access.log json_combined buffer=32k flush=5m;

五、高级功能

1. 灰度发布

map $http_cookie $upstream_group {
  ~*"gray=true" "gray";
  default "production";
}

upstream production {
  server 192.168.1.101:8080;
}

upstream gray {
  server 192.168.1.102:8080;
}

server {
  location / {
    proxy_pass http://$upstream_group;
  }
}

2. 地理位置限制

load_module modules/ngx_http_geoip2_module.so;  # 需要安装模块

http {
  geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
    $geoip2_data_country_code country iso_code;
  }
  
  map $geoip2_data_country_code $allowed_country {
    CN 1;  # 允许中国
    US 1;  # 允许美国
    default 0;
  }
}

server {
  if ($allowed_country = 0) {
    return 403 "Access denied for your country";
  }
}
复制全文 生成海报 Nginx Web服务器 网络安全 性能优化

推荐文章

在Rust项目中使用SQLite数据库
2024-11-19 08:48:00 +0800 CST
使用Python提取图片中的GPS信息
2024-11-18 13:46:22 +0800 CST
Go 接口:从入门到精通
2024-11-18 07:10:00 +0800 CST
20个超实用的CSS动画库
2024-11-18 07:23:12 +0800 CST
Nginx 反向代理 Redis 服务
2024-11-19 09:41:21 +0800 CST
Vue3中如何进行错误处理?
2024-11-18 05:17:47 +0800 CST
15 个你应该了解的有用 CSS 属性
2024-11-18 15:24:50 +0800 CST
deepcopy一个Go语言的深拷贝工具库
2024-11-18 18:17:40 +0800 CST
Vue 3 是如何实现更好的性能的?
2024-11-19 09:06:25 +0800 CST
Requests库详细介绍
2024-11-18 05:53:37 +0800 CST
资源文档库
2024-12-07 20:42:49 +0800 CST
全栈利器 H3 框架来了!
2025-07-07 17:48:01 +0800 CST
`Blob` 与 `File` 的关系
2025-05-11 23:45:58 +0800 CST
Go的父子类的简单使用
2024-11-18 14:56:32 +0800 CST
支付页面html收银台
2025-03-06 14:59:20 +0800 CST
MySQL 1364 错误解决办法
2024-11-19 05:07:59 +0800 CST
Linux 常用进程命令介绍
2024-11-19 05:06:44 +0800 CST
程序员茄子在线接单