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

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

#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服务器 网络安全 性能优化

推荐文章

liunx宝塔php7.3安装mongodb扩展
2024-11-17 11:56:14 +0800 CST
防止 macOS 生成 .DS_Store 文件
2024-11-19 07:39:27 +0800 CST
WebSQL数据库:HTML5的非标准伴侣
2024-11-18 22:44:20 +0800 CST
18个实用的 JavaScript 函数
2024-11-17 18:10:35 +0800 CST
PHP中获取某个月份的天数
2024-11-18 11:28:47 +0800 CST
Vue3中如何处理WebSocket通信?
2024-11-19 09:50:58 +0800 CST
Graphene:一个无敌的 Python 库!
2024-11-19 04:32:49 +0800 CST
Golang - 使用 GoFakeIt 生成 Mock 数据
2024-11-18 15:51:22 +0800 CST
Go配置镜像源代理
2024-11-19 09:10:35 +0800 CST
Vue 3 是如何实现更好的性能的?
2024-11-19 09:06:25 +0800 CST
38个实用的JavaScript技巧
2024-11-19 07:42:44 +0800 CST
开发外贸客户的推荐网站
2024-11-17 04:44:05 +0800 CST
Golang Sync.Once 使用与原理
2024-11-17 03:53:42 +0800 CST
网络数据抓取神器 Pipet
2024-11-19 05:43:20 +0800 CST
mysql时间对比
2024-11-18 14:35:19 +0800 CST
Rust 中的所有权机制
2024-11-18 20:54:50 +0800 CST
Redis函数在PHP中的使用方法
2024-11-19 04:42:21 +0800 CST
MySQL 1364 错误解决办法
2024-11-19 05:07:59 +0800 CST
Vue3中如何进行性能优化?
2024-11-17 22:52:59 +0800 CST
程序员茄子在线接单