# nginx

### 一、Web 服务器与应用服务器
web服务器：http服务器。主要负责接收、解析http请求的，并返回静态资源/数据(html/css/图片等等)。
常用的http服务器有apache(httpd)、Nginx、IIS、Lighttpd。
应用服务器：用于处理业务逻辑的程序(Java\PHP\Python\go),处理动态请求、并与数据库有交互。
常见的应用服务器
有Tomcat\Weblogic\Jboss等
邮件服务器：收发邮件用的。
数据服务器：Mysql、Oracle、Opengass。

### 二、Nginx 概述
什么是nginx？
nginx：一个web服务器软件，俄罗期工程师开发的，是一个高性能的http服务器和反向代理服务器。
它是免费开源的。以极低的内存，并发能力强。据说1台服务器可以支撑5万个连接。
哪些公司在用：百度、京东、网易、淘宝、腾讯、抖音等等。
官网：http://nginx.org
核心功能：
1.静态资源服务
html/图片/视频等
2.动态资源处理
支持通过 CGI、FastCGI 等协议处理 Perl、PHP 等动态语言，也可通过反向代理与 Java 等应用服务器配合，实现动静分离。

### 三、负载均衡
支持七层（http/https），支持四层（tcp/udp）负载均衡反向代理：
隐藏后端真实服务器的信息，提升安全性
正向代理：
可以作为http正向代理，供内部客户端访问互联网资源
跨平台运行：支持linux/windows操作系统。

nginx是一个多进程程序
master进程：负责读取并且验证配置文件nginx.conf，管理worker进程。
worker进程：若干个，跟CPU核数匹配。
每个worker进程都可以独立处理请求。

Master→创建listenfd→fork()→Worker1,Worker2,Worker3...
1.请求来了，worker进程去获取排它锁，接收请求，处理请求
2.又来一个请求。worker进程去获取排它锁，接收请求，处理请求  
tcp队列．．．

### 四、Nginx 的特点

速度更快：采用事件驱动\内存池\零拷贝
高扩展性：模块化设计，支持lua脚本
高可靠性：master+worker多进程模型，worker出问题，master会迅速重启它。低内存性：据说5万个连接，只要2.5ＭＢ内存 
高并发性：单台机器轻松搞定2-3万个连接。（timeout）
热部署：支持不停机，更新配置\更新主程序 

### 五、版本说明
```bash
[https://nginx.org/en/download.html]
```
生产环境安装的话，首推最新的稳定版本。（有些公司对版本管控要求严格，按公司规定操作）
版本号的中间数字，如果是偶数，那么就是稳定版。

mainline version：主线开发版本，包含最新的功能和优化。
stable version：稳定版本，包含最新的安全修复和bug修复。

常见的变种版本：
```bash
nginx plus：商业版本，企业级付费用户
```
tengeine：淘宝搞出的
openresty nginx：nginx+lua，是一个高性能的Web平台，支持lua脚本扩展功能。
apisix：云原生的网关

### 六、Nginx部署
如果时间很紧，想简单一点，你就用yum。
你想定制路径，体现你的专业能力，你就用源码编译。
gcc软件
autoconf工具（生成makefile脚本）
pcre工具（用于正则）
zlib库（用于压缩）
openssl库（用于启用证书，支持ssl的）

### 七、源码编译
1. 配置yum源
```bash
sed -e 's|^mirrorlist=|#mirrorlist=|g' \
    -e 's|^#baseurl=http://dl.rockylinux.org/$contentdir|baseurl=https://mirrors.aliyun.com/rockylinux|g' \
    -i.bak \
    /etc/yum.repos.d/Rocky-*.repo

dnf makecache

```
2. 安装依赖包
```bash
dnf install -y gcc gcc-c++ make libtool wget pcre pcre-devel zlib zlib-devel openssl openssl-devel

```
3. 创建nginx用户
```bash
useradd -s /sbin/nologin nginx -M

```
4. 下载nginx源码包并解压
```bash
mkdir -p /opt/soft && cd /opt/soft
wget https://nginx.org/download/nginx-1.24.0.tar.gz
tar -zxvf nginx-1.24.0.tar.gz
cd nginx-1.24.0

```
5. 配置编译选项
```bash
./configure \
--prefix=/usr/local/nginx-1.24.0 \
--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

./configure \ 
--prefix=/usr/local/nginx-1.24.0            # 安装路径
```
--user=nginx                                # nginx用户
--group=nginx                               # nginx用户组
--with-http_ssl_module                      # 启用ssl模块
--with-http_v2_module                       # 启用http2模块
--with-http_realip_module                   # 启用realip模块
--with-http_stub_status_module              # 启用stub status模块
--with-http_gzip_static_module              # 启用gzip压缩模块
--with-pcre                                 # 启用pcre模块
--with-stream                               # 启用stream模块
--with-stream_ssl_module                    # 启用stream ssl模块
--with-stream_realip_module                 # 启用stream realip模块 

6. 编译安装
```bash
echo $(nproc) # 查看CPU核数
make -j$(nproc) #速度更快
make install

```
7. 创建软连接（可选）
```bash
ln -s /usr/local/nginx-1.24.0 /usr/local/nginx
ln -s /usr/local/nginx-1.24.0/sbin/nginx /usr/local/bin/nginx

```
8. 验证安装
```bash
/usr/local/nginx-1.24.0/sbin/nginx -V
/usr/local/bin/nginx -V
nginx -V
nginx -t
/usr/local/nginx/sbin/nginx -t 
/usr/local/nginx/sbin/nginx

ss -ant
ps aux | grep nginx
curl -I http://localhost/

```
9. 配置systemd服务
```bash
cat>/etc/systemd/system/nginx.service<<'EOF'
[Unit]
Description=我的nginx服务单元
After=network.target

[Service]
Type=forking
PIDFile=/usr/local/nginx-1.24.0/logs/nginx.pid
ExecStartPre=/usr/local/nginx-1.24.0/sbin/nginx -t -c /usr/local/nginx-1.24.0/conf/nginx.conf
ExecStart=/usr/local/nginx-1.24.0/sbin/nginx -c /usr/local/nginx-1.24.0/conf/nginx.conf 
ExecReload=/usr/local/nginx-1.24.0/sbin/nginx -s reload
ExecStop=/usr/local/nginx-1.24.0/sbin/nginx -s stop
PrivateTmp=true 

[Install]
WantedBy=multi-user.target 
EOF
systemctl daemon-reload 
```
10. 验证systemd服务是否启动

```bash
/usr/local/nginx/sbin/nginx -s stop
systemctl start nginx
systemctl status nginx --no-pager
systemctl stop nginx
systemctl restart nginx
systemctl enable nginx

```
11. 查看systemd服务日志
```bash
systemctl status nginx -l
journalctl -u nginx -xe

### 八、yum安装
dnf install nginx #为何dnf也可以用（在红帽生态系8（含）以上版本，用高效的dnf代替yum，在大于等于8版本yum是dnf的快捷方式）
```
用dnf默认安装nginx,它的版本很老

