Nginx
- 什么是Nginx
- 一、基础入门
-
- [1.1、Nginx 架构原理](#1.1、Nginx 架构原理)
- 1.2、安装部署
- 1.3、配置文件结构(nginx.conf)
- 1.4、核心指令
- [1.5、location 匹配规则(重要!)](#1.5、location 匹配规则(重要!))
- 1.6、日志管理
- 二、反向代理与负载均衡
- 三、高级功能与安全加固
- 四、性能优化与监控
-
- 4.1、工作进程调优
- 4.2、静态文件优化
- [4.3、Gzip 压缩](#4.3、Gzip 压缩)
- 4.4、代理缓存
- 4.5、监控与状态页
- 五、文件参考
什么是Nginx
Nginx(发音 "engine-x")是一款高性能的 HTTP 服务器 和 反向代理服务器,同时也可以作为邮件代理服务器和通用的 TCP/UDP 代理服务器。
核心特点
| 特点 | 说明 |
|---|---|
| 高并发 | 采用异步非阻塞的事件驱动架构,单机可处理数万甚至数十万并发连接 |
| 低内存消耗 | 相比 Apache,同等连接数下内存占用极低 |
| 反向代理 | 可将请求分发到后端多个应用服务器(如 Tomcat、Node.js、Python) |
| 负载均衡 | 支持轮询、IP哈希、最少连接等多种负载均衡算法 |
| 静态文件服务 | 处理静态文件(HTML/CSS/JS/图片)性能极佳 |
| 高可靠性 | 长时间运行稳定,号称"永不宕机" |
典型使用场景
- 静态文件服务器:直接托管网站的前端资源
- 反向代理 + 负载均衡:将请求分发到多个后端应用服务器
- API 网关:统一入口、鉴权、限流、路由转发
- SSL/TLS 终结:集中管理 HTTPS 证书
- 缓存服务器:缓存后端响应,减轻应用服务器压力
一、基础入门
1.1、Nginx 架构原理
| 概念 | 说明 |
|---|---|
| 主进程(Master) | 负责读取配置、管理工作进程、接收外部信号 |
| 工作进程(Worker) | 实际处理客户端请求,多个 Worker 可并行 |
| 事件驱动模型 | 异步非阻塞,单 Worker 可处理成千上万连接 |
1.2、安装部署
1.3、配置文件结构(nginx.conf)
bash
http { # HTTP 全局配置
include mime.types;
default_type application/octet-stream;
server { # 虚拟主机(站点)
listen 80; # 监听端口
server_name localhost; # 域名
location / { # URL 路径匹配
root html; # 网站根目录
index index.html;
}
location /images/ {
alias D:/static/images/;
}
}
}
上下文层级(从大到小):
main → events → http → server → location
1.4、核心指令
| 指令 | 作用 | 示例 |
|---|---|---|
listen |
监听端口 | listen 80; / listen 443 ssl; |
server_name |
匹配域名 | server_name example.com www.example.com; |
root |
指定根目录 | root /var/www/html; |
alias |
路径别名 | location /img/ { alias /data/images/; } |
index |
默认首页 | index index.html index.htm; |
error_page |
自定义错误页 | error_page 404 /404.html; |
1.5、location 匹配规则(重要!)
| 写法 | 匹配类型 | 优先级 |
|---|---|---|
location = /exact |
精确匹配 | 最高 |
location ^~ /static/ |
前缀匹配(非正则) | 次高 |
location ~ \.php$ |
正则匹配(大小写敏感) | 中 |
location ~* \.jpg$ |
正则匹配(不敏感) | 中 |
location / |
通用匹配 | 最低 |
1.6、日志管理
日志格式(可自定义):
nginx
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent"';
access_log logs/access.log main;
error_log logs/error.log warn;
常用变量:
$remote_addr:客户端 IP$request:完整请求行(如GET /index.html HTTP/1.1)$status:响应状态码$http_referer:来源页面
二、反向代理与负载均衡
2.1、反向代理基础
核心指令:proxy_pass
nginx
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:3000; # 转发到后端 Node.js 应用
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
常用代理头:
| 头部 | 作用 |
|---|---|
X-Real-IP |
传递真实客户端 IP |
X-Forwarded-For |
记录代理链 IP |
X-Forwarded-Proto |
传递原始协议(http/https) |
2.2、负载均衡
定义后端服务器组:
nginx
upstream backend_servers {
# 负载均衡算法(见下表)
server 192.168.1.10:8080 weight=3; # weight 权重,默认1
server 192.168.1.11:8080;
server 192.168.1.12:8080 backup; # 备份服务器
}
server {
location / {
proxy_pass http://backend_servers;
}
}
负载均衡算法:
| 算法 | 指令 | 说明 |
|---|---|---|
| 轮询 | 默认 | 按顺序轮流分配 |
| 加权轮询 | weight=3 |
权重高的分配更多请求 |
| IP Hash | ip_hash; |
同一 IP 固定到同一台服务器 |
| 最少连接 | least_conn; |
分配给当前连接数最少的服务器 |
| 随机 | random; |
随机选择 |
2.3、健康检查(被动)
nginx
upstream backend {
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
# 30秒内失败3次则标记为不可用,30秒后再尝试
}
| 参数 | 默认值 | 说明 |
|---|---|---|
max_fails |
1 | 允许的最大失败次数 |
fail_timeout |
10s | 失败计数的时间窗口,以及标记不可用的时长 |
2.4、代理缓冲区与超时调优
nginx
location / {
proxy_pass http://backend;
# 缓冲区设置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
# 超时设置
proxy_connect_timeout 60s; # 连接后端超时
proxy_send_timeout 60s; # 发送请求超时
proxy_read_timeout 60s; # 接收响应超时
}
三、高级功能与安全加固
3.1、HTTPS 配置
步骤概览:
- 获取 SSL 证书(Let's Encrypt / 自签名 / 云服务商)
- 配置
server块监听 443 端口 - 配置证书路径和 SSL 参数
基础配置:
nginx
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/private.key;
# 推荐的安全配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# 其余 location 配置...
}
# HTTP 强制跳转 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
3.2、访问控制
基于 IP 的访问控制:
nginx
location /admin {
allow 192.168.1.0/24; # 允许内网
deny all; # 拒绝其他所有
}
基于用户名密码(HTTP Basic Auth):
bash
# 生成密码文件(需要 htpasswd 工具)
htpasswd -c /etc/nginx/.htpasswd user1
nginx
location /private {
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
}
3.3、限流限速
| 功能 | 指令模块 | 示例 |
|---|---|---|
| 请求频率限制 | limit_req |
limit_req zone=mylimit burst=20 nodelay; |
| 并发连接限制 | limit_conn |
limit_conn addr 10; |
| 下载带宽限制 | limit_rate |
limit_rate 200k; |
完整示例:
nginx
# 在 http 块中定义区域
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
limit_conn conn_limit 10;
limit_rate 500k;
proxy_pass http://backend;
}
}
3.4、防盗链
nginx
location ~* \.(jpg|jpeg|png|gif)$ {
valid_referers none blocked *.example.com example.com;
if ($invalid_referer) {
return 403;
# 或返回防盗链图片:rewrite ^/ /images/steal.jpg break;
}
}
3.5、URL 重写与重定向
| 指令 | 作用 | 示例 |
|---|---|---|
return |
直接返回状态码和内容 | return 404; / return 301 /new; |
rewrite |
重写 URL 并可选择性重定向 | rewrite ^/old/(.*)$ /new/$1 permanent; |
try_files |
按顺序检查文件是否存在 | try_files $uri $uri/ /index.html; |
常用正则:
^:开头$:结尾(.*):捕获任意内容$1、$2:引用捕获的内容
四、性能优化与监控
4.1、工作进程调优
nginx
# 主配置文件开头
worker_processes auto; # 自动匹配 CPU 核心数
worker_rlimit_nofile 65535; # 单进程最大打开文件数
events {
worker_connections 10240; # 单进程最大并发连接数
use epoll; # Linux 下使用 epoll(Windows 不需要)
multi_accept on; # 一次接受所有新连接
}
计算公式: 最大并发数 = worker_processes × worker_connections
4.2、静态文件优化
nginx
location ~* \.(css|js|jpg|png|gif|ico)$ {
expires 30d; # 设置浏览器缓存 30 天
add_header Cache-Control "public, immutable";
open_file_cache max=1000 inactive=20s; # 缓存文件句柄
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
}
4.3、Gzip 压缩
nginx
http {
gzip on;
gzip_vary on;
gzip_min_length 1024; # 小于 1KB 不压缩
gzip_comp_level 6; # 压缩级别 1-9(越高越耗 CPU)
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_disable "MSIE [1-6]\."; # 兼容旧浏览器
}
4.4、代理缓存
nginx
# 在 http 块中定义缓存路径
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m max_size=1g inactive=60m;
server {
location / {
proxy_cache mycache;
proxy_cache_key "$host$request_uri";
proxy_cache_valid 200 302 60m; # 成功响应缓存 60 分钟
proxy_cache_valid 404 1m; # 404 缓存 1 分钟
proxy_cache_use_stale error timeout; # 后端异常时使用过期缓存
add_header X-Cache-Status $upstream_cache_status; # 返回缓存命中状态
proxy_pass http://backend;
}
}
缓存状态(响应头 X-Cache-Status):
MISS:未命中HIT:命中缓存EXPIRED:已过期UPDATING:正在更新BYPASS:绕过缓存
4.5、监控与状态页
启用 stub_status 模块:
nginx
server {
listen 80;
server_name monitor.example.com;
location /nginx_status {
stub_status;
allow 127.0.0.1; # 仅允许本机访问
deny all;
}
}
访问 http://monitor.example.com/nginx_status 返回示例:
Active connections: 12
server accepts handled requests
123 123 456
Reading: 0 Writing: 1 Waiting: 11
| 指标 | 含义 |
|---|---|
| Active connections | 当前活跃连接数 |
| accepts / handled / requests | 总接受连接 / 成功处理 / 总请求数 |
| Reading / Writing / Waiting | 读取请求头 / 写响应 / 空闲长连接数 |
五、文件参考
bash
│ nginx.exe # Nginx 主程序文件,启动/停止/重载服务的可执行文件
│
├─conf/
│ │ fastcgi.conf # FastCGI 配置文件,定义了PHP等动态程序与Nginx通信的参数
│ │ fastcgi_params # FastCGI 参数文件,包含常用的CGI环境变量(SCRIPT_FILENAME等)
│ │ koi-utf # 字符集转换文件,用于KOI8-R到UTF-8的编码转换
│ │ koi-win # 字符集转换文件,用于KOI8-R到Windows-1251的编码转换
│ │ mime.types # MIME类型映射文件,定义文件扩展名对应的Content-Type
│ │ nginx.conf # Nginx主配置文件!最重要的文件,控制整个服务器行为
│ │ scgi_params # SCGI协议参数文件,用于与SCGI应用程序通信
│ │ uwsgi_params # uWSGI协议参数文件,用于与Python uWSGI应用通信
│ │ win-utf # 字符集转换文件,用于Windows编码到UTF-8的转换
│ │
│ ├─ssl/ # SSL证书目录(当前为空),存放HTTPS的证书和私钥文件
│ │
│ └─vhosts/ # 虚拟主机配置目录
│ 0localhost_80.conf # localhost:80的虚拟主机配置(可能端口0是占位符)
│ default-default.conf # 默认虚拟主机配置文件
│
├─contrib/
│ │ geo2nginx.pl # Perl脚本,将GeoIP地理数据库转换为Nginx格式
│ │ README # 贡献工具的使用说明文档
│ │
│ ├─unicode2nginx/ # Unicode转换工具目录
│ │ koi-utf # KOI8到UTF-8转换表
│ │ unicode-to-nginx.pl # Perl脚本,将Unicode编码转换为Nginx配置格式
│ │ win-utf # Windows编码到UTF-8转换表
│ │
│ └─vim/ # Vim编辑器支持文件
│ ├─ftdetect/
│ │ nginx.vim # Vim文件类型检测脚本,识别nginx配置文件
│ │
│ ├─ftplugin/
│ │ nginx.vim # Vim文件类型插件,提供nginx配置语法高亮
│ │
│ ├─indent/
│ │ nginx.vim # Vim缩进规则,自动格式化nginx配置缩进
│ │
│ └─syntax/
│ nginx.vim # Vim语法高亮文件,高亮nginx配置语法
│
├─docs/
│ CHANGES # Nginx版本更新日志(英文)
│ CHANGES.ru # Nginx版本更新日志(俄文)
│ LICENSE # Nginx软件许可证(BSD协议)
│ OpenSSL.LICENSE # OpenSSL库的许可证文件
│ PCRE.LICENCE # PCRE正则表达式库的许可证
│ README # 说明文档
│ zlib.LICENSE # zlib压缩库的许可证
│
├─logs/
│ access.log # 访问日志,记录所有HTTP请求(IP、时间、URL、状态码等)
│ error.log # 错误日志,记录Nginx运行时错误、警告信息
│ nginx.pid # 进程ID文件,记录Nginx主进程的PID,用于平滑重启
│
└─temp/
│ XP # 可能是临时标记文件或缓存索引文件
│
├─client_body_temp/ # 客户端请求体临时目录(上传大文件时的临时存储)
├─fastcgi_temp/ # FastCGI临时文件目录
│ └─1/ # 临时文件子目录
│ └─00/ # 二级临时目录(Nginx自动创建管理)
├─proxy_temp/ # 代理临时目录(反向代理时的缓存文件)
├─scgi_temp/ # SCGI协议临时文件目录
└─uwsgi_temp/ # uWSGI协议临时文件目录(Python应用)
5.1、nginx.conf
bash
# 注释掉的配置,指定Nginx工作进程的运行用户(nobody是低权限用户,更安全)
#user nobody;
# 工作进程数量:Nginx启动多少个进程处理请求。通常设置为CPU核心数,4表示启动4个进程
worker_processes 4;
# 错误日志配置:记录Nginx运行时的错误信息。级别从低到高:debug > info > notice > warn > error > crit
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
# 进程ID文件:记录Nginx主进程的PID,用于管理Nginx进程
#pid logs/nginx.pid;
events {
# 每个工作进程的最大连接数:40960表示单个worker进程最多同时处理40960个连接
# 最大并发连接数 = worker_processes × worker_connections= 4 × 40960 = 163,840 个并发连接
worker_connections 40960;
}
http {
# 引入MIME类型文件:定义文件扩展名对应的Content-Type(如.css→text/css)
include mime.types;
# 默认MIME类型:当无法识别文件类型时,作为二进制流处理
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
# 高效文件传输:启用内核态直接发送文件,减少用户态和内核态切换,提高性能
sendfile on;
#tcp_nopush on;
# 长连接超时:客户端连接保持65秒,减少重复建立连接的开销
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
# ==============================================
# 测试服务器配置(允许所有IP访问)
# ==============================================
# 虚拟主机配置块:定义一个网站服务
server {
# 添加这两行,允许所有IP访问
allow all;
# 如果需要拒绝某些IP,写在后面
# deny all;
# 监听端口,允许所有IP访问
listen 80;
# 服务器域名,* 表示匹配所有域名
server_name localhost;
# 设置字符集
charset utf-8;
# 网站根目录(重要:改为你实际的路径)
# Windows phpstudy 默认路径:C:/phpstudy/WWW
# Linux 常见路径:/var/www/html
root "C:/phpstudy/WWW";
# 默认首页文件
index index.html index.htm index.php;
# ==============================================
# PHP 请求处理(连接蚁剑必需)
# ==============================================
# 正则匹配:~表示区分大小写的正则,\.php$匹配以.php结尾的URL
location ~ \.php$ {
# 允许所有IP访问PHP文件,这里可以覆盖父级的设置
allow all;
# PHP 监听地址(根据你的PHP版本调整)
# phpstudy 通常使用端口方式
# PHP处理器地址:将PHP请求转发到127.0.0.1:9000(PHP-FPM进程)
fastcgi_pass 127.0.0.1:9000;
# 或者使用 socket 方式(二选一,注释掉另一个)
# fastcgi_pass C:/phpstudy/php/php-cgi.sock;
# 指定PHP文件索引,默认PHP文件:访问目录时默认加载index.php
fastcgi_index index.php;
# 传递脚本文件名,脚本路径:告诉PHP-FPM要执行哪个文件的完整路径
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# 引入标准fastcgi参数
include fastcgi_params;
# 增加超时时间(避免大文件操作超时)
fastcgi_read_timeout 300;
fastcgi_send_timeout 300;
}
# ==============================================
# 静态文件直接处理
# ==============================================
location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
# 缓存时间:浏览器缓存这些文件30天,减少重复请求
expires 30d;
allow all;
}
# ==============================================
# 禁止访问 .htaccess 等隐藏文件
# ==============================================
location ~ /\. {
deny all;
}
# ==============================================
# 错误页面配置(可选)
# ==============================================
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root "C:/phpstudy/WWW";
}
}
# ==============================================
# 如果有多个站点,可以在这里继续添加 server 块
# ==============================================
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
#include vhosts.conf;
# 变量映射:根据一个变量创建新变量
# Nginx内置变量,格式如"2026-04-20T10:30:00+08:00"
map $time_iso8601 $logdate { # $logdate新变量,值为提取的日期,可用于动态日志文件名
# 提取日期部分"2026-04-20"到$ymd变量
'~^(?<ymd>\\d{4}-\\d{2}-\\d{2})' $ymd;
default 'date-not-found';
}
include vhosts/*.conf;
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# 上传文件大小限制:最大允许50MB的请求体(文件上传)
client_max_body_size 50m;
# 请求体缓冲区:存储请求体的内存大小,超过则写入磁盘
client_body_buffer_size 60k;
# 请求体读取超时:读取客户端请求体超时60秒
client_body_timeout 60;
# 请求头缓冲区:存储HTTP头的大小
client_header_buffer_size 64k;
# 请求头读取超时:读取客户端请求头超时60秒
client_header_timeout 60;
# 错误文件
error_page 400 /error/400.html;
error_page 403 /error/403.html;
error_page 404 /error/404.html;
error_page 500 /error/500.html;
error_page 501 /error/501.html;
error_page 502 /error/502.html;
error_page 503 /error/503.html;
error_page 504 /error/504.html;
error_page 505 /error/505.html;
error_page 506 /error/506.html;
error_page 507 /error/507.html;
error_page 509 /error/509.html;
error_page 510 /error/510.html;
# 单连接最大请求数:一个长连接最多处理100个请求后关闭
keepalive_requests 100;
# 大请求头缓冲区:4个64KB的缓冲区处理超大请求头
large_client_header_buffers 4 64k;
# 重置超时连接:超时后立即释放连接资源
reset_timedout_connection on;
# 发送超时:发送响应给客户端超时60秒
send_timeout 60;
# sendfile分块:每次sendfile传输最大512KB
sendfile_max_chunk 512k;
# 域名哈希桶大小:优化域名匹配性能
server_names_hash_bucket_size 256;
}
# 文件描述符限制:每个worker进程最多同时打开100000个文件
worker_rlimit_nofile 100000;