Nginx高性能配置实战:从入门到优化
一、Nginx简介
Nginx是一款高性能的HTTP和反向代理服务器,以其高并发、低内存占用、稳定性强而著称。作为Web服务器,Nginx能够处理数万并发连接,是现代Web架构中不可或缺的组件。
Nginx的核心优势:
- 高并发处理:单台服务器可支持数万并发连接
- 内存占用低:相比Apache,内存使用量减少70%以上
- 配置简洁:模块化设计,配置文件易于维护
- 扩展性强:丰富的第三方模块生态
- 热部署:支持平滑升级,不中断服务
二、基础安装与配置
Ubuntu系统安装:
# 更新软件源
sudo apt update
# 安装Nginx
sudo apt install nginx
# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
# 检查状态
sudo systemctl status nginxCentOS系统安装:
# 添加EPEL源
sudo yum install epel-release
# 安装Nginx
sudo yum install nginx
# 启动服务
sudo systemctl start nginx
sudo systemctl enable nginx主配置文件结构:
# 全局配置
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
# 基础配置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志配置
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# Gzip压缩
gzip on;
# 虚拟主机
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}三、高性能核心配置优化
1. Worker进程优化
# 设置为CPU核心数
worker_processes auto;
# 绑定CPU核心(可选)
worker_cpu_affinity auto;
# 每个worker的最大文件打开数
worker_rlimit_nofile 65535;2. Events模块优化
events {
# 使用epoll事件模型
use epoll;
# 每个worker的最大连接数
worker_connections 65535;
# 一次接受多个连接
multi_accept on;
}3. HTTP核心优化
http {
# 高效文件传输
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 长连接超时
keepalive_timeout 60;
keepalive_requests 1000;
# 客户端请求限制
client_max_body_size 100M;
client_body_buffer_size 128k;
client_header_buffer_size 4k;
large_client_header_buffers 4 32k;
# 超时设置
client_body_timeout 10;
client_header_timeout 10;
send_timeout 10;
}四、Gzip压缩配置
http {
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/xml
application/x-font-ttf
font/opentype
image/svg+xml
image/x-icon;
}五、静态资源缓存优化
server {
# 图片缓存
location ~* \.(jpg|jpeg|png|gif|ico|svg|webp)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
# CSS/JS缓存
location ~* \.(css|js)$ {
expires 7d;
add_header Cache-Control "public";
}
# 字体文件缓存
location ~* \.(woff|woff2|ttf|eot)$ {
expires 365d;
add_header Cache-Control "public, immutable";
access_log off;
}
}六、反向代理配置
基础反向代理:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1: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;
proxy_set_header X-Forwarded-Proto $scheme;
}
}代理缓存配置:
# http块中配置缓存路径
proxy_cache_path /var/cache/nginx
levels=1:2
keys_zone=my_cache:10m
max_size=10g
inactive=60m
use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_lock on;
add_header X-Cache-Status $upstream_cache_status;
}
}七、负载均衡配置
轮询模式(默认):
upstream backend {
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
}
server {
location / {
proxy_pass http://backend;
}
}权重模式:
upstream backend {
server 192.168.1.101:8080 weight=3;
server 192.168.1.102:8080 weight=2;
server 192.168.1.103:8080 weight=1;
}IP哈希(会话保持):
upstream backend {
ip_hash;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
server 192.168.1.103:8080;
}最少连接:
upstream backend {
least_conn;
server 192.168.1.101:8080;
server 192.168.1.102:8080;
}八、HTTPS与SSL配置
SSL安全配置:
server {
listen 443 ssl http2;
server_name example.com;
# 证书配置
ssl_certificate /etc/nginx/ssl/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/privkey.pem;
# SSL协议优化
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
# SSL会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
# HSTS
add_header Strict-Transport-Security "max-age=63072000" always;
}HTTP强制跳转HTTPS:
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}九、安全加固配置
隐藏版本信息:
server_tokens off;禁止访问敏感文件:
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
location ~ ~$ {
deny all;
access_log off;
log_not_found off;
}限制请求方法:
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}防爬虫配置:
if ($http_user_agent ~* (Scrapy|Curl|HttpClient|python-requests)) {
return 403;
}十、状态监控与日志分析
启用状态页面:
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}日志格式优化:
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$request_time $upstream_response_time';十一、常用运维命令
# 测试配置文件
nginx -t
# 平滑重载配置
nginx -s reload
# 优雅停止
nginx -s quit
# 强制停止
nginx -s stop
# 重新打开日志文件
nginx -s reopen
# 查看版本
nginx -v
# 查看编译参数
nginx -V总结
Nginx的性能优化是一个系统性工程,需要根据实际业务场景进行调优。通过合理配置worker进程、优化事件模型、启用压缩缓存、配置负载均衡等手段,可以显著提升Web服务的性能和稳定性。
建议在生产环境中:
- 定期进行压力测试,验证配置效果
- 监控Nginx运行状态和性能指标
- 及时更新Nginx版本,修复安全漏洞
- 根据业务增长动态调整配置参数