想安装新版本，需要更换源
```bash
cat>/etc/yum.repos.d/nginx.repo<<'EOF'
[nginx-stable]
name=nginxstablerepo
baseurl=http://nginx.org/packages/centos/8/$basearch/
gpgcheck=0
enabled=1
gpgkey=https://nginx.org/packages/keys/nginx_signing.key module_hotfixes=true
EOF

dnf install -y nginx #安装最新稳定版本

dnf list| grep nginx #所有可安装的nginx版本
dnf module list nginx #所有可安装的nginx模块
dnf module reset nginx #重置nginx模块
dnf module enable nginx #启用nginx模块

### 九、docker安装
[https://developer.aliyun.com/mirror/] [https://download.docker.com]
```
1. 安装yum-utils（仓库 & 软件包增强管理工具）
```bash
dnf install -y yum-utils

```
2. 添加docker-ce仓库
```bash
sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
sed -i 's+download.docker.com+repo.huaweicloud.com/docker-ce+g' /etc/yum.repos.d/docker-ce.repo

```
3. 查看docker-ce版本
--showduplicates：列出仓库里存在的所有版本（各个版本、不同架构全部展示）
```bash
dnf list docker-ce --showduplicates | sort -r

```
4. 安装docker-ce-24.0.9-1.el8 docker-ce-cli-24.0.9-1.el8 containerd.io
```bash
dnf clean all
dnf makecache   
sudo yum install -y docker-ce-24.0.9-1.el8 docker-ce-cli-24.0.9-1.el8 containerd.io

```
5. 移除旧版本docker-ce
```bash
yum remove docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine

```
6. 验证版本
```bash
docker version
docker info

```
7. 配置docker镜像加速(会过期)
```bash
cat > /etc/docker/daemon.json <<EOF
{
    "registry-mirrors": [
        "https://docker.m.daocloud.io",
        "https://dockerproxy.com",
        "https://docker.mirrors.ustc.edu.cn",
        "https://docker.nju.edu.cn",
        "https://iju9kaj2.mirror.aliyuncs.com",
        "https://hub-mirror.c.163.com"
    ]
}
EOF

```
8. 启动docker服务
```bash
systemctl daemon-reload # 刷新systemd配置
systemctl start docker
systemctl stop docker
systemctl enable --now docker
systemctl status docker --no-pager
systemctl restart docker

```
9. 验证docker是否安装成功
```bash
docker run hello-world
docker images 

```
### 十、安装nginx
1. 拉取nginx镜像
```bash
docker pull nginx:1.24.0

```
2. 启动nginx:1.24.0镜像
```bash
docker run -d --name my_nginx1.24.0 -p 8010:80 nginx:1.24.0

```
3. [验证]容器是否启动
```bash
curl http://localhost:8010/
ss -ant | grep 8010 #查看端口是否监听
docker ps #查看容器
docker images #查看镜像

```
4. 拉取nginx:1.28.0镜像
```bash
docker pull nginx:1.28.0

```
5. 关闭nginx:1.24.0容器，删除容器，删除镜像
```bash
#先停止容器（如果在运行）
docker stop my_nginx1.24.0
#删除容器
docker rm my_nginx1.24.0
docker rm CONTAINER ID/NAME
#删除镜像
docker rmi REPOSITORY/IMAGE ID

```
6. 创建nginx-docker目录结构
```bash
mkdir -p /data/nginx-docker/{html,conf,logs,ssl}
mkdir -p /data/nginx-docker/conf/conf.d

```
7. 创建主配置文件nginx.conf
```bash
cat > /data/nginx-docker/conf/nginx.conf <<'EOF'
user  nginx;
worker_processes   auto;

error_log  /var/log/nginx/error.log  notice;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       /etc/nginx/mime.types;
    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  /var/log/nginx/access.log  main;
    sendfile on;
    #tcp_nopush on;

    keepalive_timeout  65;

    #gzip on;
    include /etc/nginx/conf.d/*.conf;
}
EOF

```
8. 创建虚拟主机配置文件
```bash
cat > /data/nginx-docker/conf/conf.d/default.conf <<'EOF'
server {
    listen 80;
    listen [::]:80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}
EOF

```
9. 创建首页展示index.html
```bash
cat > /data/nginx-docker/html/index.html << EOF
<meta charset="UTF-8">
<style>
        body {
            background-color: #000000;
            color: #9900cc;
        }
</style>
<h1>欢迎来到nginx-docker容器</h1>
EOF

```
10. 启动nginx：1.28
```bash
ss -ant | grep 80 # 查看端口是否监听

docker run -d \
--name my-nginx1.28 \
-p 80:80 \
-p 443:443 \
-v /data/nginx-docker/conf/nginx.conf:/etc/nginx/nginx.conf \
-v /data/nginx-docker/conf/conf.d:/etc/nginx/conf.d \
-v /data/nginx-docker/logs:/var/log/nginx \
-v /data/nginx-docker/html:/usr/share/nginx/html \
-v /data/nginx-docker/conf/ssl:/etc/nginx/ssl \
nginx:1.28.1

```
11. [常用工具]
```bash
docker ps -a
docker images
docker rm my-nginx1.28
ps -ef | grep nginx
curl http://localhost:80/
ss -ant | grep 80

```
### 十一、nginx模块
Nginx模板概述
Nginx高度模块化带来的优势 ：
1、灵活性：可按需要开启或禁用一些功能。
2、可扩展性：支持第三模块来扩展原生的功能。
3、可维护性：模块之间解耦，便于独立开发。
4、性能优化：可以按需编译版本，减少内存占用，减少攻击面。
第三方模块集成
添加第三方模块的基本语法
```bash
./configure \
--add-module=/path/to/third-party/module \
--add-dynamic-module=/path/to/dynamic/module

```
模块类型
类型               控制参数
1、内置模块         --without-xxx-module
2、静态模块         --with-xxx-module
3、动态模块         --add-dynamic-module

编译一个动态模块
```bash
./configure --prefix=/usr/local/nginx-1.24.0-2 --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 --with-compat \
--add-dynamic-module=/opt/soft/nginx-rtmp-module-master


make -j 4
make install

vi nginx-1.24.0-2/conf/nginx.conf
load_module modules/ngx_rtmp_module.so;

/usr/local/nginx-1.24.0-2/sbin/nginx

dnf install -y lsof
lsof -p $(cat /usr/local/nginx-1.24.0-2/logs/nginx.pid) | grep \\.so

```
### 十二、nginx进程管理与信息控制
信号         �参数     作用参数     作用描述     适用场景TERM/INT stop 立即停止 - 强制关闭所有 Nginx 进程 紧急停机、服务异常时
QUIT         quit 优雅停止 - 处理完现有请求后关闭 计划停机、维护操作
HUP          reload 热重载 - 重新加载配置文件 配置更新后
USR1         reopen 日志轮转 - 重新打开日志文件 日志切割、备份
USR2         upgrade 平滑升级 - 启动新版本主进程 版本升级、二进制替换
WINCH        winch 优雅关闭工作进程 配合 USR2 完成热升级

