笔记说明:本文档旨在系统性地梳理Nginx的核心架构、I/O模型、安装配置方法,并提供从基础站点搭建到高级负载均衡、HTTPS配置及PHP整合的全流程实验,作为学习和配置Nginx的参考手册。
第一部分:核心概念与架构
1.1 Web服务基础与I/O模型
-
Apache三种工作模型对比
-
prefork:多进程单线程,稳定性高,但并发弱(使用select模型,最大连接数1024)。
-
worker:多进程多线程,内存占用少,并发中等。
-
event:事件驱动(基于epoll),高并发优秀,解决了keepalive长连接中线程的浪费问题。
-
-
I/O模型核心 :Nginx基于多路复用I/O(epoll),能够单线程监控海量连接,通过事件回调进行处理,效率极高。
特性 select poll epoll 操作方式 线性遍历 线性遍历 事件回调 效率 O(n) O(n) O(1) 最大连接数 1024/2048 无上限 无上限 -
零拷贝(Zero-Copy) :Nginx默认启用
SENDFILE。它使数据直接在内核缓冲区与socket缓冲区之间传输,全程不经过用户态,能大幅提升静态文件的传输性能。
1.2 Nginx架构
-
进程模型 :采用经典的 Master-Worker 多进程模型。
-
Master进程:负责读取配置、管理监控Worker进程。
-
Worker进程:数量通常建议等于CPU核心数,它们平等地竞争连接并处理请求。
-
-
模块体系:高度模块化,支持动态装载。核心模块包括:
-
标准HTTP模块
-
可选HTTP模块(如SSL、Stream四层代理)
-
第三方模块
-
第二部分:基础环境与安装
2.1 源码编译安装
源码编译可以灵活定制所需模块,是生产环境中常用的安装方式。
bash
# 1. 安装依赖
dnf install gcc openssl-devel pcre2-devel zlib-devel -y
# 2. 创建运行用户
useradd -s /sbin/nologin -M nginx
# 3. 配置编译参数(按需启用模块)
./configure --prefix=/usr/local/nginx \
--user=nginx --group=nginx \
--with-http_ssl_module --with-http_v2_module \
--with-http_realip_module --with-http_stub_status_module \
--with-http_gzip_static_module --with-pcre --with-stream \
--with-stream_ssl_module --with-stream_realip_module
# 4. 编译安装
make && make install
# 5. 配置环境变量(将Nginx的sbin目录加入PATH)
vim ~/.bash_profile
export PATH=$PATH:/usr/local/nginx/sbin
source ~/.bash_profile
-
--with-http_ssl_module:支持HTTPS。 -
--with-stream:启用四层负载均衡功能。
2.2 Systemd服务配置
为了方便管理,可以配置Systemd服务。
bash
vim /lib/systemd/system/nginx.service
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t # 启动前测试配置
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
systemctl daemon-reload && systemctl enable --now nginx
2.3 核心优化参数
在配置文件的全局块和events块中进行优化:
nginx
worker_processes auto; # 自动适配CPU核心数
worker_cpu_affinity auto; # 自动绑定CPU核心,提高缓存效率
events {
worker_connections 10000; # 单个worker进程的最大连接数
use epoll; # 强制使用epoll事件模型(Linux高性能)
accept_mutex on; # 连接互斥锁,避免惊群效应
multi_accept on; # worker一次可接受多个新连接
}
第三部分:基础功能实验
3.1 PC站点构建:root与alias区别
这两个指令都用于指定文件路径,但处理方式不同。
-
root:将完整的URI附加在root指定的路径之后。- 访问
/lee/实际查找/webdir/timinglee.org/lee/html/lee/。
- 访问
-
alias:用alias指定的路径替换掉location匹配的URI部分。-
访问
/passwd返回/etc/passwd文件。 -
注意 :
alias末尾的/需要与匹配的URI配合好。
-
3.2 Location匹配规则
匹配优先级非常重要,决定了请求由哪个location块处理。
nginx
# 优先级从高到低:
location = /null { ... } # 1. 精确匹配(=),完全匹配/nul
location ^~ /img/ { ... } # 2. 前缀匹配(^~),匹配后不再检查正则
location ~ \.php$ { ... } # 3. 正则匹配(~区分大小写),匹配.php结尾
location ~* \.(jpg|png)$ { ... } # 4. 正则匹配(~*不区分大小写)
location / { ... } # 5. 通用前缀匹配(最低优先级)
3.3 用户认证
bash
# 创建密码文件(需要安装httpd-tools)
htpasswd -cmb /usr/local/nginx/conf/.htpasswd admin lee
nginx
location /admin {
auth_basic "login passwd"; # 弹窗提示信息
auth_basic_user_file "/usr/local/nginx/conf/.htpasswd";
}
3.4 自定义错误页面
优雅地处理错误,提升用户体验。
nginx
error_page 404 405 503 502 /error; # 捕获错误码,重定向到内部location
location /error {
alias /usr/local/nginx/errorpage/errormessage; # 返回自定义提示文件
}
第四部分:进阶功能实验
4.1 下载服务器与限速
nginx
location /download {
root /usr/local/nginx;
autoindex on; # 开启目录列表
limit_rate 1024k; # 限制下载速度为1MB/s
autoindex_exact_size off; # 显示友好文件大小(KB/MB)
autoindex_localtime on; # 显示服务器本地时间
}
4.2 文件检测(try_files)
按顺序检查文件是否存在,常用作前端路由(如React/Vue应用)的 fallback。
nginx
root /usr/local/nginx/errorpage;
# 依次尝试访问请求的文件、加.html后缀、加/index.html、最后返回default.html
try_files $uri $uri.html $uri/index.html /default.html;
4.3 状态页(stub_status)
监控Nginx的运行状态,常与认证和访问控制结合使用。
nginx
location /nginx_status {
stub_status; # 启用状态页
auth_basic "login"; # 开启认证
auth_basic_user_file /usr/local/nginx/conf/.htpasswd;
allow 172.25.254.0/24; # 允许内网访问
deny all; # 拒绝其他所有
}
4.4 Gzip压缩
压缩静态文本文件,显著减少传输体积。
nginx
gzip on;
gzip_comp_level 4; # 压缩级别(1-9,越高越耗CPU)
gzip_min_length 1024k; # 大于1024k才压缩,小文件不压缩
gzip_types text/plain text/css application/javascript;
gzip_static on; # 优先使用预编译的.gz文件(需提前生成)
4.5 Nginx变量
Nginx拥有丰富的内置变量,也可自定义变量(需安装echo-nginx-module模块)。
nginx
location /vars {
echo $remote_addr; # 客户端IP
echo $request_method; # 请求方法
set $test "hello"; # 自定义变量
echo $test;
}
第五部分:高级功能实验
5.1 网页重写(rewrite)
rewrite是Nginx的核心功能之一,用于URL重定向和重写。
-
breakvslast:-
break:在当前location中停止后续的rewrite规则。 -
last:停止当前location,并重新用新的URI进行location匹配。
-
-
重定向:
nginx
rewrite / http://www.baidu.com redirect; # 302临时重定向 rewrite / http://www.baidu.com permanent; # 301永久重定向
5.2 全站HTTPS配置
启用HTTPS并强制跳转。
nginx
# 生成自签名证书
openssl req -newkey rsa:2048 -nodes -sha256 -keyout /usr/local/nginx/certs/key -x509 -days 365 -out /usr/local/nginx/certs/crt
server {
listen 80;
server_name lee.timinglee.org;
if ($scheme = http) { # 判断如果是HTTP
rewrite / https://$host permanent; # 永久重定向到HTTPS
}
}
server {
listen 443 ssl;
server_name lee.timinglee.org;
ssl_certificate /usr/local/nginx/certs/timinglee.org.crt;
ssl_certificate_key /usr/local/nginx/certs/timinglee.org.key;
}
5.3 防盗链
防止其他网站直接引用本站资源。
nginx
location /img {
# 定义合法的referer:空、无、本域名、*.baidu.com
valid_referers none blocked server_names *.baidu.com;
if ($invalid_referer) { # 如果referer不合法
rewrite ^/img/(.*)$ /img/daolian.jpg break; # 返回一张防盗链图片
}
}
5.4 反向代理与负载均衡
这是Nginx最强大的用途之一。
-
基础反向代理
nginx
location / { proxy_pass http://172.25.254.10:80; # 后端服务器地址 proxy_set_header X-Forwarded-For $remote_addr; # 传递客户端真实IP proxy_hide_header ETag; # 隐藏后端ETag proxy_pass_header Server; # 透传后端Server头 } -
负载均衡
nginx
upstream webserver { # server <地址> [参数] server 172.25.254.10:80 weight=1 max_fails=3 fail_timeout=15s; server 172.25.254.20:80 weight=2; # 权重越高,分配越多 server 172.25.254.100:8888 backup; # 标记为备用节点 } server { listen 80; location / { proxy_pass http://webserver; # 引用upstream组 } }-
负载均衡算法
-
weight:加权轮询(默认)。 -
ip_hash:根据客户端IP进行哈希,实现会话保持。 -
least_conn:转发给当前活动连接数最少的服务器。 -
hash $request_uri consistent:对URI进行一致性哈希,用于缓存服务器。
-
-
第六部分:PHP整合与扩展实验
6.1 Nginx整合PHP-FPM
Nginx本身不处理PHP,需要通过FastCGI协议将PHP请求转发给PHP-FPM解析。
nginx
server {
listen 80;
server_name php.timinglee.org;
root /webdir/timinglee.org/php/html; # 设置网站根目录
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000; # PHP-FPM监听地址
fastcgi_index index.php;
include fastcgi.conf; # 包含fastcgi环境变量
}
}
PHP-FPM的编译和配置请参考原文6.1节,核心是确保listen地址与Nginx中的fastcgi_pass一致。
总结
Nginx以其高性能 、高并发 和丰富的功能 (反向代理、负载均衡、HTTP缓存、Web服务器)成为现代Web架构的核心组件。理解其Master-Worker进程模型 、epoll I/O模型 以及请求处理的各阶段 (location匹配、rewrite、try_files)是灵活配置的基础。