Nginx详细配置说明
以下是关于 Nginx 配置的详细说明,涵盖核心概念、常用配置及实际示例:
一、Nginx 核心配置文件结构
Nginx 的主配置文件通常位于 /etc/nginx/nginx.conf
,其结构分为多个上下文块(Context):
# 全局块(全局配置,影响所有部分)
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;# Events块(网络连接配置)
events {worker_connections 1024;
}# HTTP块(核心HTTP配置)
http {include /etc/nginx/mime.types;default_type application/octet-stream;# Server块(虚拟主机配置)server {listen 80;server_name example.com;root /var/www/html;}
}
二、核心配置指令详解
1. 虚拟主机(Server Block)
server {listen 80; # 监听端口server_name example.com www.example.com; # 域名root /var/www/html; # 网站根目录index index.html index.php; # 默认首页文件# 访问日志和错误日志access_log /var/log/nginx/access.log;error_log /var/log/nginx/error.log;
}
2. 反向代理
location / {proxy_pass http://localhost:3000; # 转发到本地3000端口proxy_set_header Host $host; # 传递原始Host头proxy_set_header X-Real-IP $remote_addr;
}
3. 负载均衡
upstream backend {server 192.168.1.1:80 weight=3; # 权重3server 192.168.1.2:80;server 192.168.1.3:80 backup; # 备用服务器
}server {location / {proxy_pass http://backend;}
}
4. HTTPS 配置
server {listen 443 ssl;server_name example.com;# SSL证书路径ssl_certificate /etc/ssl/certs/example.com.crt;ssl_certificate_key /etc/ssl/private/example.com.key;# 安全协议配置ssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers HIGH:!aNULL:!MD5;
}
5. 静态文件缓存
location ~* \.(jpg|png|css|js)$ {expires 30d; # 缓存30天add_header Cache-Control "public";access_log off; # 关闭日志记录
}
6. URL 重写(Rewrite)
location /old {rewrite ^/old/(.*)$ /new/$1 permanent; # 301重定向
}# 隐藏index.php(常见于PHP项目)
location / {try_files $uri $uri/ /index.php?$query_string;
}
7. 限制访问
# IP白名单
location /admin {allow 192.168.1.100;deny all;
}# 基础认证
location /secure {auth_basic "Restricted";auth_basic_user_file /etc/nginx/.htpasswd;
}
三、常用场景配置示例
1. 单页应用(SPA)配置
server {root /var/www/react-app;index index.html;location / {try_files $uri $uri/ /index.html; # 处理前端路由}
}
2. PHP-FPM 支持(如WordPress)
location ~ \.php$ {fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;fastcgi_index index.php;include fastcgi_params;fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
3. WebSocket 代理
location /ws {proxy_pass http://backend;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";
}
4. 跨域配置
location /api {add_header 'Access-Control-Allow-Origin' '*';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,Content-Type';
}
四、性能优化参数
http {# 开启高效文件传输模式sendfile on;tcp_nopush on;# 连接超时时间keepalive_timeout 65;client_max_body_size 100m; # 上传文件大小限制# Gzip压缩gzip on;gzip_types text/plain text/css application/json;
}
五、调试与维护命令
#检查配置语法
nginx -t#重新加载配置(不中断服务)
nginx -s reload#查看运行状态
systemctl status nginx
六、常见问题解决
-
403 Forbidden
-
检查
root
目录权限:chown -R nginx:nginx /var/www
-
确保
index
文件存在
-
-
502 Bad Gateway
-
后端服务(如PHP-FPM)是否运行
-
检查
proxy_pass
或fastcgi_pass
地址
-
-
地址冲突
-
使用
netstat -tulnp | grep 80
检查端口占用
-
通过合理配置 Nginx,可以实现高性能的 Web 服务、反向代理和负载均衡。建议结合具体需求调整参数,并通过 nginx -t
测试后再应用更改。