1. 立即停止
nginx的开关
```bash
/usr/local/nginx-1.24.0-2/sbin/nginx -s stop
kill -TERM $(cat /usr/local/nginx-1.24.0-2/logs/nginx.pid)

```
2. 优雅关闭
```bash
/usr/local/nginx-1.24.0-2/sbin/nginx -s quit
kill -QUIT $(cat /usr/local/nginx-1.24.0-2/logs/nginx.pid)

```
工作流程 --> 停止接收新连接 --> 处理现有请求 --> 关闭端口 --> 优雅退出进程

3. 标准启动
```bash
/usr/local/nginx-1.24.0-2/sbin/nginx -t
/usr/local/nginx-1.24.0-2/sbin/nginx

```
4. 热加载配置文件
```bash
/usr/local/nginx-1.24.0-2/sbin/nginx -s reload
kill -HUP $(cat /usr/local/nginx-1.24.0-2/logs/nginx.pid)

```
5. 日志轮转
```bash
kill -USR1 $(cat /usr/local/nginx-1.24.0-2/logs/nginx.pid)

### 十三、nginx平滑升级
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx
```
1. 查看当前版本
```bash
/usr/local/nginx/sbin/nginx -v
```
2. 查看编译选项
```bash
/usr/local/nginx/sbin/nginx -V
```
3. 备份当前版本
```bash
cp -aR /usr/local/nginx /usr/local/nginx.bak
```
4. 下载新版本nginx
```bash
wget https://nginx.org/download/nginx-1.25.0.tar.gz
```
5. 解压编译新版本nginx  
```bash
tar -zxvf nginx-1.25.0.tar.gz
cd nginx-1.25.0

./configure \
--prefix=/usr/local/nginx-1.24.0 \
--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
make -j 4

cp -f objs/nginx /usr/local/nginx/sbin/nginx

/usr/local/nginx/sbin/nginx -V

```
6. 更新nginx进程
```bash
ss -ant | grep :80
ps aux | grep nginx | grep -v grep
pid
kill -USR2 $(cat /usr/local/nginx/logs/nginx.pid)
ps aux | grep nginx | grep -v grep 
kill -WINCH 
kill -QUIT 
ps aux | grep nginx | grep -v grep

ps -ef | grep nginx | grep -v grep

### 十四、nginx的目录结构
dnf install tree -y
```
1. nginx的主配置文件
fastcgi_params # 快CGI参数文件
mime.types # 媒体类型文件
html # 静态文件目录
logs # 日志目录
pid # 进程ID文件
sbin # 可执行文件目录
conf # 配置文件目录
modules # 模块目录
obj # 临时文件目录
nginx.conf # 主配置文件
全局配置块
events # 事件配置块
http # HTTP配置块
server # 服务器配置块
location # 位置配置块

2. location路径匹配(重点)
```bash
location [修饰符] url { 配置块 }
https://www.linuxnote.com:443/path/to/page?name=value

```
= 精确匹配 location = /path/to/page
^~ 前缀匹配 location ^~ /path/to/page
* 正则匹配(区分大小写) location ~ /path/to/page
~* 正则匹配(不区分大小写) location ~* /path/to/page
无修饰符 普通匹配 location /path/to/page
/ 通配符匹配 location /

### 十五、nginx的虚拟主机
#### （一）ip
多个ip 多个网站
```bash
ip a
nmcli con mod ens160 +ipv4.address 192.168.20.90/24
nmcli con up ens160

mkdir -p /usr/local/nginx-1.24.0/conf/vhost
mkdir -p /data/www/{151,90}

cat > /usr/local/nginx-1.24.0/conf/vhost/151.conf <<EOF
server {
    listen 80;
    server_name 192.168.20.151;
    location / {
        root /data/www/151;
        index index.html;
    }
}
EOF

cat > /usr/local/nginx-1.24.0/conf/vhost/90.conf <<EOF
server {
    listen 80;
    server_name 192.168.20.90;
    location / {
        root /data/www/90;
        index index.html;
    }
}
EOF

sed -i '$i include /usr/local/nginx-1.24.0/conf/vhost/*.conf;' /usr/local/nginx-1.24.0/conf/nginx.conf

cat > /data/www/151/index.html <<EOF
<meta charset="utf-8">
<h1>欢迎来到151</h1>
EOF

cat > /data/www/90/index.html <<EOF
<meta charset="utf-8">
<h1>欢迎来到90</h1>
EOF

nginx -t
nginx -s reload

```
浏览器访问
```bash
http://192.168.20.151
http://192.168.20.90

```
终端访问
```bash
curl 192.168.20.151
curl 192.168.20.90

```
#### （二）端口
一个ip 多个端口 多个网站

```bash
mkdir -p /data/www/{2000,3000}

cat > /usr/local/nginx-1.24.0/conf/vhost/2000.conf <<EOF
server {
    listen 2000;
    server_name 192.168.20.151;
    location / {
        root /data/www/2000;
        index index.html;
    }
}
EOF

cat > /usr/local/nginx-1.24.0/conf/vhost/3000.conf <<EOF
server {
    listen 3000;
    server_name 192.168.20.151;
    location / {
        root /data/www/3000;
        index index.html;
    }
}
EOF

cat > /data/www/2000/index.html <<EOF
<meta charset="utf-8">
<h1>欢迎来到2000</h1>
EOF

cat > /data/www/3000/index.html <<EOF
<meta charset="utf-8">
<h1>欢迎来到3000</h1>
EOF

nginx -t
nginx -s reload

```
浏览器访问
```bash
http://192.168.20.151:2000
http://192.168.20.151:3000

```
终端访问
```bash
curl 192.168.20.151:2000
curl 192.168.20.151:3000

```
#### （三）域名
一个ip 多个域名 多个网站

```bash
mkdir -p /data/www/{web1,web2}

cat > /usr/local/nginx-1.24.0/conf/vhost/web1.conf <<EOF
server {
    listen 80;
    server_name www.linuxnote1.com;
    location / {
        root /data/www/web1;
        index index.html;
    }
}
EOF

cat > /usr/local/nginx-1.24.0/conf/vhost/web2.conf <<EOF
server {
    listen 80;
    server_name www.linuxnote2.com;
    location / {
        root /data/www/web2;
        index index.html;
    }
}
EOF

cat > /data/www/web1/index.html <<EOF
<meta charset="utf-8">
<h1>欢迎来到web1</h1>
EOF

cat > /data/www/web2/index.html <<EOF
<meta charset="utf-8">
<h1>欢迎来到web2</h1>
EOF

nginx -t
nginx -s reload

echo 192.168.20.151    www.linuxnote1.com >> /etc/hosts
echo 192.168.20.151    www.linuxnote2.com >> /etc/hosts

```
终端访问
```bash
curl www.linuxnote1.com
curl www.linuxnote2.com

```
window C盘模拟 
```bash
C:\Windows\System32\drivers\etc\hosts
192.168.20.151 www.linuxnote1.com
192.168.20.151 www.linuxnote2.com

```
浏览器访问
```bash
http://www.linuxnote1.com
http://www.linuxnote2.com

```
#### （四）Server Name
匹配规则:对 "*.域名" 的匹配规则的运用

