一、Nginx 核心特点
- 事件驱动模型(epoll/kqueue):异步非阻塞 I/O,单进程可处理万级并发,内存占用极低。
- 轻量:CPU/内存消耗小,配置简洁。
- 多角色:Web 服务器、反向代理、负载均衡、HTTP 缓存、SSL 终端、限流/防盗链/gzip、虚拟主机等。
- 架构 :Master-Worker 多进程。
- Master(root 运行):读取配置、管理 worker、接收信号(启动/停止/reload)。
- Worker (业务处理):单线程异步非阻塞,
worker_processes auto自动等于 CPU 核心数,互相独立。
热重载流程:master 校验新配置 → 启动新 worker(加载新配置)→ 旧 worker 处理完现有连接后退出 → 服务不中断。
二、安装与基础部署
节点规划(示例)
| 节点 | IP | 角色 |
|---|---|---|
| nginx-server | 10.1.8.10/24 | Nginx 服务端 |
| nginx-client | 10.1.8.11/24 | 客户端测试 |
安装步骤(CentOS 7)
bash
bash
# 添加 EPEL 源
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
yum -y install nginx
systemctl enable nginx --now
# 准备测试页
echo "Hello World From Nginx" > /usr/share/nginx/html/index.html
# 防火墙放行 http
firewall-cmd --add-service=http --permanent && firewall-cmd --reload
测试
修改客户端 hosts,添加 10.1.8.10 www.laogao.cloud,然后 curl http://www.laogao.cloud 验证。
三、配置文件结构(层级嵌套)
text
全局块 → events块 → http块 → server块 → location块
- 全局块 :
user,worker_processes,error_log,pid,include等。 - events 块 :网络连接参数,如
worker_connections 1024; use epoll;。 - http 块 :HTTP 服务公共配置,可包含多个
server。 - server 块:虚拟主机配置(监听端口、域名、根目录等)。
- location 块:URI 路径匹配规则。
四、Location 匹配规则(优先级从高到低)
| 规则 | 示例 | 说明 |
|---|---|---|
= 精确匹配 |
location = /login |
最高优先级,完全一致 |
^~ 前缀匹配 |
location ^~ /static/ |
匹配开头,跳过正则 |
~ 大小写敏感正则 |
`location ~ .(jpg | png)$` |
~* 大小写不敏感正则 |
`location ~* .(jpg | png)$` |
| 普通前缀 | location /api/ |
最长前缀优先 |
/ 兜底 |
location / |
最低优先级 |
五、核心功能详解
1. 静态 Web 服务器
nginx
server {
listen 80;
server_name static.test.com;
root /data/static;
index index.html;
}
利用 sendfile 零拷贝,高性能。
2. 反向代理(Proxy)
- 正向代理:代理客户端(翻墙)。
- 反向代理:代理服务端,客户端无感知。
核心指令:proxy_pass http://后端地址;
常用代理头(传递客户端真实信息):
nginx
location /api/ {
proxy_pass http://127.0.0.1:8080;
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_pass 末尾带 / 与不带 / 的区别:
- 带
/:剔除匹配路径前缀,拼接剩余部分。
例:location /api/ { proxy_pass http://backend/; }→ 请求/api/user→ 后端接收/user。 - 不带
/:保留匹配路径前缀,直接拼接。
例:location /api/ { proxy_pass http://backend; }→ 请求/api/user→ 后端接收/api/user。
3. 负载均衡(upstream)
定义后端服务器组,结合 proxy_pass 使用。
nginx
upstream backend_pool {
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 backup; # 备份
server 192.168.1.13:8080 down; # 下线
}
常见调度算法:
| 算法 | 配置 | 说明 |
|---|---|---|
| 轮询(默认) | 无 | 依次分发 |
| 权重(weight) | weight=N |
按比例分配,性能高者多承担 |
| IP 哈希(ip_hash) | ip_hash; |
同一客户端 IP 固定到同一后端(解决 session) |
| 通用哈希(hash) | hash $变量; |
自定义键(如 cookie/url)做哈希,consistent 可减少抖动 |
| 最少连接(least_conn) | least_conn; |
分给活跃连接数最少的后端,支持 weight |
| 最少时间(least_time) | least_time header; |
商业版,根据响应时间调度 |
4. HTTPS/SSL 终端
nginx
server {
listen 443 ssl http2;
server_name www.test.com;
ssl_certificate /etc/nginx/cert/fullchain.pem;
ssl_certificate_key /etc/nginx/cert/privkey.key;
ssl_protocols TLSv1.2 TLSv1.3;
# ... root, location 等
}
# HTTP 强制跳转 HTTPS
server {
listen 80;
server_name www.test.com;
return 301 https://$host$request_uri;
}
生成自签名证书:
bash
bash
openssl genrsa -out www.key 2048
openssl req -new -key www.key -out www.csr -subj "/C=CN/ST=JS/L=NJ/O=LG/OU=DEV/CN=www.laogao.cloud"
openssl x509 -req -days 3650 -in www.csr -signkey www.key -out www.crt
5. 其他实用功能
-
gzip 压缩:减少传输带宽。
nginx
gzip on; gzip_types text/plain text/css application/json application/javascript; -
访问控制(IP 黑白名单):
nginx
location /admin { allow 192.168.1.0/24; deny all; } -
限流 (
limit_req)、防盗链 (valid_referers)、缓存 (proxy_cache)、重写 (rewrite)。
六、虚拟主机配置
同一服务器提供多个站点,支持:
- 基于域名(server_name)
- 基于端口(listen)
- 基于 IP(不常用)
示例(基于域名):
nginx
server {
server_name web1.laogao.cloud;
root /usr/share/nginx/web1;
}
server {
server_name web2.laogao.cloud;
root /usr/share/nginx/web2;
}
测试时修改客户端 hosts 解析域名。
七、基本认证(HTTP Basic Auth)
nginx
location /auth-basic/ {
auth_basic "Basic Auth";
auth_basic_user_file /etc/nginx/.htpasswd;
}
创建用户:
bash
bash
htpasswd -bc /etc/nginx/.htpasswd laogao 123456
八、PHP 站点配置(PHP-FPM)
安装 php php-fpm 并启动。
nginx
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
九、反向代理综合示例
nginx
upstream backend_main { server 192.168.1.200:8080; }
upstream backend_api { server 192.168.1.201:9090; }
upstream backend_static { server 192.168.1.202:80; }
server {
listen 80;
server_name localhost;
location = /login {
proxy_pass http://backend_login;
proxy_set_header Host $host;
}
location ^~ /static/ {
proxy_pass http://backend_static/;
}
location ~* \.(jpg|png|gif)$ {
proxy_pass http://backend_static;
}
location /api/ {
proxy_pass http://backend_api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location / {
proxy_pass http://backend_main;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
匹配流程示例:
| 请求 URL | 命中 location | 转发后端 URL |
|---|---|---|
/login |
= 精确 |
http://backend_login/login |
/static/css/main.css |
^~ /static/ |
http://backend_static/css/main.css |
/api/user/info |
/api/ |
http://backend_api/user/info |
/index.html |
/ 兜底 |
http://backend_main/index.html |
十、常用命令与日志
命令
bash
bash
nginx # 启动
nginx -s stop # 快速停止
nginx -s quit # 优雅停止
nginx -s reload # 重载配置(热更新)
nginx -t # 检查配置文件语法
日志
- access.log :记录每次请求,格式可自定义(
log_format)。 - error.log:记录错误,排查 502/504/403 等。
常见错误:
- 502 Bad Gateway:后端服务不可达(端口/防火墙/服务宕机)。
- 504 Gateway Timeout:后端响应超时。
- 499:客户端主动断开。
- 403:权限/目录/索引文件问题。
十一、生产调优小贴士
worker_processes auto;自动匹配 CPU 核心数。worker_connections适当调大(系统ulimit -n也要调高)。- 开启
sendfile on; tcp_nopush on; tcp_nodelay on;优化网络传输。 - 使用
keepalive_timeout控制长连接超时。 - 合理利用
location匹配顺序,避免冗余规则。