Nginx的源码编译
一、下载软件包
# 切换到/opt目录(推荐的软件安装目录)
[root@Nginx ~]# cd /opt
# 下载Nginx 1.28.1源码包(官方源)
[root@Nginx opt]# wget https://nginx.org/download/nginx-1.28.1.tar.gz
# 若wget失败,可先安装wget:dnf install wget -y
二、解压并进入源码目录
# 解压tar.gz包
[root@Nginx opt]# tar zxf nginx-1.28.1.tar.gz
# 进入解压后的源码目录
[root@Nginx opt]# cd nginx-1.28.1/
# 验证目录文件(确保configure脚本存在)
[root@Nginx nginx-1.28.1]# ls
auto CHANGES.ru conf contrib html man SECURITY.md
CHANGES CODE_OF_CONDUCT.md configure CONTRIBUTING.md LICENSE README.md src
三、安装依赖并检测编译环境
# 安装编译依赖(gcc编译器、SSL、PCRE、zlib等)
[root@Nginx nginx-1.28.1]# dnf install gcc openssl-devel.x86_64 pcre2-devel.x86_64 zlib-devel -y
# 执行configure配置(指定安装路径+功能模块)
[root@Nginx nginx-1.28.1]# ./configure \
--prefix=/usr/local/nginx \ # 核心:指定安装根目录
--user=nginx \ # 运行用户
--group=nginx \ # 运行用户组
--with-http_ssl_module \ # 启用HTTPS模块
--with-http_v2_module \ # 启用HTTP/2模块
--with-http_realip_module \ # 启用真实IP模块
--with-http_stub_status_module \ # 启用状态监控模块
--with-http_gzip_static_module \ # 启用gzip静态压缩模块
--with-pcre \ # 启用PCRE正则支持
--with-stream \ # 启用TCP/UDP转发
--with-stream_ssl_module \ # 启用流协议SSL
--with-stream_realip_module # 启用流协议真实IP
# 若configure报错:
# 1. 检查依赖是否安装完整
# 2. 确保系统架构与依赖包匹配(x86_64/arm64)
四、编译并安装
# 编译(-j指定CPU核心数,加速编译,例如-j4)
[root@Nginx nginx-1.28.1]# make -j$(nproc)
# 安装(将编译后的文件复制到--prefix指定目录)
[root@Nginx nginx-1.28.1]# make install
# 验证安装:检查sbin目录是否存在nginx二进制文件
[root@Nginx nginx-1.28.1]# ls /usr/local/nginx/sbin/nginx
/usr/local/nginx/sbin/nginx
五、初始化运行环境并启动
# 1. 创建nginx系统用户(无登录权限)
[root@Nginx ~]# useradd -s /sbin/nologin -M nginx
# 2. 配置环境变量(永久生效)
[root@Nginx ~]# echo "export PATH=\$PATH:/usr/local/nginx/sbin" >> ~/.bash_profile
# 加载环境变量
[root@Nginx ~]# source ~/.bash_profile
# 3. 启动Nginx
[root@Nginx ~]# nginx
# 验证启动状态
[root@Nginx ~]# ps aux | grep nginx
root XXXXX 0.0 0.1 14688 2356 ? Ss XX:XX 0:00 nginx: master process nginx
nginx XXXXX 0.0 0.2 14888 3892 ? S XX:XX 0:00 nginx: worker process
# 4. 测试访问(修改默认页面并验证)
[root@Nginx ~]# echo "Hello Nginx" > /usr/local/nginx/html/index.html
[root@Nginx ~]# curl $(hostname -I | awk '{print $1}')
Hello Nginx
# 若curl失败:
# 1. 检查防火墙:systemctl stop firewalld(临时关闭)
# 2. 检查SELinux:setenforce 0(临时关闭)
六、配置 systemd 服务(实现开机自启)
# 1. 创建服务文件
[root@Nginx ~]# 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 # 后台运行模式
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
# 2. 重新加载systemd配置
[root@Nginx ~]# systemctl daemon-reload
# 3. 设置开机自启并立即启动
[root@Nginx ~]# systemctl enable --now nginx
# 4. 验证服务状态
[root@Nginx ~]# systemctl status nginx
● nginx.service - The NGINX HTTP and reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: disabled)
Active: active (running) since XXXX-XX-XX XX:XX:XX CST; XXmin ago
# 5. 重启系统验证开机自启(可选)
[root@Nginx ~]# reboot
# 重启后检查状态
[root@Nginx ~]# systemctl status nginx
常用运维命令(扩展)
# 停止Nginx
nginx -s stop
# 平滑重启(不中断业务)
nginx -s reload
# 检查配置文件语法
nginx -t
# 查看Nginx版本
nginx -v
注意事项
- 依赖安装失败:若
dnf源失效,可替换为阿里云 / 清华镜像源; - 编译报错:确保系统已安装
make、gcc-c++(dnf install make gcc-c++ -y); - 端口占用:默认 80 端口被占用时,修改
/usr/local/nginx/conf/nginx.conf的listen端口后重启。
Nginx的平滑升级及回滚
一、下载目标版本 Nginx 源码包
# 替换为目标版本号(如1.29.4)
NGINX_VERSION="1.29.4"
wget https://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz -P /root/
二、编译新版本(隐藏版本号)+ 平滑升级
1. 解压并修改版本标识
tar zxf /root/nginx-${NGINX_VERSION}.tar.gz -C /root/
cd /root/nginx-${NGINX_VERSION}/src/core/
# 编辑nginx.h,隐藏版本信息
vim nginx.h
# 替换以下内容(可自定义标识)
#define nginx_version 1029004 # 对应版本数字(1.29.4=1029004)
#define NGINX_VERSION ""
#define NGINX_VER "CUSTOM/" NGINX_VERSION
2. 编译(复用原有编译参数)
cd /root/nginx-${NGINX_VERSION}/
# 先查看当前Nginx编译参数(关键!必须复用)
/usr/local/nginx/sbin/nginx -V
# 复制configure arguments: 后的内容,替换下方<原有编译参数>
./configure <原有编译参数> # 示例:--prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module ...
make # 仅编译,不执行make install(避免覆盖配置)
3. 替换二进制文件 + 平滑启动新版本
# 备份旧版二进制文件
cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old -p
# 替换新版本二进制(\cp 强制覆盖)
\cp -f /root/nginx-${NGINX_VERSION}/objs/nginx /usr/local/nginx/sbin/nginx
# 查看当前master进程ID
NGINX_MASTER_PID=$(ps aux | grep "nginx: master process" | grep -v grep | awk '{print $2}' | head -n1)
# 发送USR2信号,启动新版本master进程
kill -USR2 ${NGINX_MASTER_PID}
# 验证新版本启动(logs目录生成nginx.pid.oldbin)
ls /usr/local/nginx/logs/ | grep oldbin
# 验证版本
/usr/local/nginx/sbin/nginx -V
4. 回收旧版本 worker 进程
# 向旧master进程发送WINCH信号,关闭旧worker进程
kill -WINCH ${NGINX_MASTER_PID}
# 验证旧worker进程已退出
ps aux | grep nginx
三、版本回滚(回退到旧版本)
cd /usr/local/nginx/sbin/
# 备份新版本二进制
cp nginx nginx.new -p
# 恢复旧版本二进制
\cp -f nginx.old nginx -pf
# 向旧master进程发送HUP信号,重新加载旧版本配置/二进制
OLD_MASTER_PID=$(cat /usr/local/nginx/logs/nginx.pid.oldbin)
kill -HUP ${OLD_MASTER_PID}
# 回收新版本worker进程
NEW_MASTER_PID=$(cat /usr/local/nginx/logs/nginx.pid)
kill -WINCH ${NEW_MASTER_PID}
# 验证回滚结果
/usr/local/nginx/sbin/nginx -V
关键注意事项
- 编译参数必须复用 :升级前务必用
nginx -V查看原有编译参数,否则新版本可能缺失模块导致启动失败; - 仅编译不安装 :全程用
make而非make install,避免覆盖现有配置文件; - 信号说明 :
USR2:启动新版本 master 进程(新旧进程共存);WINCH:关闭指定 master 进程的 worker 子进程;HUP:重载配置 / 重启 worker 进程(回滚核心);
- 回滚前提 :必须提前备份旧版二进制文件(
nginx.old),否则无法回滚; - 验证环节 :每一步操作后通过
ps aux | grep nginx、nginx -V确认状态,避免操作失效。
Nginx配置文件的管理及优化参数
一、Nginx 核心进程优化
1. 编辑 Nginx 主配置文件
vim /usr/local/nginx/conf/nginx.conf
2. 设置 worker_processes(工作进程数)
-
手动指定进程数(例如 2 核 CPU 设为 2): nginx
worker_processes 2; # 数值建议等于 CPU 核心数 -
自动匹配 CPU 核心数(推荐): nginx
worker_processes auto; # 绑定 CPU 亲和性(4 核示例,0001=核0,0010=核1,0100=核2,1000=核3) worker_cpu_affinity 0001 0010 0100 1000;
3. 重载配置并验证进程
# 重载 Nginx 配置
nginx -s reload
# 查看 Nginx 进程
ps aux | grep nginx
# 查看进程绑定的 CPU 核心(psr 列是核心编号)
ps axo pid,cmd,psr | grep nginx
二、事件模块(events)优化
1. 编辑配置文件,修改 events 块
vim /usr/local/nginx/conf/nginx.conf
添加 / 修改如下配置:
events {
worker_connections 10000; # 单个工作进程最大连接数
use epoll; # 启用 epoll 模型(Linux 下高性能 I/O 模型)
accept_mutex on; # 防止惊群效应
multi_accept on; # 单个进程同时接受多个连接
}
2. 重载配置
nginx -s reload
三、系统级文件句柄限制(解决 "Too many open files")
1. 修改系统限制配置
vim /etc/security/limits.conf
添加如下内容(全局 /root 用户的文件句柄限制):
* - nofile 100000 # 所有用户最大打开文件数
* - noproc 100000 # 所有用户最大进程数
root - nofile 100000 # root 用户单独配置(可选)
2. 验证限制是否生效
# 查看 nginx 用户的文件句柄限制
sudo -u nginx ulimit -n
# 临时修改当前会话的限制(可选,永久生效需重启)
ulimit -n 100000
四、并发测试(ApacheBench)
1. 安装 ab 工具
dnf install httpd-tools -y # CentOS/RHEL 8+
# 或 yum install httpd-tools -y # CentOS/RHEL 7
2. 执行并发测试
# -n:总请求数;-c:并发数;替换为你的 Nginx 服务器 IP
ab -n 100000 -c 10000 http://172.25.254.100/index.html
关键注意事项
worker_processes建议设为 CPU 核心数(或 auto),过多会导致进程竞争资源;worker_connections需结合系统句柄限制,公式:总连接数 = worker_processes * worker_connections;epoll仅适用于 Linux 系统,BSD 系统用kqueue;- 测试并发时,服务器硬件(CPU / 内存 / 网卡)需匹配,避免因硬件瓶颈导致测试失败;
- 修改
limits.conf后,重启系统 或重新登录会话才能完全生效; - 若仍报 "Too many open files",需检查 Nginx 主进程的启动用户(需匹配 limits.conf 的限制)。
Nginx下构建PC站点
一、完整复刻 location 中 root 的配置操作
1. 环境准备(Nginx 配置目录调整)
# 进入Nginx主配置目录
[root@Nginx ~]# cd /usr/local/nginx/conf/
# 创建conf.d目录用于存放虚拟主机配置
[root@Nginx conf]# mkdir conf.d
# 编辑主配置文件,引入conf.d下的所有.conf文件
[root@Nginx conf]# vim nginx.conf
# 在http块中添加/确认以下行(通常行号82左右)
include "/usr/local/nginx/conf/conf.d/*.conf";
# 重新加载Nginx配置(不重启服务)
[root@Nginx conf]# nginx -s reload
# 进入conf.d目录准备编写虚拟主机配置
[root@Nginx conf]# cd conf.d/
2. 站点目录与测试文件创建
# 创建站点根目录(层级与示例一致)
[root@Nginx conf.d]# mkdir -p /webdata/nginx/timinglee.org/lee/html
# 创建首页测试文件,写入标识内容
[root@Nginx conf.d]# echo lee.timinglee.org > /webdata/nginx/timinglee.org/lee/html/index.html
3. 编写虚拟主机配置(root 基础配置)
[root@Nginx conf.d]# vim vhosts.conf
# 写入以下server块配置
server {
listen 80;
server_name lee.timinglee.org;
location / {
root /webdata/nginx/timinglee.org/lee/html;
# 可选:添加index指令确保默认访问index.html
index index.html;
}
}
# 重启Nginx使配置生效
[root@Nginx conf.d]# systemctl restart nginx.service
4. 配置 hosts 解析(本地测试)
[root@Nginx conf.d]# vim /etc/hosts
# 添加以下行(172.25.254.100为Nginx服务器IP,需替换为实际IP)
172.25.254.100 Nginx www.timinglee.org lee.timinglee.org
# 测试访问(验证root基础配置)
[root@Nginx conf.d]# curl lee.timinglee.org
# 预期输出:lee.timinglee.org
5. 扩展:location 匹配子目录(/lee)
# 编辑虚拟主机配置,新增/lee的location
[root@Nginx conf.d]# vim vhosts.conf
server {
listen 80;
server_name lee.timinglee.org;
location / {
root /webdata/nginx/timinglee.org/lee/html;
index index.html;
}
location /lee {
root /webdata/nginx/timinglee.org/lee/html;
index index.html;
}
}
# 重启Nginx
[root@Nginx conf.d]# systemctl restart nginx.service
# 创建/lee子目录及测试文件
[root@Nginx conf.d]# mkdir -p /webdata/nginx/timinglee.org/lee/html/lee
[root@Nginx conf.d]# echo lee > /webdata/nginx/timinglee.org/lee/html/lee/index.html
# 测试访问子目录
[root@Nginx conf.d]# curl lee.timinglee.org/lee/
# 预期输出:lee
二、完整复刻 location 中 alias 的配置操作
1. 编辑虚拟主机配置(替换 / 新增 alias 规则)
[root@Nginx conf.d]# vim vhosts.conf
# 覆盖为以下配置(仅保留lee.timinglee.org的alias规则)
server {
listen 80;
server_name lee.timinglee.org;
# alias匹配文件(访问/passwd直接返回/etc/passwd内容)
location /passwd {
alias /etc/passwd;
}
# alias匹配目录(访问/passwd/返回/mnt目录下的index.html)
location /passwd/ {
alias /mnt/;
index index.html;
}
}
# 重新加载Nginx配置
[root@Nginx conf.d]# nginx -s reload
2. 创建 alias 目录测试文件
# 创建/mnt目录(若不存在)并写入测试内容
[root@Nginx conf.d]# mkdir -p /mnt
[root@Nginx conf.d]# echo passwd > /mnt/index.html
3. 测试 alias 配置
# 测试目录访问(/passwd/)
[root@Nginx conf.d]# curl lee.timinglee.org/passwd/
# 预期输出:passwd
# 测试文件访问(/passwd)
[root@Nginx conf.d]# curl lee.timinglee.org/passwd
# 预期输出:/etc/passwd文件的内容(如root:x:0:0:root:/root:/bin/bash等)
关键说明
root与alias核心区别:root:最终访问路径 = root 值 + location 匹配的路径(如root /a/b+location /c→ 实际路径/a/b/c);alias:最终访问路径 = alias 值(直接替换 location 匹配的路径,如location /c+alias /d→ 实际路径/d)。
Location 字符匹配详解
一、环境准备
- 确保 Nginx 已安装并启动(示例版本
1.28.1,其他版本逻辑一致); - 进入 Nginx 虚拟主机配置目录(示例路径:
/etc/nginx/conf.d/); - 创建 / 编辑测试配置文件
vhosts.conf。
二、逐类验证 Location 匹配规则
1. 无符号:前缀匹配(区分大小写,非精确)
配置内容:
vim /etc/nginx/conf.d/vhosts.conf
server {
listen 80;
server_name lee.timinglee.org; # 替换为你的测试域名/本机IP
location /null {
return 200 "/null-1";
}
}
重载配置 + 测试:
nginx -s reload
# 测试1:精准前缀匹配 → 返回 /null-1
curl lee.timinglee.org/null/
# 测试2:大小写不一致 → 404
curl lee.timinglee.org/NULL/
# 测试3:前缀不匹配(/test/null 不是以 /null 开头)→ 404
curl lee.timinglee.org/test/null
结论:无符号是「前缀匹配」,严格区分大小写,仅匹配「以指定路径开头」的请求。
2. =:精确匹配(优先级最高)
配置内容(追加到 server 块):
location /null {
return 200 "null-1";
}
location = /null { # 精确匹配 /null 路径
return 200 "null-2";
}
location ~ /null { # 正则匹配(后续验证)
return 200 "null-3";
}
重载配置 + 测试:
nginx -s reload
# 精确匹配生效,优先级高于前缀/正则 → 返回 null-2
curl lee.timinglee.org/null
结论 := 是「精确匹配」,匹配成功后立即终止后续匹配,优先级最高。
3. ^~:前缀匹配(优先级高于正则)
配置内容(追加):
location ^~ /lee {
return 200 "lee";
}
重载配置 + 测试:
nginx -s reload
# 测试1:前缀匹配 /lee → 返回 lee
curl lee.timinglee.org/lee
# 测试2:非 /lee 开头 → 404
curl lee.timinglee.org/test/lee
# 测试3:/lee 开头(后续拼接任意字符)→ 返回 lee
curl lee.timinglee.org/lee/test
# 测试4:非 /lee 开头(aleea)→ 404
curl lee.timinglee.org/aleea/test
# 测试5:/lee 开头(leeab)→ 返回 lee
curl lee.timinglee.org/leeab/test
结论 :^~ 是「前缀匹配」,匹配成功后跳过正则匹配,优先级高于 ~/~*,但低于 =。
4. ~:正则匹配(区分大小写)
配置内容(追加):
location ~ /timing/ {
return 200 "timing";
}
重载配置 + 测试:
nginx -s reload
# 测试1:包含 /timing/ → 返回 timing
curl lee.timinglee.org/timinga/
# 测试2:精准 /timing/ → 返回 timing
curl lee.timinglee.org/timing/
# 测试3:路径中包含 /timing/ → 返回 timing
curl lee.timinglee.org/a/timing/
# 测试4:路径中包含 /timing/ → 返回 timing
curl lee.timinglee.org/a/timinga/
# 测试5:无 /timing/(atiming)→ 404
curl lee.timinglee.org/a/atiming/
# 测试6:大小写不一致(Timinga)→ 404
curl lee.timinglee.org/aTiminga/a/
结论 :~ 是「区分大小写的正则匹配」,匹配路径中包含 正则表达式的请求,优先级低于 =/^~,高于无符号前缀。
5. ~*:正则匹配(不区分大小写)
配置内容(追加):
location ~* /timinglee {
return 200 "timinglee";
}
重载配置 + 测试:
nginx -s reload
# 测试1:大小写混合 → 返回 timinglee
curl lee.timinglee.org/Timinglee/
# 测试2:全小写 → 返回 timinglee
curl lee.timinglee.org/timinglee/
# 测试3:/timinglee 开头 → 返回 timinglee
curl lee.timinglee.org/timinglee/a
# 测试4:路径中包含 /timinglee → 返回 timinglee
curl lee.timinglee.org/a/timinglee/a
# 测试5:无 /timinglee(atiminglee)→ 404
curl lee.timinglee.org/a/atiminglee/a
# 测试6:包含 timinglee(拼接字符)→ 返回 timinglee
curl lee.timinglee.org/a/timingleea/a
# 测试7:大小写混合 → 返回 timinglee
curl lee.timinglee.org/a/Timinglee/a
结论 :~* 是「不区分大小写的正则匹配」,逻辑同 ~,仅取消大小写限制。
6. 正则符号(\/./| 等):匹配文件后缀
配置内容(追加):
location ~* \.(img|php|jsp)$ {
return 200 "app";
}
重载配置 + 测试:
nginx -s reload
# 测试1:.php 后缀 → 返回 app
curl lee.timinglee.org/test.php
# 测试2:.jsp 后缀 → 返回 app
curl lee.timinglee.org/test.jsp
结论 :正则可匹配「文件后缀」,\ 转义特殊字符(. 匹配任意字符,需转义为 \.),| 表示或,$ 表示行尾(匹配后缀)。
三、核心总结(匹配优先级从高到低)
| 符号 | 匹配类型 | 大小写 | 核心特点 |
|---|---|---|---|
= |
精确匹配 | 敏感 | 匹配后立即终止,优先级最高 |
^~ |
前缀匹配 | 敏感 | 跳过正则匹配,优先级高于正则 |
~ |
正则匹配 | 敏感 | 按正则规则匹配,优先级高于无符号 |
~* |
正则匹配 | 不敏感 | 同 ~,仅取消大小写限制 |
| 无符号 | 前缀匹配 | 敏感 | 优先级最低,默认匹配方式 |
四、注意事项
- 测试前务必执行
nginx -s reload重载配置; - 若本机测试无域名,可将
lee.timinglee.org替换为127.0.0.1,或修改/etc/hosts绑定域名; - 正则匹配中,
\需转义(示例中\.(img|php|jsp)$表示匹配以.img/.php/.jsp结尾的请求); - 匹配规则为「一旦匹配到高优先级规则,立即终止后续匹配
服务访问的用户认证
二、逐类验证 Location 匹配规则
1. 无符号:前缀匹配(区分大小写,非精确)
配置内容:
bash
运行
vim /etc/nginx/conf.d/vhosts.conf
nginx
server {
listen 80;
server_name lee.timinglee.org; # 替换为你的测试域名/本机IP
location /null {
return 200 "/null-1";
}
}
重载配置 + 测试:
bash
运行
nginx -s reload
# 测试1:精准前缀匹配 → 返回 /null-1
curl lee.timinglee.org/null/
# 测试2:大小写不一致 → 404
curl lee.timinglee.org/NULL/
# 测试3:前缀不匹配(/test/null 不是以 /null 开头)→ 404
curl lee.timinglee.org/test/null
结论:无符号是「前缀匹配」,严格区分大小写,仅匹配「以指定路径开头」的请求。
2. =:精确匹配(优先级最高)
配置内容(追加到 server 块):
nginx
location /null {
return 200 "null-1";
}
location = /null { # 精确匹配 /null 路径
return 200 "null-2";
}
location ~ /null { # 正则匹配(后续验证)
return 200 "null-3";
}
重载配置 + 测试:
bash
运行
nginx -s reload
# 精确匹配生效,优先级高于前缀/正则 → 返回 null-2
curl lee.timinglee.org/null
结论 := 是「精确匹配」,匹配成功后立即终止后续匹配,优先级最高。
3. ^~:前缀匹配(优先级高于正则)
配置内容(追加):
nginx
location ^~ /lee {
return 200 "lee";
}
重载配置 + 测试:
bash
运行
nginx -s reload
# 测试1:前缀匹配 /lee → 返回 lee
curl lee.timinglee.org/lee
# 测试2:非 /lee 开头 → 404
curl lee.timinglee.org/test/lee
# 测试3:/lee 开头(后续拼接任意字符)→ 返回 lee
curl lee.timinglee.org/lee/test
# 测试4:非 /lee 开头(aleea)→ 404
curl lee.timinglee.org/aleea/test
# 测试5:/lee 开头(leeab)→ 返回 lee
curl lee.timinglee.org/leeab/test
结论 :^~ 是「前缀匹配」,匹配成功后跳过正则匹配,优先级高于 ~/~*,但低于 =。
4. ~:正则匹配(区分大小写)
配置内容(追加):
nginx
location ~ /timing/ {
return 200 "timing";
}
重载配置 + 测试:
bash
运行
nginx -s reload
# 测试1:包含 /timing/ → 返回 timing
curl lee.timinglee.org/timinga/
# 测试2:精准 /timing/ → 返回 timing
curl lee.timinglee.org/timing/
# 测试3:路径中包含 /timing/ → 返回 timing
curl lee.timinglee.org/a/timing/
# 测试4:路径中包含 /timing/ → 返回 timing
curl lee.timinglee.org/a/timinga/
# 测试5:无 /timing/(atiming)→ 404
curl lee.timinglee.org/a/atiming/
# 测试6:大小写不一致(Timinga)→ 404
curl lee.timinglee.org/aTiminga/a/
结论 :~ 是「区分大小写的正则匹配」,匹配路径中包含 正则表达式的请求,优先级低于 =/^~,高于无符号前缀。
5. ~*:正则匹配(不区分大小写)
配置内容(追加):
nginx
location ~* /timinglee {
return 200 "timinglee";
}
重载配置 + 测试:
bash
运行
nginx -s reload
# 测试1:大小写混合 → 返回 timinglee
curl lee.timinglee.org/Timinglee/
# 测试2:全小写 → 返回 timinglee
curl lee.timinglee.org/timinglee/
# 测试3:/timinglee 开头 → 返回 timinglee
curl lee.timinglee.org/timinglee/a
# 测试4:路径中包含 /timinglee → 返回 timinglee
curl lee.timinglee.org/a/timinglee/a
# 测试5:无 /timinglee(atiminglee)→ 404
curl lee.timinglee.org/a/atiminglee/a
# 测试6:包含 timinglee(拼接字符)→ 返回 timinglee
curl lee.timinglee.org/a/timingleea/a
# 测试7:大小写混合 → 返回 timinglee
curl lee.timinglee.org/a/Timinglee/a
结论 :~* 是「不区分大小写的正则匹配」,逻辑同 ~,仅取消大小写限制。
6. 正则符号(\/./| 等):匹配文件后缀
配置内容(追加):
nginx
location ~* \.(img|php|jsp)$ {
return 200 "app";
}
重载配置 + 测试:
bash
运行
nginx -s reload
# 测试1:.php 后缀 → 返回 app
curl lee.timinglee.org/test.php
# 测试2:.jsp 后缀 → 返回 app
curl lee.timinglee.org/test.jsp
结论 :正则可匹配「文件后缀」,\ 转义特殊字符(. 匹配任意字符,需转义为 \.),| 表示或,$ 表示行尾(匹配后缀)。
三、核心总结(匹配优先级从高到低)
| 符号 | 匹配类型 | 大小写 | 核心特点 |
|---|---|---|---|
= |
精确匹配 | 敏感 | 匹配后立即终止,优先级最高 |
^~ |
前缀匹配 | 敏感 | 跳过正则匹配,优先级高于正则 |
~ |
正则匹配 | 敏感 | 按正则规则匹配,优先级高于无符号 |
~* |
正则匹配 | 不敏感 | 同 ~,仅取消大小写限制 |
| 无符号 | 前缀匹配 | 敏感 | 优先级最低,默认匹配方式 |
四、注意事项
- 测试前务必执行
nginx -s reload重载配置; - 若本机测试无域名,可将
lee.timinglee.org替换为127.0.0.1,或修改/etc/hosts绑定域名; - 正则匹配中,
\需转义(示例中\.(img|php|jsp)$表示匹配以.img/.php/.jsp结尾的请求); - 匹配规则为「一旦匹配到高优先级规则,立即终止后续匹配」。
Markdown
用户认证
一、环境说明
操作基于 Linux 系统(CentOS/Debian 均可),已安装 Nginx 且能正常运行,htpasswd 工具已安装(若未安装,可通过 yum install httpd-tools 或 apt install apache2-utils 安装)。
二、操作步骤
1. 创建密码文件并添加用户
执行 htpasswd 命令创建加密的密码文件,添加用户(示例中用户名为 admin,密码为 lee):
# -c:创建新文件;-m:使用MD5加密;-b:直接传入密码(非交互模式)
[root@Nginx ~]# htpasswd -cmb /usr/local/nginx/conf/.htpasswd admin lee
Adding password for user admin
-
若需添加第二个用户,去掉
-c(避免覆盖已有文件):[root@Nginx ~]# htpasswd -mb /usr/local/nginx/conf/.htpasswd test 123456
2. 配置 Nginx 虚拟主机,开启认证
编辑 Nginx 虚拟主机配置文件:
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
写入以下配置(核心是 auth_basic 和 auth_basic_user_file 指令):
server {
listen 80;
# 替换为你的域名/IP
server_name lee.timinglee.org;
# 对 /admin 路径做认证
location /admin {
# 网页文件根目录(确保该目录下有文件,比如新建一个测试文件)
root /usr/local/nginx/html;
# 认证提示语(浏览器弹窗显示)
auth_basic "login passwd";
# 指定密码文件路径
auth_basic_user_file "/usr/local/nginx/conf/.htpasswd";
}
}
3. 准备测试文件(可选)
确保 /usr/local/nginx/html/admin 目录存在且有测试文件,否则访问会报 403/404:
[root@Nginx ~]# mkdir -p /usr/local/nginx/html/admin
[root@Nginx ~]# echo "admin" > /usr/local/nginx/html/admin/index.html
4. 重启 Nginx 生效配置
运行
[root@Nginx ~]# systemctl restart nginx.service
# 检查 Nginx 配置是否合法(重启前建议执行)
[root@Nginx ~]# nginx -t
三、测试认证效果
1. 未传账号密码(返回 401)
[root@Nginx ~]# curl lee.timinglee.org/admin/
<html>
<head><title>401 Authorization Required</title></head>
<body>
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx/1.28.1</center>
</body>
</html>
2. 传入正确账号密码(正常访问)
[root@Nginx ~]# curl -uadmin:lee http://lee.timinglee.org/admin/
admin
四、常见问题排查
- 401 一直出现但账号密码正确 :
- 检查密码文件路径是否配置正确(绝对路径);
- 检查 Nginx 进程是否有权限读取
.htpasswd文件(权限建议644,属主root)。
- 重启 Nginx 失败 :
- 执行
nginx -t检查配置语法错误; - 检查端口 80 是否被占用。
- 执行
自定义错误页面
第一步:创建错误页面存放目录及内容
# 1. 创建存放自定义错误页面的目录
[root@Nginx ~]# mkdir -p /usr/local/nginx/errorpage
# 2. 写入自定义错误提示内容(可自定义文案)
[root@Nginx ~]# echo "抱歉,你访问的页面暂时无法访问,请稍后重试!" > /usr/local/nginx/errorpage/err_info
# 3. 验证文件内容是否写入成功
[root@Nginx ~]# cat /usr/local/nginx/errorpage/err_info
抱歉,你访问的页面暂时无法访问,请稍后重试!
第二步:配置 Nginx 虚拟主机(关联错误页面)
# 编辑Nginx虚拟主机配置文件
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
在配置文件中写入 / 修改如下内容(核心是error_page和location /error段):
server {
listen 80;
# 替换为你的域名/IP
server_name test.example.com;
# 定义需要拦截的错误码,并重定向到/error路径
error_page 404 405 500 502 503 504 /error;
# 业务location示例(可根据实际需求调整)
location /test {
root /usr/local/nginx/html;
}
# 错误页面匹配规则(alias指向实际错误文件)
location /error {
# 指向第一步创建的错误文件路径
alias /usr/local/nginx/errorpage/err_info;
# 强制返回200状态码(可选,避免浏览器默认错误页覆盖)
add_header Content-Type text/plain;
return 200;
}
}
第三步:验证配置并重启 Nginx
# 1. 检查Nginx配置是否有语法错误
[root@Nginx ~]# /usr/local/nginx/sbin/nginx -t
# 正常输出:nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
# nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
# 2. 重启Nginx使配置生效
[root@Nginx ~]# /usr/local/nginx/sbin/nginx -s reload
第四步:测试效果
# 访问不存在的路径(触发404错误)
[root@Nginx ~]# curl test.example.com/test/non-exist-page
抱歉,你访问的页面暂时无法访问,请稍后重试!
# 或用浏览器访问 http://test.example.com/test/任意不存在的页面
关键说明
error_page:指定需要自定义的 HTTP 错误码,多个用空格分隔,/error是自定义的跳转路径;location /error:匹配跳转路径,alias指向实际的错误提示文件(区别于root,alias会直接匹配文件而非目录);- 错误文案可自由修改,也可以替换为 HTML 文件(只需将
echo的内容改为 HTML 代码,或直接上传 HTML 文件到对应目录); - 若需对不同错误码显示不同内容,可配置多个
location(如/error404、/error502)并分别关联不同文件。
自定义错误日志
一、操作前提
- 已安装 Nginx 且能正常启动
- 拥有 Nginx 配置文件和日志目录的读写权限
- 提前创建错误页面目录及文件(示例中
/usr/local/nginx/errorpage/errormessage)
二、完整操作步骤
1. 创建自定义错误日志目录
# 创建日志存储目录(按需替换域名)
mkdir -p /usr/local/nginx/logs/timinglee.org/
2. 编辑 Nginx 虚拟主机配置文件
vim /usr/local/nginx/conf/conf.d/vhosts.conf
3. 添加 / 修改 server 块配置
在配置文件中新增或修改如下 server 配置(核心与示例一致):
server {
listen 80;
# 替换为你的域名/主机名
server_name lee.timinglee.org;
# 定义需要捕获的错误码,并重定向到/error路径
error_page 404 405 503 502 /error;
# 定义错误日志存储路径和日志级别(error为常用级别)
error_log logs/timinglee.org/lee.error error;
# 业务路径示例(按需修改)
location /lee {
root /usr/local/nginx/html;
}
# 错误页面映射(alias指向实际错误页面目录)
location /error {
alias /usr/local/nginx/errorpage/errormessage;
}
}
4. 重启 Nginx 服务使配置生效
systemctl restart nginx.service
# 可选:验证配置是否正确(避免重启失败)
nginx -t
5. 测试错误日志生成
# 1. 进入日志目录查看文件是否存在
cd /usr/local/nginx/logs/timinglee.org/
ls
# 预期输出:lee.error
# 2. 模拟访问不存在的页面(触发404错误)
curl lee.timinglee.org/lee/
# 3. 查看错误日志内容
cat lee.error
三、预期输出示例
# curl命令输出(错误页面内容)
太不巧了,你要访问的页面辞职了!!
# cat lee.error输出(错误日志)
2026/02/01 11:10:57 [error] 2467#0: *1 "/usr/local/nginx/html/lee/index.html" is not found (2: No such file or directory), client: 172.25.254.100, server: lee.timinglee.org, request: "GET /lee/ HTTP/1.1", host: "lee.timinglee.org"
四、关键说明
- error_log 参数 :
logs/timinglee.org/lee.error是相对路径(基于 Nginx 安装目录),也可写绝对路径(如/usr/local/nginx/logs/timinglee.org/lee.error);最后一个error是日志级别(可选:debug/info/notice/warn/error/crit/alert/emerg)。 - error_page :将指定错误码重定向到
/error路径,需确保location /error的alias目录存在且有可读的错误页面文件(如 index.html)。 - alias 与 root 区别 :
alias会替换匹配的路径(此处/error会指向/usr/local/nginx/errorpage/errormessage),而root是在指定目录后拼接访问路径,需根据实际场景选择。
五、常见问题排查
- 重启 Nginx 失败:执行
nginx -t检查配置语法错误,确保目录权限(Nginx 进程用户需有日志目录写入权限)。 - 日志无内容:检查访问的 URL 是否真的触发指定错误码,或日志级别设置过高(如设为 crit 则 error 级别日志不会记录)。
- 错误页面不显示:检查
alias路径是否正确,错误页面文件是否存在,且文件权限为 Nginx 进程可读。
Nginx中建立下载服务器
一、基础环境准备(创建下载目录与测试文件)
-
创建 Nginx 下载目录
[root@Nginx ~]# mkdir -p /usr/local/nginx/download
-
复制测试文件到下载目录
[root@Nginx ~]# cp /etc/passwd /usr/local/nginx/download/
-
创建 100MB 的大测试文件
[root@Nginx ~]# dd if=/dev/zero of=/usr/local/nginx/download/bigfile bs=1M count=100
执行后会输出类似:
记录了100+0 的读入
记录了100+0 的写出
104857600字节(105 MB,100 MiB)已复制,0.152409 s,688 MB/s
二、配置 Nginx 虚拟主机(基础下载目录)
-
编辑 Nginx 虚拟主机配置文件
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
-
写入基础配置(监听 80 端口,指定下载目录)
server {
listen 80;
server_name lee.timinglee.org; # 替换为你的域名/服务器IP
error_page 404 405 503 502 /error;
error_log logs/timinglee.org/lee.error error;location /lee { root /usr/local/nginx/html; } location /error { alias /usr/local/nginx/errorpage/errormessage; } location /download { root /usr/local/nginx; }}
-
重新加载 Nginx 配置
[root@Nginx ~]# nginx -s reload
三、启用目录列表功能
-
编辑配置文件,添加
autoindex on;[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
修改后配置:
server {
listen 80;
server_name lee.timinglee.org;
error_page 404 405 503 502 /error;
error_log logs/timinglee.org/lee.error error;
location /lee {
root /usr/local/nginx/html;
}
location /error {
alias /usr/local/nginx/errorpage/errormessage;
}
location /download {
root /usr/local/nginx;
autoindex on; # 启用目录列表
}
}
-
重新加载配置
[root@Nginx ~]# nginx -s reload
此时访问 http://lee.timinglee.org/download/ 可看到文件列表。
四、限制下载速度
-
编辑配置文件,添加
limit_rate 1024k;(限制为 1MB/s)[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
修改后配置:
server {
listen 80;
server_name lee.timinglee.org;
error_page 404 405 503 502 /error;
error_log logs/timinglee.org/lee.error error;
location /lee {
root /usr/local/nginx/html;
}
location /error {
alias /usr/local/nginx/errorpage/errormessage;
}
location /download {
root /usr/local/nginx;
autoindex on;
limit_rate 1024k; # 限制下载速度为1MB/s
}
}
-
重新加载配置
[root@Nginx ~]# nginx -s reload
-
测试下载速度(删除原有测试文件,重新下载)运行
[root@Nginx ~]# rm -fr bigfile
[root@Nginx ~]# wget http://lee.timinglee.org/download/bigfile
此时下载速度会被限制在 1MB/s 左右。
五、优化文件大小显示(人性化显示)
-
编辑配置文件,添加
autoindex_exact_size off;[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
修改后配置:
server {
listen 80;
server_name lee.timinglee.org;
error_page 404 405 503 502 /error;
error_log logs/timinglee.org/lee.error error;
location /lee {
root /usr/local/nginx/html;
}
location /error {
alias /usr/local/nginx/errorpage/errormessage;
}
location /download {
root /usr/local/nginx;
autoindex on;
limit_rate 1024k;
autoindex_exact_size off; # 人性化显示文件大小(如100M而非字节数)
}
}
-
重新加载配置
[root@Nginx ~]# nginx -s reload
-
验证效果
[root@Nginx ~]# curl lee.timinglee.org/download/
输出中文件大小会显示为 100M 而非字节数。
六、调整时间显示(使用本地时间)
-
编辑配置文件,添加
autoindex_localtime on;[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
修改后配置:nginx
server {
listen 80;
server_name lee.timinglee.org;
error_page 404 405 503 502 /error;
error_log logs/timinglee.org/lee.error error;
location /lee {
root /usr/local/nginx/html;
}
location /error {
alias /usr/local/nginx/errorpage/errormessage;
}
location /download {
root /usr/local/nginx;
autoindex on;
limit_rate 1024k;
autoindex_exact_size off;
autoindex_localtime on; # 显示本地时间(默认UTC)
}
}
-
重新加载配置
[root@Nginx ~]# nginx -s reload
此时目录列表中的文件时间会显示服务器本地时间。
七、自定义目录列表风格
-
编辑配置文件,添加
autoindex_format(可选 html/xml/json/jsonp)[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
修改后配置(以 xml 为例,可替换为 html/json/jsonp):
server {
listen 80;
server_name lee.timinglee.org;
error_page 404 405 503 502 /error;
error_log logs/timinglee.org/lee.error error;
location /lee {
root /usr/local/nginx/html;
}
location /error {
alias /usr/local/nginx/errorpage/errormessage;
}
location /download {
root /usr/local/nginx;
autoindex on;
limit_rate 1024k;
autoindex_exact_size off;
autoindex_localtime on;
autoindex_format xml; # 可选值:html | xml | json | jsonp
}
}
-
重新加载配置
[root@Nginx ~]# nginx -s reload
访问 http://lee.timinglee.org/download/ 即可看到对应风格的目录列表。
注意事项
- 替换
lee.timinglee.org为你的实际域名或服务器 IP; - 确保 Nginx 已正确安装,且配置文件路径与示例一致(若路径不同,需对应修改);
- 若
nginx -s reload报错,执行nginx -t检查配置语法错误; - 需保证
/usr/local/nginx/errorpage/errormessage目录存在(若不需要错误页面,可删除error_page和location /error相关配置)
Nginx的文件检测
一、创建错误页文件
-
首先创建 Nginx 错误页存放目录(若不存在):
mkdir -p /usr/local/nginx/errorpage
-
创建默认错误页文件并写入内容:
echo default > /usr/local/nginx/errorpage/default.html
-
验证文件内容:
cat /usr/local/nginx/errorpage/default.html
执行后应输出:default
二、配置 Nginx 虚拟主机
-
编辑虚拟主机配置文件:
vim /usr/local/nginx/conf/conf.d/vhosts.conf
-
写入以下配置内容(替换
lee.timinglee.org为你的域名 / 主机名):server {
listen 80;
server_name lee.timinglee.org; # 替换为实际域名/IP
error_page 404 405 503 502 /error; # 定义错误码跳转
error_log logs/timinglee.org/lee.error error; # 错误日志路径
root /usr/local/nginx/errorpage; # 站点根目录
try_files uri uri.html $uri/index.html /default.html; # 文件查找顺序
}
三、重载 Nginx 配置
nginx -s reload
若报错需先检查配置语法:
nginx -t,确保无语法错误后再重载。
四、测试访问
使用 curl 命令访问不存在的路径,验证是否返回 default 内容:
curl -v lee.timinglee.org/aaaaaaaaaa/
预期输出关键信息:
< HTTP/1.1 200 OK
< Content-Length: 8
...
default
关键说明
- 需确保 Nginx 的安装路径为
/usr/local/nginx,若为其他路径(如/etc/nginx),需同步修改配置中的目录路径; server_name需替换为实际的域名或服务器 IP,否则无法匹配访问;try_files指令是核心:Nginx 会依次查找$uri(请求路径)、$uri.html、$uri/index.html,若都不存在则返回default.html的内容;- 错误日志目录
logs/timinglee.org/需提前创建(mkdir -p /usr/local/nginx/logs/timinglee.org/),否则重载时会报错。
Nginx的状态页
一、操作步骤
1. 创建认证密码文件(.htpasswd)
# 生成密码文件,用户名为自定义(示例用nginx_admin)
[root@Nginx ~]# htpasswd -c /usr/local/nginx/conf/.htpasswd nginx_admin
# 执行后按提示输入2次密码(如:Nginx@123456)
说明:
-c表示创建新文件,若后续新增用户,去掉-c即可。
2. 编辑虚拟主机配置文件
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
写入以下配置(按需修改server_name和允许的 IP 段):
server {
listen 80;
# 替换为你的域名/服务器IP
server_name lee.timinglee.org;
location /nginx_status{
# 启用Nginx状态页
stub_status;
# 认证提示语
auth_basic "auth login";
# 认证密码文件路径
auth_basic_user_file /usr/local/nginx/conf/.htpasswd;
# 允许访问的IP段(按需修改)
allow 172.25.254.0/24;
# 拒绝其他所有IP
deny all;
}
}
3. 检查配置并重新加载 Nginx
# 检查配置语法是否错误
[root@Nginx ~]# /usr/local/nginx/sbin/nginx -t
# 语法无错后重新加载配置
[root@Nginx ~]# /usr/local/nginx/sbin/nginx -s reload
# 若用系统服务管理,可执行:systemctl reload nginx
二、访问验证
-
从允许的 IP 段(如 172.25.254.xxx)访问:
http://lee.timinglee.org/nginx_status -
弹出认证框,输入用户名(nginx_admin)和密码(如 Nginx@123456)
-
成功访问后,页面显示 Nginx 状态信息,示例:
Active connections: 1
server accepts handled requests
1 1 1
Reading: 0 Writing: 1 Waiting: 0
三、常见问题排查
- 403 Forbidden:检查
allow段 IP 是否正确,或deny all是否误写 - 认证框不弹出:检查
auth_basic_user_file路径是否正确,.htpasswd 文件权限(推荐 644) - 500 Internal Error:检查
stub_status是否启用(Nginx 编译时需包含--with-http_stub_status_module模块)- 验证模块:
/usr/local/nginx/sbin/nginx -V | grep stub_status
- 验证模块:
Nginx的压缩功能
一、环境准备(以 CentOS/RedHat 为例)
-
确保 Nginx 已安装并能正常启动
# 检查 Nginx 状态 systemctl status nginx # 若未安装,执行安装(以 yum 为例) yum install -y nginx
二、创建测试文件目录及文件
-
创建站点根目录
mkdir -p /usr/local/nginx/timinglee.org/lee/html -
创建小型测试文件
echo "hello lee" > /usr/local/nginx/timinglee.org/lee/html/index.html -
创建大型测试文件(复用 Nginx 访问日志)
cp /usr/local/nginx/logs/access.log /usr/local/nginx/timinglee.org/lee/html/bigfile.txt
三、配置 Nginx 压缩功能
-
编辑 Nginx 主配置文件
vim /usr/local/nginx/conf/nginx.conf -
在
http {}块内添加以下压缩配置(若已有相关配置,替换 / 补充)# 开启 gzip 压缩 gzip on; # 压缩级别(1-9,级别越高压缩率越高但消耗 CPU 越多) gzip_comp_level 4; # 禁用 IE6 及以下版本的压缩(兼容性问题) gzip_disable "MSIE [1-6]\."; # 仅压缩大于 1024KB 的文件(小文件无需压缩,节省资源) gzip_min_length 1024k; # 指定需要压缩的文件类型 gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/gif image/png; # 向响应头添加 Vary: Accept-Encoding(告知代理服务器缓存压缩/未压缩版本) gzip_vary on; # 开启预压缩(若有 .gz 预压缩文件,优先使用) gzip_static on; -
编辑虚拟主机配置文件
vim /usr/local/nginx/conf/conf.d/vhosts.conf -
添加 / 修改虚拟主机配置
server { listen 80; # 站点域名(需确保本地 hosts 或 DNS 解析生效) server_name lee.timinglee.org; # 站点根目录 root /usr/local/nginx/timinglee.org/lee/html; # 可选:配置 Nginx 状态监控(带基础认证) location /nginx_status{ stub_status; auth_basic "auth login"; auth_basic_user_file /usr/local/nginx/conf/.htpasswd; allow 172.25.254.0/24; # 仅允许该网段访问状态页 deny all; } } -
(可选)若配置了
auth_basic,创建认证文件(需安装 httpd-tools)yum install -y httpd-tools htpasswd -c /usr/local/nginx/conf/.htpasswd 用户名 # 按提示输入密码即可
四、重载 Nginx 配置(使配置生效)
nginx -s reload
若报错,执行
nginx -t检查配置语法,根据提示修正。
五、测试压缩功能
-
测试大型文件(bigfile.txt)的压缩响应
curl --head --compressed lee.timinglee.org/bigfile.txt预期输出(关键看
Content-Encoding: gzip):HTTP/1.1 200 OK Server: nginx/1.28.1 Date: Sun, 01 Feb 2026 07:32:10 GMT Content-Type: text/plain Last-Modified: Sun, 01 Feb 2026 07:29:53 GMT Connection: keep-alive Keep-Alive: timeout=100 Vary: Accept-Encoding ETag: W/"697f00f1-2ca84bd" Content-Encoding: gzip -
测试小型文件(index.html)的响应(因
gzip_min_length 1024k,不会压缩)curl --head --compressed lee.timinglee.org/index.html预期输出(无 Content-Encoding: gzip):
HTTP/1.1 200 OK Server: nginx/1.28.1 Date: Sun, 01 Feb 2026 07:32:19 GMT Content-Type: text/html Content-Length: 10 Last-Modified: Sun, 01 Feb 2026 07:19:59 GMT Connection: keep-alive Keep-Alive: timeout=100 ETag: "697efe9f-a" Accept-Ranges: bytes
关键说明
-
gzip_min_length 1024k表示仅文件大小超过 1024KB 才会压缩,因此index.html(仅 10 字节)不会触发压缩; -
--compressed参数告诉 curl 接收压缩响应,模拟浏览器的压缩请求; -
若测试时域名
lee.timinglee.org无法解析,可临时修改/etc/hosts:echo "本机IP lee.timinglee.org" >> /etc/hosts -
压缩级别
gzip_comp_level建议根据服务器性能调整
Nginx 变量
一、环境准备
-
安装依赖包
yum install -y gcc gcc-c++ make pcre-devel zlib-devel openssl-devel wget
-
下载 Nginx 和 echo 模块
下载 Nginx 1.28.1
wget http://nginx.org/download/nginx-1.28.1.tar.gz
下载 echo 模块(用于输出变量)
wget https://github.com/openresty/echo-nginx-module/archive/v0.64.tar.gz -O echo-nginx-module-0.64.tar.gz
解压
tar zxf nginx-1.28.1.tar.gz
tar zxf echo-nginx-module-0.64.tar.gz -
创建 Nginx 用户
useradd -M -s /sbin/nologin nginx
二、编译安装带 echo 模块的 Nginx
-
停止原有 Nginx(如有)
systemctl stop nginx
ps aux | grep nginx | grep -v grep | awk '{print $2}' | xargs kill -9 2>/dev/null -
配置编译参数(核心:添加 echo 模块)
cd nginx-1.28.1
make clean # 清空旧编译文件
./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
--add-module=/root/echo-nginx-module-0.64 # echo 模块路径 -
编译并替换 Nginx 二进制文件
make # 仅编译(无需 make install,避免覆盖配置)
rm -rf /usr/local/nginx/sbin/nginx # 删除旧二进制文件
cp objs/nginx /usr/local/nginx/sbin/ -p # 替换新二进制文件
三、配置虚拟主机并测试内置变量
步骤 1:基础配置(输出 $remote_addr)
-
创建站点目录
mkdir -p /usr/local/nginx/timinglee.org/lee/html
-
编辑虚拟主机配置
vim /usr/local/nginx/conf/conf.d/vhosts.conf
写入以下内容:
server {
listen 80;
server_name lee.timinglee.org; # 需解析到 Nginx 服务器 IP
root /usr/local/nginx/timinglee.org/lee/html;
location /vars {
default_type text/html; # 指定响应类型
echo $remote_addr; # 输出客户端 IP
}
}
-
验证配置并启动 Nginx
/usr/local/nginx/sbin/nginx -t # 验证配置语法
systemctl start nginx # 启动 Nginx(若未创建 systemd 服务,用 /usr/local/nginx/sbin/nginx) -
测试
curl http://lee.timinglee.org/vars
输出示例:172.25.254.100(客户端 IP)
步骤 2:测试 $args(URL 参数)
-
修改配置
vim /usr/local/nginx/conf/conf.d/vhosts.conf
修改 location /vars 段:
location /vars {
default_type text/html;
echo $args; # 输出 URL 参数
}
-
重载配置并测试
/usr/local/nginx/sbin/nginx -s reload
curl "http://lee.timinglee.org/vars?key=lee&id=11"输出示例:key=lee&id=11
步骤 3:测试 $is_args(是否存在参数)
-
修改配置
location /vars {
default_type text/html;
echo args; echo is_args; # 有参数输出 "?",无参数输出空
} -
重载并测试
/usr/local/nginx/sbin/nginx -s reload
带参数测试
curl "http://lee.timinglee.org/vars?key=lee&id=11"
输出:
key=lee&id=11
?
无参数测试
curl http://lee.timinglee.org/vars
输出:
(空行)
步骤 4:测试 $document_root(站点根目录)
-
修改配置
location /vars {
default_type text/html;
echo $document_root;
} -
重载并测试
/usr/local/nginx/sbin/nginx -s reload
curl "http://lee.timinglee.org/vars?key=lee&id=11"输出:/usr/local/nginx/timinglee.org/lee/html
步骤 5:批量测试常用内置变量
-
修改配置(覆盖所有核心变量)
server {
listen 80;
server_name lee.timinglee.org;
root /usr/local/nginx/timinglee.org/lee/html;
location /vars {
default_type text/html;
echo remote_addr; # 客户端 IP echo args; # URL 参数
echo is_args; # 是否有参数(? 或空) echo document_root; # 站点根目录
echo document_uri; # 请求 URI(不含参数) echo host; # 请求主机名
echo remote_port; # 客户端端口 echo remote_user; # 认证用户名(需配置认证)
echo request_method; # 请求方法(GET/POST 等) echo request_filename; # 请求对应的本地文件路径
echo request_uri; # 完整请求 URI(含参数) echo scheme; # 协议(http/https)
echo server_protocol; # 服务器协议(HTTP/1.1 等) echo server_addr; # 服务器 IP
echo server_name; # 服务器名 echo server_port; # 服务器端口
echo http_user_agent; # 客户端 User-Agent echo cookie_key2; # Cookie 中的 key2 值
echo $sent_http_content_type; # 响应的 Content-Type
}
} -
重载配置并带参数测试(模拟 Cookie、User-Agent、认证)
/usr/local/nginx/sbin/nginx -s reload
带 Cookie、User-Agent、基础认证测试
curl -b "key1=hello,key2=timinglee" -A "haha" -ulee:lee "http://lee.timinglee.org/vars?key=lee&id=11"
输出示例:
172.25.254.100
key=lee&id=11
?
/usr/local/nginx/timinglee.org/lee/html
/vars
lee.timinglee.org
45156
lee
GET
/usr/local/nginx/timinglee.org/lee/html/vars
/vars?key=lee&id=11
http
HTTP/1.1
172.25.254.100
lee.timinglee.org
80
haha
timinglee
text/html
关键说明
echo-nginx-module是第三方模块,必须重新编译 Nginx 才能使用;- 测试前需确保
lee.timinglee.org解析到 Nginx 服务器 IP(可修改本地 hosts 文件); - 各变量含义:
$remote_addr:客户端 IP$args:URL 所有参数$is_args:存在参数则为?,否则为空$document_root:当前 location 对应的根目录$request_uri:完整请求路径(含参数)$http_xxx:读取请求头(如$http_user_agent对应 User-Agent)$cookie_xxx:读取 Cookie 中的指定键值$sent_http_xxx:设置 / 输出响应头
常见问题解决
- 编译报错:检查依赖包是否安装完整(pcre-devel、zlib-devel 等);
- 重载配置失败:检查配置文件语法(
nginx -t),确保路径、括号匹配; - 访问 404:确认
root目录存在,且server_name解析正确; - echo 无输出:确认 Nginx 已编译 echo 模块(
nginx -V查看编译参数)。
自定义变量
1. 编辑 Nginx 虚拟主机配置文件
# 编辑vhosts.conf配置文件(若文件不存在会创建,确保conf.d目录存在)
vim /usr/local/nginx/conf/conf.d/vhosts.conf
2. 写入完整配置内容
将以下配置粘贴到文件中(覆盖原有内容或新增该 server 块):
server {
listen 80;
server_name lee.timinglee.org;
root /usr/local/nginx/timinglee.org/lee/html;
location /vars {
default_type text/html;
# 打印Nginx内置变量
echo $remote_addr;
echo $args;
echo $is_args;
echo $document_root;
echo $document_uri;
echo $host;
echo $remote_port;
echo $remote_user;
echo $request_method;
echo $request_filename;
echo $request_uri;
echo $scheme;
echo $server_protocol;
echo $server_addr;
echo $server_name;
echo $server_port;
echo $http_user_agent;
echo $cookie_key2;
echo $http_user_agent;
echo $sent_http_content_type;
# 自定义变量&变量传递
set $test lee;
echo $test;
set $web_port $server_port;
echo $web_port;
}
}
3. 重载 Nginx 配置(使配置生效)
nginx -s reload
若提示
nginx: [error] open() "/var/run/nginx.pid" failed (2: No such file or directory),先执行nginx启动服务,再执行重载命令。
4. 测试访问(验证变量输出)
curl lee.timinglee.org/vars/
预期输出说明
执行 curl 后会输出如下内容(部分值因环境不同会变化,如 remote_addr、remote_port):
172.25.254.100 # $remote_addr(客户端IP)
# $args(请求参数,无则空)
# $is_args(是否有参数,无则空)
/usr/local/nginx/timinglee.org/lee/html # $document_root(网站根目录)
/vars/ # $document_uri(请求URI)
lee.timinglee.org # $host(请求主机名)
42538 # $remote_port(客户端端口)
# $remote_user(认证用户,无则空)
GET # $request_method(请求方法)
/usr/local/nginx/timinglee.org/lee/html/vars/ # $request_filename(请求文件路径)
/vars/ # $request_uri(完整请求URI)
http # $scheme(请求协议)
HTTP/1.1 # $server_protocol(请求协议版本)
172.25.254.100 # $server_addr(服务器IP)
lee.timinglee.org # $server_name(配置的服务器名)
80 # $server_port(监听端口)
curl/7.76.1 # $http_user_agent(客户端代理)
# $cookie_key2(cookie值,无则空)
curl/7.76.1 # 重复输出$http_user_agent
text/html # $sent_http_content_type(响应Content-Type)
lee # 自定义变量$test
80 # 变量传递后的$web_port
前置条件说明
- 需提前创建网站根目录:
mkdir -p /usr/local/nginx/timinglee.org/lee/html - 本地需解析
lee.timinglee.org到 Nginx 服务器 IP(可修改/etc/hosts添加:服务器IP lee.timinglee.org) - Nginx 需安装
echo模块(若未安装,echo指令会报错,需重新编译 Nginx 加入--add-module=echo-nginx-module)
Nginx利用网页重写实现全站加密
一、环境准备
- 确保已安装 Nginx(推荐 1.18 + 版本)和 openssl 工具:
bash
运行
# CentOS/RHEL
yum install -y nginx openssl
# Ubuntu/Debian
apt install -y nginx openssl
- 创建证书存放目录(确保 Nginx 进程有权限访问):
bash
运行
mkdir -p /usr/local/nginx/certs
chmod 700 /usr/local/nginx/certs
二、生成自签 SSL 证书(生产环境建议用 CA 签发证书)
执行 openssl 命令生成 2048 位 RSA 密钥 + X509 证书,有效期 365 天:
bash
运行
openssl req -newkey rsa:2048 -nodes -sha256 \
-keyout /usr/local/nginx/certs/yourdomain.com.key \
-x509 -days 365 \
-out /usr/local/nginx/certs/yourdomain.com.crt
执行后会提示填写证书信息(可按实际填写,测试环境可直接回车):
plaintext
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:Beijing
Locality Name (eg, city) [Default City]:Beijing
Organization Name (eg, company) [Default Company Ltd]:Test Corp
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:yourdomain.com
Email Address []:admin@yourdomain.com
三、编辑 Nginx 虚拟主机配置
- 打开配置文件(按需调整路径):
bash
运行
vim /usr/local/nginx/conf/conf.d/vhosts.conf
- 写入以下配置(替换域名 / 网站根目录):
nginx
server {
# 监听80端口(HTTP)和443端口(HTTPS)
listen 80;
listen 443 ssl;
# 配置SSL证书和私钥路径
ssl_certificate /usr/local/nginx/certs/yourdomain.com.crt;
ssl_certificate_key /usr/local/nginx/certs/yourdomain.com.key;
# 优化SSL会话缓存(提升性能)
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
# 配置域名(替换为实际域名)
server_name yourdomain.com;
# 配置网站根目录(替换为实际路径)
root /webdir/yourdomain.com/html;
# 核心:HTTP强制跳转HTTPS
location / {
if ($scheme = http ){
rewrite /(.*) https://$host/$1 redirect;
}
}
}
四、重启 Nginx 并验证
- 重启 Nginx 服务:
bash
运行
# 检查配置语法(关键!避免配置错误导致启动失败)
nginx -t
# 语法无错后重启
systemctl restart nginx
- 测试跳转效果:
bash
运行
curl -I http://yourdomain.com
预期返回结果(包含 302 跳转和 HTTPS 地址):
plaintext
HTTP/1.1 302 Moved Temporarily
Server: nginx/xxx.xxx
Date: Xxx, XX Xxx XXXX XX:XX:XX GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: https://yourdomain.com/
补充说明
- 生产环境建议:
- 替换自签证书为 Let's Encrypt 等免费可信 CA 证书
- 增加 SSL 协议 / 加密套件优化(如禁用低版本 SSL/TLS)
- 配置 HSTS 头(强制浏览器长期使用 HTTPS)
- 常见问题:
- 若跳转失败,检查防火墙 / SELinux 是否放行 80/443 端口
- 确认 Nginx 配置文件路径、证书路径、网站根目录权限正确
- 避免多个 server 块冲突(确保域名唯一匹配)
防盗链
一、完整复刻操作步骤
1. 配置 Nginx 防盗链规则
登录 Nginx 服务器,编辑虚拟主机配置文件:
[root@Nginx ~]# vim /usr/local/nginx/conf/conf.d/vhosts.conf
写入以下配置(核心是valid_referers校验来源,区分全站和 /img 目录规则):
server {
listen 80;
server_name lee.timinglee.org; # 替换为你的域名/IP
root /webdir/timinglee.org/lee/html; # 替换为实际网页根目录
# 全站防盗链(非/img目录):非法来源返回404
location / {
valid_referers none blocked server_names *.timinglee.org ~/.baidu/.;
if ($invalid_referer){
return 404;
}
}
# /img目录防盗链:非法来源重定向到指定图片
location /img {
valid_referers none blocked server_names *.timinglee.org ~/.baidu/.;
if ($invalid_referer){
rewrite ^/ http://lee.timinglee.org/daolian/daolian.png; # 替换为你的"防盗链占位图"地址
}
}
}
2. 重载 Nginx 配置(使规则生效)
[root@Nginx ~]# nginx -s reload
若报错,先执行
nginx -t检查配置语法,修复后再重载。
3. 准备盗链测试环境(另一台 Web 服务器)
步骤 1:安装 Web 服务(以 CentOS 为例)
[root@RS1 ~]# yum install -y httpd # 安装Apache
[root@RS1 ~]# systemctl start httpd && systemctl enable httpd # 启动并开机自启
步骤 2:创建盗链测试页面
[root@RS1 ~]# vim /var/www/html/index.html
写入以下 HTML 代码(核心是引用目标服务器的图片):
<html>
<head>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<title>盗链测试</title>
</head>
<body>
<!-- 引用目标服务器的图片(盗链核心) -->
<img src="http://lee.timinglee.org/img/lee.png">
<h1 style="color:red">盗链测试页面</h1>
<p><a href=http://lee.timinglee.org>访问原站</a></p>
</body>
</html>
4. 测试验证
- 确保
lee.timinglee.org能解析到 Nginx 服务器 IP(可修改本地 hosts 文件); - 在浏览器访问盗链服务器地址(如
http://RS1的IP/index.html); - 观察效果:
- 若来源非法:
/img目录的图片会被替换为daolian.png,全站其他资源返回 404; - 若来源合法(如从
*.timinglee.org或百度跳转):正常显示图片。
- 若来源非法:
二、关键参数说明
| 配置项 | 作用 |
|---|---|
valid_referers |
定义合法的 Referer(来源),多个值用空格分隔:- none:无 Referer(如直接访问)- blocked:Referer 被防火墙屏蔽- server_names:匹配当前 server_name- *.timinglee.org:匹配子域名- ~/.baidu/:正则匹配百度来源 |
$invalid_referer |
Nginx 内置变量,合法 Referer 时为0,非法时为1 |
rewrite ^/ 目标地址 |
非法来源时重写 URL,将所有 /img 目录请求跳转到占位图 |
三、注意事项
- 需提前在 Nginx 服务器创建目录:
/webdir/timinglee.org/lee/html/img(存放lee.png)、/webdir/timinglee.org/lee/html/daolian(存放daolian.png); - Referer 可被伪造,防盗链仅为基础防护,若需更强防护可结合:- 图片加水印- 限制 IP 访问频率- 基于 Cookie/Token 验证;
- 测试时关闭浏览器缓存,避免缓存导致效果不生效。
Nginx反向代理
一、基础环境准备(后端 Web 服务器)
- Nginx 代理服务器:172.25.254.100
- 后端 RS1(Web A):172.25.254.10
- 后端 RS2(Web B):172.25.254.20
1. 后端 RS1/RS2 部署 Apache 服务
# 所有后端服务器执行(RS1、RS2)
dnf install httpd -y # CentOS/RHEL 系,Debian 系用 apt install apache2
systemctl enable --now httpd
# RS1 写入标识内容
echo "172.25.254.10" > /var/www/html/index.html
# RS2 写入标识内容
echo "172.25.254.20" > /var/www/html/index.html
# RS2 额外创建 /web 路径(用于反向代理路径匹配测试)
mkdir /var/www/html/web
echo "172.25.254.20 web" > /var/www/html/web/index.html
2. 测试后端连通性(Nginx 服务器执行)
curl 172.25.254.10 # 应输出 172.25.254.10
curl 172.25.254.20 # 应输出 172.25.254.20
curl 172.25.254.20/web/ # 应输出 172.25.254.20 web
二、Nginx 反向代理配置(基础路径转发)
1. 编辑 Nginx 虚拟主机配置
# Nginx 服务器执行
vim /usr/local/nginx/conf/conf.d/vhosts.conf
写入以下内容:
server {
listen 80;
server_name lee.timinglee.org; # 自定义域名,需配置 hosts 解析
# 根路径代理到 RS1
location / {
proxy_pass http://172.25.254.10:80;
}
# /web 路径代理到 RS2
location /web {
proxy_pass http://172.25.254.20:80;
}
}
2. 重载 Nginx 配置并测试
nginx -s reload
# 测试根路径代理
curl lee.timinglee.org # 应输出 172.25.254.10
# 测试 /web 路径代理
curl lee.timinglee.org/web/ # 应输出 172.25.254.20 web
三、请求头控制(隐藏 / 透传响应头)
1. 隐藏 ETag 响应头
修改 vhosts.conf:
server {
listen 80;
server_name lee.timinglee.org;
location / {
proxy_pass http://172.25.254.10:80;
proxy_hide_header ETag; # 隐藏 ETAG 响应头
}
location /web {
proxy_pass http://172.25.254.20:80;
}
}
重载配置后测试(对比 ETAG 是否消失):
nginx -s reload
curl -v lee.timinglee.org # 响应头中无 ETag 字段
2. 透传后端 Server 响应头
修改 vhosts.conf:
server {
listen 80;
server_name lee.timinglee.org;
location / {
proxy_pass http://172.25.254.10:80;
proxy_pass_header Server; # 透传后端 Server 头(默认 Nginx 会替换)
}
location /web {
proxy_pass http://172.25.254.20:80;
}
}
重载配置后测试(响应头会显示 Apache 而非 Nginx):
nginx -s reload
curl -v lee.timinglee.org # 响应头中 Server: Apache/2.4.62
四、透传真实客户端 IP(X-Forwarded-For)
1. 后端 Apache 配置日志格式(RS1 执行)
vim /etc/httpd/conf/httpd.conf
# 修改 LogFormat 行,添加 X-Forwarded-For 记录
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{X-Forwarded-For}i\"" combined
# 重启 Apache
systemctl restart httpd
2. Nginx 配置透传 X-Forwarded-For
修改 vhosts.conf:
server {
listen 80;
server_name lee.timinglee.org;
location / {
proxy_pass http://172.25.254.10:80;
proxy_set_header X-Forwarded-For $remote_addr; # 透传客户端真实 IP
}
location /web {
proxy_pass http://172.25.254.20:80;
}
}
重载配置后测试:
nginx -s reload
# 客户端访问(模拟)
curl lee.timinglee.org
# 查看 RS1 Apache 日志,验证真实 IP
cat /etc/httpd/logs/access_log
# 日志中最后一列会显示客户端真实 IP(如 172.25.254.1)
五、反向代理 + 负载均衡配置
1. 配置 Nginx 上游服务器组
# 创建上游配置目录
mkdir /usr/local/nginx/conf/upstream/
# 编辑负载均衡配置
vim /usr/local/nginx/conf/upstream/loadbalance.conf
写入:
upstream webserver {
server 172.25.254.10:80 weight=1 fail_timeout=15s max_fails=3; # 权重 1,失败重试 3 次
server 172.25.254.20:80 weight=1 fail_timeout=15s max_fails=3; # 权重 1
server 172.25.254.100:8888 backup; # 备份服务器(主节点都挂时启用)
}
server {
listen 80;
server_name www.timinglee.org;
location / {
proxy_pass http://webserver; # 代理到上游服务器组
}
}
2. 配置备份服务器(Nginx 本地)
# 创建备份页面目录
mkdir /webdir/timinglee.org/error/html -p
echo "error" > /webdir/timinglee.org/error/html/index.html
# 编辑备份虚拟主机配置
vim /usr/local/nginx/conf/conf.d/vhosts.conf
添加:
server {
listen 8888;
root /webdir/timinglee.org/error/html; # 备份页面根目录
}
3. 重载配置并测试负载均衡
nginx -s reload
# 多次访问,验证轮询(weight=1 时默认轮询)
curl www.timinglee.org # 交替输出 172.25.254.10 / 172.25.254.20
# 停止所有后端 Apache,测试备份服务器
systemctl stop httpd # RS1、RS2 都执行
curl www.timinglee.org # 输出 error
关键注意事项
- 域名解析:需在客户端 / 测试机配置
hosts(如172.25.254.100 lee.timinglee.org www.timinglee.org); - Nginx 路径:示例中 Nginx 安装在
/usr/local/nginx,若为系统级安装(如yum install nginx),配置路径为/etc/nginx/; - 权限:确保 Nginx 进程有权访问
/webdir等自定义目录(可执行chown -R nginx:nginx /webdir); - 防火墙:关闭防火墙(
systemctl stop firewalld)或放行 80/8888 端口。