```bash
mkdir -p /data/www/{www_linuxnote3.com,all_linuxnote3.com}

cat > /usr/local/nginx-1.24.0/conf/vhost/www_linuxnote3.com.conf <<EOF
server {
    listen 80;
    server_name www.linuxnote3.com;
    location / {
        root /data/www/www_linuxnote3.com;
        index index.html;
    }
}
EOF

cat > /usr/local/nginx-1.24.0/conf/vhost/all_linuxnote3.com.conf <<EOF
server {
    listen 80;
    server_name *.linuxnote3.com;
    location / {
        root /data/www/all_linuxnote3.com;
        index index.html;
    }
}
EOF

cat > /data/www/www_linuxnote3.com/index.html <<EOF
<meta charset="utf-8">
<h1>欢迎来到www_linuxnote3.com</h1>
EOF

cat > /data/www/all_linuxnote3.com/index.html <<EOF
<meta charset="utf-8">
<h1>欢迎来到all_linuxnote3.com</h1>
EOF

nginx -t
nginx -s reload

echo 192.168.20.151    www.linuxnote3.com >> /etc/hosts
echo 192.168.20.151    aaa.linuxnote3.com >> /etc/hosts
echo 192.168.20.151    all.linuxnote3.com >> /etc/hosts

curl www.linuxnote3.com
curl aaa.linuxnote3.com
curl all.linuxnote3.com

```
window C盘模拟 
```bash
C:\Windows\System32\drivers\etc\hosts
192.168.20.151 www.linuxnote3.com
192.168.20.151 aaa.linuxnote3.com
192.168.20.151 all.linuxnote3.com

```
浏览器访问
```bash
http://www.linuxnote3.com
http://aaa.linuxnote3.com
http://all.linuxnote3.com



```
### 十六、nginx模块
1. 查看已经安装的模块
```bash
nginx -V

```
2. 在源码未安装目录查看模块
```bash
/opt/soft/nginx-1.24.0/auto/options 
```
--with 表示不会默认编译安装的模块
--without 表示会默认编译安装的模块

### 十七、访问模块
```bash
studtax: stub_status on
default: -
context: server.location

cat >  /usr/local/nginx-1.24.0/conf/vhost/studtax.conf << EOF
server {
    listen 80 ;
    server_name  192.168.20.151;
    location / {
        root /data/www/all_linuxnote3.com;
        index index.html;
    }
    location /qianshan {
        stub_status;
        access_log off;
    }
}
EOF

cat > /data/www/all_linuxnote3.com/index.html << EOF
<meta charset="UTF-8">
    <h1>all.linuxnote3.com</h1>
EOF


nginx -t
nginx -s reload


192.168.20.151
192.168.20.151/qianshan
curl http://192.168.20.151
curl http://192.168.20.151/qianshan

Active connections: 1
server accepts handled requests
 46 46 44
Reading: 0 Writing: 1 Waiting: 0

```
accepts：#统计总值，Nginx自启动后已经接受的客户端请求连接的总数。
handled：#统计总值，Nginx自启动后已经处理完成的客户端请求连接总数，通常等于accepts。
Reading：#当前状态，正在读取客户端请求报文首部的连接的连接数,数值越大,说明排队现象严重,性能不足。
Writing：#当前状态，正在向客户端发送响应报文过程中的连接数,数值越大,说明访问量很大。
Waiting：#当前状态，正在等待客户端发出请求的空闲连接数。

### 十八、web密码访问控制模块
```bash
syntax： auth_basic [ text|off ]
default: auth_basic off
auth_basic_user_file file_path
context: http, server, location, limit_except

cat > /usr/local/nginx-1.24.0/conf/vhost/studtax.conf << EOF
server {
    listen 80 ;
    server_name  192.168.20.151;
    location / {
        root /data/www/all_linuxnote3.com;
        index index.html;
    }
    location /qianshan {
        stub_status;
        auth_basic "secret你好";
        auth_basic_user_file /usr/local/nginx-1.24.0/conf/vhost/nginx-passwd.db;
        access_log off;
    }
}
EOF

dnf install -y httpd-tools
htpasswd -c /usr/local/nginx-1.24.0/conf/vhost/nginx-passwd.db aaa
chmod 400 /usr/local/nginx-1.24.0/conf/vhost/nginx-passwd.db
chown nginx.nginx /usr/local/nginx-1.24.0/conf/vhost/nginx-passwd.db    

nginx -t
nginx -s reload

http://192.168.20.151/qianshan

```
### 十九、控制客户端访问模块
HttpAccess模块:对客户端的IP地址进行控制
规则是从上向下匹配，一旦匹配上，就停止向下匹配。
访问控制语法如下：
deny IP/IP 段：拒绝某个 IP 或 IP 段的客户端访问。
allow IP/IP 段：允许某个 IP 或 IP 段的客户端访问，如果是所有网段，则用all表示。
IP网段格式：x.x.x.x/24

```bash
cat > /usr/local/nginx-1.24.0/conf/vhost/studtax.conf << EOF
server {
    listen 80 ;
    server_name  192.168.20.151;
    location / {
        root /data/www/all_linuxnote3.com;
        index index.html;
    }
    location /qianshan {
        stub_status;
        auth_basic "secret你好";
        auth_basic_user_file /usr/local/nginx-1.24.0/conf/vhost/nginx-passwd.db;
        allow 192.168.20.0/24;
        allow 124.221.251.28;
        deny all;
        access_log off;
    }
}
EOF

http://192.168.20.151/qianshan
curl http://192.168.20.151/qianshan -u aaa:123456
curl -L http://aaa:123456@192.168.20.151/qianshan
curl ifconfig.me

```
### 二十、正向，反向代理模块
代理：是指一个中间人或第三方，或者叫中介。它代表用户访问网络资源。
代理访问过程中，大约有3个角色，客户端，代理服务器，服务器。
正向代理：被代理的对方是客户端。（squit）
反向代理：被代理的对方是服务端。

