适用人群:后端开发者、运维工程师
学习时长:约1-2天
重要程度:★★★★☆(部署必备)
一、Nginx 是什么?
Nginx 是高性能的Web服务器和反向代理服务器,全球超过60%的网站使用Nginx。
| 功能 | 说明 |
|---|---|
| Web服务器 | 静态文件服务 |
| 反向代理 | 转发请求到后端服务 |
| 负载均衡 | 分发流量到多台服务器 |
| HTTPS | SSL证书配置 |
| 缓存 | 静态资源缓存 |
二、安装
# Ubuntu
sudo apt update
sudo apt install nginx
# CentOS
sudo yum install epel-release
sudo yum install nginx
# 启动
sudo systemctl start nginx
sudo systemctl enable nginx
# 检查状态
sudo systemctl status nginx
nginx -v
三、基本配置
3.1 配置文件结构
# /etc/nginx/nginx.conf
# 全局配置
user www-data;
worker_processes auto; # 自动设置为CPU核心数
pid /run/nginx.pid;
# 事件配置
events {
worker_connections 1024; # 单个worker最大连接数
}
# HTTP配置
http {
# 基础配置
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# MIME类型
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;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
# 引入站点配置
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
3.2 虚拟主机(站点配置)
# /etc/nginx/sites-available/my-site
server {
# 监听端口
listen 80;
listen [::]:80;
# 域名
server_name example.com www.example.com;
# 网站根目录
root /var/www/html;
index index.html index.php;
# 访问日志
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
# 主要规则
location / {
try_files $uri $uri/ /index.php?$query_string;
}
}
四、反向代理配置
4.1 代理Node.js应用
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
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;
proxy_cache_bypass $http_upgrade;
}
}
4.2 代理PHP-FPM
server {
listen 80;
server_name example.com;
root /var/www/html/public;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_buffering off;
}
location ~ /\.ht {
deny all;
}
}
4.3 代理Python/Go应用
# Python Flask/Gunicorn
upstream python_app {
server 127.0.0.1:5000;
}
# Go应用
upstream go_app {
server 127.0.0.1:8080;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://python_app;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
五、HTTPS配置
5.1 Let's Encrypt 免费证书
# 安装Certbot
sudo apt install certbot python3-certbot-nginx
# 获取证书
sudo certbot --nginx -d example.com -d www.example.com
# 自动续期
sudo certbot renew --dry-run
5.2 手动配置SSL
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.pem;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers off;
# HSTS
add_header Strict-Transport-Security "max-age=63072000" always;
root /var/www/html;
}
# HTTP跳转HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
六、负载均衡
# 负载均衡配置
upstream backend {
# 轮询(默认)
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
# 加权轮询
# server 192.168.1.10:8080 weight=3;
# server 192.168.1.11:8080 weight=2;
# server 192.168.1.12:8080 weight=1;
# IP Hash(会话保持)
# ip_hash;
# 最少连接
# least_conn;
# 备用服务器
# server 192.168.1.13:8080 backup;
# 健康检查
# server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
七、静态资源配置
server {
listen 80;
server_name static.example.com;
root /var/www/static;
# 静态文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|woff|ttf)$ {
expires 30d;
add_header Cache-Control "public, immutable";
access_log off;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 禁止访问特定文件
location ~* \.(env|git|svn)$ {
deny all;
}
}
八、安全配置
server {
listen 80;
server_name example.com;
# 安全头
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 Content-Security-Policy "default-src 'self' http: https: ws: wss: data: blob: 'unsafe-inline'; frame-ancestors 'self';" always;
# 限制请求大小
client_max_body_size 10M;
# 限制请求速率
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
# 基本认证(简单保护)
location /admin/ {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://backend;
}
}
九、常见问题排查
# 测试配置
sudo nginx -t
# 重新加载配置
sudo nginx -s reload
# 查看错误日志
sudo tail -f /var/log/nginx/error.log
# 查看访问日志
sudo tail -f /var/log/nginx/access.log
# 检查端口占用
sudo netstat -tlnp | grep :80
sudo netstat -tlnp | grep :443
# 常见错误
# 403 Forbidden:检查文件权限和index配置
# 502 Bad Gateway:检查后端服务是否运行
# 504 Gateway Timeout:检查proxy_read_timeout配置
十、配置速查表
| 场景 | 配置 |
|---|---|
| 静态网站 | root /var/www/html; |
| PHP应用 | fastcgi_pass unix:/run/php/php8.2-fpm.sock; |
| Node.js | proxy_pass http://127.0.0.1:3000; |
| SSL证书 | ssl_certificate /path/to/cert.pem; |
| 负载均衡 | upstream backend { server ...; } |
| URL重写 | try_files $uri $uri/ /index.php; |
| 缓存 | expires 30d; |
| 限流 | limit_req zone=api burst=20; |
学习建议
- 先理解正向代理和反向代理的区别
- 掌握location匹配规则,这是Nginx的核心
- 学会配置PHP和Node.js的代理
- 配置HTTPS,现代网站必备
- 学会查看日志,排查问题的关键