Nginx 配置:基础到 HTTPS 自动化
发布于 2026/04/12 · 公开
## 1. Nginx 基础配置结构
Nginx 的配置文件(通常位于 /etc/nginx/nginx.conf)采用层级结构。最常用的配置是在 http 块下的 server 块。
# 运行用户
user www-data;
worker_processes auto;
events {
worker_connections 1024;
}
http {
# 基础设置
include mime.types;
default_type application/octet-stream;
sendfile on;
# 虚拟主机配置
server {
listen 80;
server_name example.com www.example.com;
# 根目录设置
location / {
root /var/www/html;
index index.html index.htm;
}
# 错误页面处理
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
## 2. 常用功能配置
### 反向代理 (Reverse Proxy)
这是 Nginx 最核心的进阶用法之一,常用于将流量转发给后端应用(如 Node.js, Python, Java)。
location /api/ {
proxy_pass http://localhost:3000; # 后端服务地址
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;
}
### 开启 Gzip 压缩
显著提升网页加载速度,减少带宽消耗。
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_proxied any;
gzip_min_length 1000;
## 3. 进阶知识:Certbot 与 HTTPS 自动化
在现代互联网中,HTTPS 是标配。Certbot 是由 EFF 提供的工具,可以自动获取和续期 Let's Encrypt 的免费 SSL 证书,并自动修改 Nginx 配置。
### 安装与使用步骤
- 安装 Certbot:
sudo apt update sudo apt install certbot python3-certbot-nginx - 获取并部署证书:
执行以下命令,Certbot 会自动识别你的server_name并引导你完成配置。sudo certbot --nginx -d example.com -d www.example.com - 自动续期测试:
Let's Encrypt 证书有效期为 90 天,Certbot 通常会自动创建定时任务。你可以通过此命令测试续期流程:sudo certbot renew --dry-run
## 4. Nginx 性能优化小贴士
- 缓存配置:利用
proxy_cache减少后端服务器压力。 - 负载均衡:使用
upstream块分发流量。 - 安全加固:
- 隐藏版本号:
server_tokens off; - 限制请求速率:
limit_req_zone防止暴力攻击。
- 隐藏版本号:
## 5. 配置检查与生效
每次修改完配置文件后,务必执行以下操作:
- 语法检查:
sudo nginx -t - 重新加载(不停机热加载):
sudo systemctl reload nginx
注意:在配置 Certbot 之前,请确保你的域名 A 记录已经正确指向了服务器的公网 IP,且服务器的 80 和 443 端口已在防火墙中开启。