#### （一）反向代理
proxy_pass指令
在反向代理中，该指令配置被代理的服务端的URL地址。
作用域：location, if in location, limit_except
```bash
语法：proxy_pass URL;
```
proxy_set_header指令
该指令可以更改客户端请求的请求头信息或添加新的请求头信息，并将这些信息传递给被代理的服务端。
作用域：http, server, location
```bash
语法：proxy_set_header field value;
默认值：proxy_set_header Host $proxy_host; proxy_set_header Connection close;
$proxy_host指的是被代理的服务端的IP名称和端口。

cat > /usr/local/nginx-1.24.0/conf/vhost/studtax.conf << 'EOF'
server {
    listen 80 ;
    server_name  192.168.20.151;
    location / {
        proxy_pass http://192.168.20.145;
        proxy_set_header Host $proxy_host;
        proxy_set_header Connection close;
    }
}
EOF

nginx -t
nginx -s reload

http://192.168.20.151/qianshan

#### （二）正向代理
ngx_http_proxy_connect_module-master.zip
unzip ngx_http_proxy_connect_module-master.zip

cd /opt/soft/nginx-1.24.0
make clean

dnf install -y patch
patch -p1 < /opt/ngx_http_proxy_connect_module-master/patch/proxy_connect_rewrite_102101.patch

./configure \
--prefix=/usr/local/nginx-1.24.0 \
--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=/opt/ngx_http_proxy_connect_module-master

make -j 4
make install

kill -QUIT $(pid)
systemctl restart nginx
ps -ef | grep nginx
nginx -v


cat >/usr/local/nginx-1.24.0/conf/vhost/zproxy.conf<<'EOB'
server {
listen 10000;
resolver 114.114.114.114;#DNS，解析域名时需要配置
server_name localhost;
proxy_connect; #启用 proxy_connect 模块处理 CONNECT 方法
proxy_connect_allow 443 80; #允许的协议，http与https都可以
连接超时设置
proxy_connect_connect_timeout 10s;
proxy_connect_read_timeout 10s;
proxy_connect_send_timeout 10s;
location / {
proxy_pass $scheme://$host$request_uri; #设定代理服务器的协议和地址
传递必要的头部信息
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_buffers 256 4k;
proxy_max_temp_file_size 0k;
连接后端服务器的超时
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_next_upstream error timeout invalid_header http_502;
}
可选：访问日志（便于排查问题）
access_log logs/proxy_access.log;
error_log logs/proxy_error.log;
}
EOB

nginx -t
nginx -s reload
ss -ant

ping www.baidu.com
ip route del default
ip route add default via 192.168.20.10 dev ens160

curl --proxy 192.168.20.151:10000 https://www.qq.com
curl --proxy 192.168.20.151:10000 https://www.163.com
curl --proxy 192.168.20.151:10000 https://www.baidu.com


dnf install -y telnet
telnet 192.168.20.151 10000

```
### 二十一、负载均衡
1. 负载均衡（Load Balancing）是将用户请求分发到多台后端服务器上，以此提高系统的处理能力、可用性和扩展性。

2. Nginx 负载均衡类型
类型 层级 特点 应用场景
七层负载均衡 应用层（HTTP/HTTPS） 基于内容分发，功能丰富 Web应用、API网关
四层负载均衡 传输层（TCP/UDP） 基于IP和端口转发，性能高 数据库、SSH、MySQL

3. 负载均衡算法
轮询（Round Robin）
默认负载均衡策略，每个请求按时间顺序逐一分配到不同的后端服务器。
特点：
服务器宕机自动剔除
适合服务器配置相当、无状态的短连接服务

```bash
upstream backend_servers {
server 172.22.4.203:8080;
server 172.22.4.204:8080;
server 172.22.4.205:8080;
}

```
4. 加权轮询（Weight）
在轮询基础上指定权重，权重越高分配到的请求越多。
特点：
可与其他算法（least_conn、ip_hash）结合使用
适合服务器硬件配置差异较大的场景

```bash
upstream backend_servers {
```
server 172.22.4.203:8080 weight=50; # 性能好，分配更多请求
server 172.22.4.204:8080 weight=3; # 性能中等
server 172.22.4.205:8080 weight=2; # 性能一般
```bash
}

```
5. IP 哈希（ip_hash）
基于客户端IP地址分配，确保同一客户端始终访问同一台服务器。
特点：
解决 Session 共享问题
不能与 backup 同时使用
服务器移除需要手动标记 down
```bash
upstream backend_servers {
ip_hash;
server 172.22.4.203:8080;
server 172.22.4.204:8080;
```
server 172.22.4.205:8080 down; # 手动标记停机
```bash
}

```
6. 最少连接（least_conn）
将请求转发给当前活动连接数最少的后端服务器。
特点：
适合请求处理时间长短不一的服务
自动平衡服务器负载

```bash
upstream backend_servers {
least_conn;
server 172.22.4.203:8080;
server 172.22.4.204:8080;
server 172.22.4.205:8080;
}

```
7. 后端服务器状态参数
参数 说明 示例
weight 权重，默认1 weight=5
max_fails 最大失败次数，默认1 max_fails=3
fail_timeout 失败超时时间，默认10s fail_timeout=30s
backup 备用服务器 backup
down 永久停机 down
max_conns 最大连接数限制 max_conns=1000

```bash
upstream backend_servers {
```
主服务器
```bash
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
```
备用服务器（主服务器全部故障时启用）
```bash
server 192.168.1.12:8080 backup;
```
永久停机的服务器
```bash
server 192.168.1.13:8080 down;
}

```
### 二十二、七层负载均衡
对应第七层应用层（HTTP/HTTPS）
1. 架构图
客户端
```bash
│
▼
┌─────────────────┐
```
│ Nginx 负载均衡器 │
```bash
│ 172.22.4.200 │
└─────────────────┘
│ │
▼ ▼
┌────────┐ ┌────────┐
│ Web01 │ │ Web02 │
│ .201 │ │ .202 │
└────────┘ └────────┘

```
145是负载均衡器，151和152是后端服务器的IP地址。


