以下是一个详细的Nginx配置使用实例分析,涵盖常见场景和最佳实践:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
}
关键点:
- listen
指定监听端口
- server_name
绑定域名
- root
设置网站根目录
- try_files
实现优雅的404处理
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
root /var/www/html;
index index.html;
# HSTS增强安全
add_header Strict-Transport-Security "max-age=31536000" always;
}
安全建议: 1. 使用Let's Encrypt免费证书 2. 禁用旧版TLS协议(如TLSv1.0) 3. 启用HTTP/2提升性能
upstream backend {
least_conn; # 最少连接算法
server 192.168.1.10:8000 weight=3;
server 192.168.1.11:8000;
server 192.168.1.12:8000 backup; # 备用服务器
}
server {
listen 80;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
负载均衡策略:
- round-robin
(默认)
- least_conn
- ip_hash
(会话保持)
server {
location / {
proxy_pass http://backend;
}
location /static/ {
alias /var/www/static/;
expires 30d; # 缓存控制
}
location ~* \.(jpg|png|gif)$ {
root /var/www/images;
access_log off; # 不记录静态资源访问日志
}
}
优化建议:
- 静态资源设置长期缓存
- 禁用静态资源访问日志
- 使用alias
处理非root路径
location /ws/ {
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location ~* \.(jpg|png)$ {
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}
}
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
location /api/ {
limit_req zone=api_limit burst=20;
proxy_pass http://api_backend;
}
日志分析:
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
性能调优参数:
worker_processes auto; # 自动匹配CPU核心数
worker_connections 1024; # 每个worker最大连接数
keepalive_timeout 65; # 长连接超时
gzip on; # 启用压缩
配置检查命令:
nginx -t # 测试配置语法
nginx -T # 查看完整配置
502 Bad Gateway:
proxy_read_timeout
值413 Request Entity Too Large:
client_max_body_size 20M;
性能瓶颈:
sendfile on;
通过以上配置示例,可以快速搭建高性能的Web服务。实际应用中建议:
1. 根据业务需求选择合适配置
2. 使用include
指令模块化管理配置
3. 定期检查Nginx错误日志(/var/log/nginx/error.log
)
需要更具体的配置方案,可以提供您的具体应用场景。