```bash
ps -ef | grep nginx
ll /etc/nginx/conf.d/

[145]
cat > /etc/nginx/conf.d/webshare.conf << 'EOB'
upstream webshare {
        server 192.168.20.151;
        server 192.168.20.152;
}
EOB
cat > /etc/nginx/conf.d/linuxnote.conf << 'EOB'
server {
    listen 80;
    server_name www.linuxnote.asia;

    location / {
        proxy_pass http://webshare;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
EOB
[151][152]
cat > /usr/local/nginx-1.24.0/conf/vhost/linuxnote.conf << 'EOB'
server {
    listen 80 default_server;
    root /usr/share/nginx/html;
    index index.html ;

    location / {
    }
}
EOB
nginx -s reload
cat > /etc/nginx/conf.d/linuxnote.conf << 'EOB'
server {
    listen 80 ;
    root /usr/share/nginx/html;
    index index.html ;

    location / {
    }
}
EOB
mkdir -p /usr/share/nginx/html
cat > /usr/share/nginx/html/index.html << 'EOB'
<meta charset="UTF-8">
<h1>这是151服务器页面</h1>
EOB

cat > /usr/share/nginx/html/index.html << 'EOB'
<meta charset="UTF-8">
<h1>这是152服务器页面</h1>
EOB

for i in {1..60};do curl http://192.168.20.145;done > file.txt
curl http://192.168.20.145

```
### 二十三、四层负载均衡
对应第四层传输层（TCP/UDP）
编译时添加 stream 模块
```bash
./configure \
--prefix=/usr/local/nginx \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module

vim /etc/nginx/nginx.conf
include conf.d/proxy.4.layer;

cat > /etc/nginx/conf.d/proxy.4.layer << 'EOB'
stream {
定义日志格式
log_format proxy '$remote_addr $remote_port - [$time_local] $status $protocol '
'"$upstream_addr" "$upstream_bytes_sent" "$upstream_connect_time"';
访问日志
access_log logs/stream_access.log proxy;
定义上游服务器组（ssh 22端口）
upstream backend_ssh {
server 192.168.20.151:22 weight=3;
}
MySQL 代理
server {
listen 2222;
proxy_pass backend_ssh;
proxy_connect_timeout 5s;
proxy_timeout 10s;
}
}
EOB

nginx -s reload
ss -ant

telnet 192.168.20.145 2222
dnf install -y telnet

### 二十四、防盗模块
mkdir -p /web/static
cat > /etc/nginx/conf.d/linuxnote1.conf << 'EOB'
server {
    listen 80 ;
    server_name www.linuxnote1.asia;
    root /web;
    index index.html ;
    
    location / {
        try_files $uri $uri/ /index.html;
    }
    location /static {
    }
}
EOB
systemctl restart nginx

cat > /web/index.html << 'EOB'
<meta charset="UTF-8">
<h1>这是145服务器页面</h1>
EOB

curl http://192.168.20.145
curl http://192.168.20.151
curl http://192.168.20.152

cat > /web/static/index.html << 'EOB'
<meta charset="UTF-8">
<h1>这是145服务器页面</h1>
EOB

cd /web/static && ll
http://192.168.20.151/static/aaa.png

cat >index.html<<'EOB'
<!DOCTYPE html>
<html>
<head>
<meta charset=“UTF-8”>
</head>
<body>
Hello! This is 145 Server <br/> <br/> <br/>
The following photo source 151 server: <br/>
<img src="http://www.linuxnote2.asia/static/aaa.png" alt="png is missing" >
<br/>
</body>
</html>
EOB

192.168.20.145 www.linuxnote1.asia
192.168.20.151 www.linuxnote2.asia
192.168.20.152 www.linuxnote3.asia

echo "192.168.20.145 www.linuxnote1.asia" >> /etc/hosts
echo "192.168.20.151 www.linuxnote2.asia" >> /etc/hosts
echo "192.168.20.152 www.linuxnote3.asia" >> /etc/hosts

windows
C:\Windows\System32\drivers\etc\hosts

http://www.linuxnote1.asia/static/index.html
http://www.linuxnote2.asia/static/aaa.png


cat >/etc/nginx/conf.d/linuxnote2.conf<<'EOB'
server {
    listen 80 default_server;
    server_name www.linuxnote2.asia;
    root /web;
    index index.html ;
    
    location ~* \.(js|css|jpg|jpeg|png|gif|webp|bmp|ico)$ {
        valid_referers none blocked server_names
        192.168.20.151
        *.linuxnote2.asia
        linuxnote2.asia;
        if ($invalid_referer) {
        return 403;
        }
    }
}   
EOB
nginx -t
systemctl restart nginx

www.linuxnote2.asia/static/index.html

```
### 二十五、限速模块

1. 限速的三种类型
类型 指令 作用
限制请求数 limit_req 控制每秒/每分钟的请求数量
限制连接数 limit_conn 控制同时并发连接数量
限制响应速度 limit_rate 控制下载速度

2. 限制请求数（limit_req）
基本原理 - 漏桶算法
完整配置示例
201服务器
```bash
┌─────────────┐
```
│ 请求流入 │
```bash
└──────┬──────┘
▼
┌─────────────┐
```
│ 漏桶 │ ← 请求队列
```bash
│ ┌───────┐ │
```
│ │ 排队 │ │
```bash
│ └───────┘ │
└──────┬──────┘
▼
┌─────────────┐
```
│ 请求流出 │ ← 按固定速率处理
```bash
└─────────────┘
```
- **水流入**：客户端发来的请求
- **漏桶**：服务器处理能力
- **水流速**：每秒处理的请求数
- **溢出**：超过处理能力的请求被拒绝

```bash
http {
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;

    upstream backend {
        server 192.168.20.151:80;
    }
}
grep limit_req_zone /etc/nginx/nginx.conf
cat >/etc/nginx/conf.d/linuxnote2_1.conf<<'EOB'
server {
    listen 80 ;
    server_name www.linuxnote2.asia;
    access_log /var/log/nginx/linuxnote2_access.log main;
    error_log /var/log/nginx/linuxnote2_error.log;

    location /api/ {
        limit_req zone=api_limit burst=10 nodelay;
        limit_req_status 503; # 超限返回状态码503

        proxy_pass http://backend;
    }
    error_page 503 = @rate_limit;
    location @rate_limit {
        default_type application/json;
        return 503 '{"code":503,"message":"请求过于频繁，请稍后再试"}';
    }
}
EOB
systemctl reload nginx

- `$binary_remote_addr`：按客户端IP限速
- `zone=mylimit:10m`：区域名称为mylimit，占用10M内存
- `rate=5r/s`：每秒允许10个请求

dnf -y install httpd-tools
ab -c 10 -n 100 http://www.linuxnote2.asia:8020/api/
www.linuxnote2.asia/api/

```
### 二十六、限制连接数
基础配置
定义连接数区域（放在 http 块中）
```bash
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;

server {
    listen 80;
    server_name example.com;

    limit_conn perip 6;
    limit_conn perserver 6000;
    limit_conn_status 503;
    location / {
        root /web;
    }
}

```
使用场景
场景 推荐配置
普通网站 每IP 10-20个连接
下载服务 每IP 3-5个连接，防止多线程下载
API服务 每IP 2-5个连接


### 二十七、限制响应速度
```bash
server {
    listen 80;
    server_name example.com;

    location / {
        limit_rate 1m;
    }

    location /download/ {
        limit_rate 500k;
        limit_rate_after 10m;
    }
}

122.152.231.125-zy
http://k1.zhynet.net/down.html

```
### 二十八、https接入
http不安全
https=ssl证书+http

```bash
https://euxs8.xetslk.com/sl/4lr9yg
```
腾讯云SSL证书签发及监控项目实战

证书
```bash
mkdir -p /etc/nginx/ssl
cd /etc/nginx/ssl

openssl req -x509 -nodes -days 365 \
-newkey rsa:2048 \
-keyout 2_https.key \
-out 2_https.crt \
-subj "/C=CN/ST=Shanghai/L=Shanghai/O=MengKe/OU=aaaa/CN=www.linuxnote2.asia"

cat > /etc/nginx/conf.d/linunote2_https.conf<<'EOB'
server {
    listen 443 ssl;
    server_name www.linuxnote2.asia;
    ssl_certificate /etc/nginx/ssl/2_https.crt;
    ssl_certificate_key /etc/nginx/ssl/2_https.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    location / {
        root /web;
        index index.html;
    }
}
EOB
systemctl reload nginx

https://www.linuxnote2.asia

```
### 二十九、Nginx Rewrite
什么是 Rewrite？
●URL 重写：将客户端请求的URL进行转换
●作用：URL标准化、SEO优化、动态URL静态化、请求转发等
●实现：基于正则表达式匹配和替换
●模块名：ngx_http_rewrite_module

指令 作用域 功能说明
rewrite server, location, if URL重写
return server, location, if 返回状态码和内容
set server, location, if 设置变量
```bash
if server, location 条件判断
```
break server, location, if 终止 rewrite 处理

Rewrite 规则编写
基础语法示例

### 三十、正则表达式常用符号
符号 说明 示例
^ 匹配字符串开始 ^/api/
```bash
$ 匹配字符串结束 .html$
```
符号 说明 示例
. 匹配任意字符（除换行） ^/user/.+$
* 前一个字符0次或多次 .*
+ 前一个字符1次或多次 .+
? 前一个字符0次或1次 index.html?
```bash
() 分组捕获 ^/([0-9]+)/

### 三十一、伪静态页面
cat > /web/index.php<<'EOB'
<?php
echo "<h1>欢迎访问伪静态Demo</h1>";
echo "<p><a href='/aaa/123.html'>查看商品123</a></p>";
echo "<p><a href='/bbb/bbc.html'>电子分类</a></p>";
echo "<p><a href='/ccc/123.html'>搜索apple</a></p>";
?>
EOB

mkdir -p /web/aaa /web/bbb /web/ccc
cat > /web/aaa.php<<'EOB'
<?php
$id = $_GET['id'] ?? '未知';
echo "<h1>商品页面</h1>";
echo "<p>商品ID: $id</p>";
echo "<p>访问的URL: " . $_SERVER['REQUEST_URI'] . "</p>";
echo "<p>实际执行的文件: /aaa/123.php</p>";
?>
EOB

cat > /web/bbb.php<<'EOB'
<?php
$name = $_GET['name'] ?? '未知';
$id = $_GET['id'] ?? '未知';
echo "<h1>Get接收的参数介绍</h1>";
echo "<p>访问的URL: " . $_SERVER['REQUEST_URI'] . "</p>";
echo "<p>接收的参数id: $id</p>";

?>
EOB

cat > /web/ccc.php<<'EOB'
<?php
// ========== 1. 接收单个参数 ==========
$id = $_GET['id'] ?? '未知';
$name = $_GET['name'] ?? '未知';
$page = $_GET['page'] ?? 1;

// ========== 2. 获取请求信息 ==========
$request_uri = $_SERVER['REQUEST_URI'];      // 完整 URL
$client_ip = $_SERVER['REMOTE_ADDR'];        // 客户端 IP
$host = $_SERVER['HTTP_HOST'];               // 主机名

// ========== 3. 判断参数是否存在 ==========
if (isset($_GET['id'])) {
    echo "有 id 参数";
}
echo "<p>接收的参数id: $id</p> \n<br>";
echo "<p>接收的参数name: $name</p> \n<br>";
echo "<p>接收的参数page: $page</p> \n<br>";
echo "<p>接收的参数host: $host</p> \n<br>";
echo "<p>接收的参数client_ip: $client_ip</p> \n<br>";
echo "<p>接收的参数request_uri: $request_uri</p> \n<br>";

?>

EOB

cat > /etc/nginx/conf.d/rewrite.conf<<'EOB'
server {
    listen 8080;
    server_name www.linuxnote1.asia;
    root /web;
    index index.php index.html;
    
    rewrite ^/aaa/([0-9]+)\.html$ /aaa.php?id=$1 last;
    rewrite ^/bbb/([a-z]+)\.html$ /bbb.php?id=$1 last;
    rewrite ^/ccc/([0-9]+)\.html$ /ccc.php?id=$1&name=$1&page=1 last;

    location / {
        rewrite ^ /index.php last;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php-fpm/www.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    rewrite_log on;
    error_log /var/log/nginx/rewrite.log notice;
}
EOB

systemctl reload nginx
http://www.linuxnote1.asia:8080/aaa/123.html

curl http://www.linuxnote1.asia:8080/aaa/123.html
curl http://www.linuxnote1.asia:8080/bbb/bbc.html
curl http://www.linuxnote1.asia:8080/ccc/123.html



tail -n 20 /var/log/nginx/rewrite.log

$id = $_GET['id']
$name = $_GET['name']
$client_ip = $_SERVER['REMOTE_ADDR']
$host = $_SERVER['HTTP_HOST']
$request_uri = $_SERVER['REQUEST_URI']

### 三十二、http跳转https
server {
• listen 80;
• server_name qianshan.cc;
• return 301 https://$server_name$request_uri;
}

### 三十三、日志格式与切割

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                                '$status $body_bytes_sent "$http_referer" '
                                '"$http_user_agent" "$http_x_forwarded_for"';

```
字段 功能描述
```bash
$remote_addr #记录客户端IP地址
$remote_user #记录客户端用户名
$time_local
#记录通用的本地时间，有些用$time_iso8601，记录ISO8601标准格式下的本地时
```
间
```bash
$request #记录请求的方法以及请求的http协议
$status #记录请求状态码(用于定位错误信息)
$body_bytes_sent #发送给客户端的资源字节数，不包括响应头的大小
$http_referer #记录从哪个页面链接访问过来的
$http_user_agent #记录客户端浏览器相关信息
$http_x_forwarded_for #记录客户端IP地址

### 三十四、自定义日志
log_format log_json '{"@timestamp": "$time_local", '
                    '"remote_addr": "$remote_addr", '
                    '"referer": "$http_referer", '
                    '"request": "$request", '
                    '"status": $status, '
                    '"bytes": $body_bytes_sent, '
                    '"agent": "$http_user_agent", '
                    '"x_forwarded": "$http_x_forwarded_for", '
                    '"up_addr": "$upstream_addr",'
                    '"up_host": "$upstream_http_host",'
                    '"up_resp_time": "$upstream_response_time",'
                    '"request_time": "$request_time"'
                    ' }';
```
主配置文件里
```bash
access_log  /var/log/nginx/access.log log_json;

more /usr/local/nginx-1.24.0/conf/vhosts/https.conf
server {
    listen 80;
    server_name qianshan.cc www.qianshan.cc;
    return 301 https://$server_name$request_uri;
}
server {
    listen 443 ssl;
    server_name qianshan.cc www.qianshan.cc;

    ssl_certificate /etc/nginx/ssl/qianshan.crt;
    ssl_certificate_key /etc/nginx/ssl/qianshan.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    access_log logs/qianshan.cc.log log_json;
    location / {
        root /data/www/;
        index index.html;
    }
}

### 三十五、日志切割
cat >/etc/logrotate.d/nginx<<'EOB'
/usr/local/nginx-1.24.0/logs/*.log
{
    daily
    rotate 15
    missingok
    compress
    delaycompress
    notifempty
    postrotate
        if [ -f /usr/local/nginx-1.24.0/logs/nginx.pid ]; then
            kill -USR1 `cat /usr/local/nginx-1.24.0/logs/nginx.pid`
        fi
endscript
}
EOB

/etc/logrotate.d/nginx,文件中同行不能有中文注释，会报错。


logrotate -vf /etc/logrotate.d/nginx

#crontab –e
59 23 * * * /usr/sbin/logrotate -vf /etc/logrotate.d/nginx #每天晚上23点59分执行

```
### 三十六、性能优化
配置管理策略
1. 主配置文件最小化： nginx.conf 只包含全局配置
2. 站点配置分离：每个站点创建独立的 .conf 文件在 conf.d/ 目录

```bash
worker_rlimit_nofile 65535; 
events {
    worker_connections 4096; 
    use epoll; 
    multi_accept on;
}
http {
    # 优化缓冲区
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 8m;
    large_client_header_buffers 4 8k;
    # 超时设置
    client_body_timeout 12;
    client_header_timeout 12;
    send_timeout 10;
    # 压缩优化
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_types text/plain text/css application/json application/javascript;
}

```
安全加固
隐藏版本信息
```bash
server_tokens off;
```
安全头设置
```bash
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
```
限制请求方法
```bash
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
```
禁止特定文件访问
```bash
location ~ /\.(ht|git|svn) {
deny all;
return 404;
}


```
CPU亲和性
自动绑定到CPU核心
```bash
worker_processes auto;
worker_cpu_affinity auto;


```
连接和请求
打开文件缓存
```bash
open_file_cache max=10000 inactive=60s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
```
启用sendfile（高效文件传输）
```bash
sendfile on;
```
tcp_nopush on; # 与sendfile配合，优化数据包发送
tcp_nodelay on; # 禁用Nagle算法
连接复用
```bash
keepalive_timeout 65;
```
keepalive_requests 1000; # 单个keepalive连接最大请求数
reset_timedout_connection on; # 释放超时连接的内存

静态文件缓存
```bash
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
```
expires 30d; # 设置过期时间
```bash
add_header Cache-Control "public, immutable";

### 三十七、标准优化模板

```bash
cat >nginx.conf<<'EOB'
运行用户
user nginx;
工作进程数（自动匹配CPU核心数）
worker_processes auto;
CPU亲和性（自动绑定）
worker_cpu_affinity auto;
文件描述符限制
worker_rlimit_nofile 65535;
错误日志
error_log /var/log/nginx/error.log warn;
进程ID
pid /run/nginx.pid;
Events模块
events {
    worker_connections 4096;
    use epoll;
    multi_accept on; 
}
HTTP模块
http {
基础配置
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    # 隐藏版本信息
    server_tokens off;
    # 日志格式
    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 /var/log/nginx/access.log main;
    # 文件传输优化
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    # 连接复用
    keepalive_timeout 65;
    keepalive_requests 1000;
    reset_timedout_connection on;
    # 优化缓冲区
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    client_max_body_size 8m;
    large_client_header_buffers 4 8k;
    # 超时设置
    client_body_timeout 12;
    client_header_timeout 12;
    send_timeout 10;
    # 压缩优化
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied any;
    gzip_types text/plain text/css application/json application/javascript;
    # 打开文件缓存
    open_file_cache max=10000 inactive=60s;
    open_file_cache_valid 60s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;
    # 安全头设置
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    # 默认服务器配置
    server {
        listen 80;
        server_name localhost;
        # 根目录
        root /usr/share/nginx/html;
        index index.html index.htm;
        # 限制请求方法
        if ($request_method !~ ^(GET|HEAD|POST)$ ) {
            return 405;
        }
        # 禁止特定文件访问
        location ~ /\.(ht|git|svn) {
            deny all;
            return 404;
        }
        # 静态文件缓存
        location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 30d;
            add_header Cache-Control "public, immutable";
        }
        # 错误页面
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/share/nginx/html;
        }
    }
    # 包含其他站点配置
    include /etc/nginx/conf.d/*.conf;
}
EOB

```


### 三十八、nginx
```bash
dnf module list nginx
dnf module reset nginx -y
dnf module enable nginx:1.24
dnf -y install nginx

```
### 三十九、反向代理
```bash
proxy_pass http://192.168.20.146: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;

```
### 四十、负载均衡
```bash
upstream aaa_servers {server 111;222;333}
server {proxy_pass aaa_servers}

```
### 四十一、https配置
```bash
listen 443 ssl;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;

```
### 四十二、虚拟主机
```bash
/etc/hosts

```
### 四十三、动静分离
```bash
/static/{alias /aaa; autoindex on;}

```
### 四十四、linux机器部两个网站实验

```bash
wget https://gitee.com/Discuz/DiscuzX/attach_files/2714621/download -O Discuz_X3.4_SC_UTF8.zip

dnf install php-mysqlnd php-xml php-json -y

grep -E '^listen|^user|^group' /etc/php-fpm.d/www.conf

server {
    listen  80 default_server ;
    server_name www.bbs.com.cn ;
    root  /web/upload ;
    index index.php index.html ;

    location / { 
        index index.php ;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php-fpm/www.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

}

```

### 四十五、tcpdump
```bash
dnf install -y tcpdump
dnf install -y telnet

tcpdump -i ens160 port 80

telnet 192.168.20.146 80

```

### 排错三板斧

### 网络层面

```bash
ping 192.168.20.145
telnet 192.168.20.145 80
iptables -A INPUT -s 192.168.20.135 -j DROP
service iptables save
iptables -nL
iptables -nL --line-numbers

```
### 四十六、iptables
```bash
iptables -D INPUT 1 && iptables -nL INPUT --line-number

iptables -nL INPUT --line-number && awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c

yum install httpd-tools -y
ab -c 100 -n 1000 -t 30 http://192.168.20.145/

dnf install git make gcc -y
git clone https://github.com/wg/wrk.git
cd wrk
make
cp wrk /usr/local/bin/
wrk --version
wrk -t4 -c100 -d30 http://192.168.20.145/
```

### 系统层面

```bash
watch -n 1 "awk '{print \$1}' /var/log/nginx/access.log | sort | uniq -c"

```

```bash
worker_cpu_affinity auto;   轮询
worker_connections 65535; 	最大连接数
use epoll;					网络模型
worker_rlimit_nofile 65535;	文件描述服务
```
```bash
location ~* \.(jpg|png|css) { expires 30d; }

gzip on;
gzip_comp_level 5;
gzip_types text/plain text/css application/json;
sendfile            on;
tcp_nopush          on;
erver_tokens off;

```