Nginx 安装配置 与核心配置与变量

1.1 Nginx 概述
1.1.1 Nginx 介绍

Nginx(engine X)由Igor Sysoev于2002年开发,分为社区版和商业版(nginx plus)。2019年3月11日,F5 Networks以6.7亿美元的价格收购了Nginx。Nginx是一款免费的、开源的、高性能HTTP和反向代理服务器,同时支持邮件代理服务器以及TCP/UDP代理服务器。它被设计用于解决C10K问题(10,000个并发连接),并且广泛应用于高流量网站中。

Nginx 官网:http://nginx.org

Nginx的其他二次发行版包括:

  • Tengine:由淘宝网发起的Web服务器项目,基于Nginx进行优化,添加了许多高级功能和特性,特别适合高访问量的网站。Tengine已经在大型网站如淘宝网、天猫商城中得到了充分检验。官网:http://tengine.taobao.org/

  • OpenResty:由章亦春团队开发的基于Nginx与Lua语言的高性能Web平台,官网:http://openresty.org/cn/

1.1.2 Nginx 功能介绍
  • 静态资源服务器:如html、图片、js、css、txt等。
  • 反向代理:支持HTTP/HTTPS协议。
  • 动态资源请求反向代理:结合FastCGI/uWSGI/SCGI等协议。
  • TCP/UDP协议转发:支持tcp/udp协议的请求转发。
  • 邮件代理:支持IMAP4/POP3协议的反向代理。
1.1.3 Nginx 基础特性
  • 模块化设计:具备良好的扩展性。
  • 高可靠性:支持热部署,不停机更新配置文件、升级版本和更换日志文件。
  • 低内存消耗:在10,000个keep-alive连接下,仅需2.5MB内存。
  • 事件驱动:支持AIO、mmap、sendfile等机制。
1.2 Nginx 架构和进程
1.2.1 Nginx 进程结构

Nginx采用多进程架构,由一个Master主进程和多个Worker工作进程组成。

  • 主进程(Master Process):负责接收外部操作信号,转发给Worker进程,并监控Worker进程的运行状态。它还负责读取Nginx配置文件,建立、绑定和关闭socket连接,管理和生成工作进程,并实现不中断服务的平滑升级和重启。

  • 工作进程(Worker Process):负责处理所有网络请求。每个Worker进程都是独立且平等的,通常设置为CPU核心数,以充分利用资源并减少上下文切换的损耗。Worker进程处理客户请求,将其送入各个功能模块,执行I/O调用,与后端服务器通信,并响应客户请求。

1.2.2 Nginx 进程间通信

Nginx的主进程与工作进程之间通过管道通信。主进程生成工作进程,并在启动时为每个进程建立单向管道,用于发送指令。Worker进程之间也可以通过共享内存或管道通信,但由于它们是隔离的,因此需要通过主进程来实现状态信息的共享。

1.2.3 Nginx 启动和 HTTP 连接建立

Nginx启动时,Master进程加载配置文件并初始化监听的socket。然后,Master进程通过fork出多个Worker进程,Worker进程之间竞争新的连接,成功的Worker进程通过三次握手建立Socket连接并处理请求。

1.3 Nginx 模块介绍

Nginx支持多种模块,模块化设计使其功能可以灵活扩展。

  • 核心模块:提供Nginx的基本运行功能,如错误日志记录、配置文件解析、事件驱动机制和进程管理。
  • 标准HTTP模块:处理HTTP协议的解析和管理。
  • 可选HTTP模块:扩展HTTP功能,如多媒体传输、GeoIP请求解析、网络传输压缩和SSL支持。
  • 邮件服务模块:支持POP3、IMAP和SMTP协议的邮件服务。
  • Stream服务模块:用于TCP协议代理的实现。
  • 第三方模块:用于扩展Nginx功能,如Json支持和Lua支持。
1.4 Nginx 安装
1.4.1 Nginx 版本和安装方式

Nginx主要有三个版本:

  • Mainline version:主要开发版本,一般为奇数版本号,如1.19。
  • Stable version:最新的稳定版本,一般为偶数版本号,如1.20。
  • Legacy versions:旧的稳定版本,如1.18。

Nginx可以通过yum或源码编译安装,推荐使用源码编译方式安装。虽然yum安装较为方便,但版本通常较旧,而源码编译可以更灵活地自定义安装路径和功能,以满足特定业务需求。


Nginx 编译安装

1. 安装所需依赖包
dnf install gcc pcre-devel zlib-devel openssl-devel -y

首先,通过 dnf 包管理器安装 Nginx 编译所需的依赖库。这些依赖包括 gcc 编译器、pcre-devel(Perl Compatible Regular Expressions 开发库)、zlib-devel(压缩库开发文件)和 openssl-devel(OpenSSL 开发文件)。

2. 创建目录并解压 Nginx 源码包
mkdir /nginx

创建一个名为 /nginx 的目录,用于存放 Nginx 源码包。将 nginx-1.24.0.tar.gz 文件放置在该目录中,并执行解压命令:

tar zxf nginx-1.24.0.tar.gz
3. 创建 Nginx 运行用户
useradd -s /sbin/nologin -M nginx

通过 useradd 命令创建一个名为 nginx 的系统用户。该用户将用于运行 Nginx,并且不允许登录系统(-s /sbin/nologin)且不创建家目录(-M)。

4. 进入 Nginx 源码目录
cd nginx-1.24.0/

进入解压后的 nginx-1.24.0 目录,准备进行配置和编译。

5. 配置 Nginx
./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

使用 ./configure 脚本配置 Nginx 安装路径和功能模块:

  • --prefix=/usr/local/nginx:指定 Nginx 安装路径。

  • --user=nginx--group=nginx:指定 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:启用正则表达式支持。

  • --with-stream:启用 TCP 反向代理支持。

  • `–wi

  • --with-stream_realip_module:启用 TCP 透传 IP 功能。

6. 编译并安装 Nginx
make && make install

使用 make 命令编译源码并安装 Nginx 到指定的目录。

在这里插入图片描述

验证版本及编译参数

1. 配置环境变量
vim ~/.bash_profile

编辑 ~/.bash_profile 文件,添加 Nginx 二进制文件的路径到系统环境变量中:

export PATH=$PATH:/usr/local/nginx/sbin

保存并退出后,执行以下命令使配置生效:

source ~/.bash_profile
2. 验证 Nginx 版本及编译参数
nginx -V

使用 nginx -V 命令查看 Nginx 的版本号和编译时启用的模块。输出如下:
在这里插入图片描述

此命令验证了 Nginx 是否成功安装以及是否正确编译了所需模块。

3. 创建 Nginx 启动文件
vim /lib/systemd/system/nginx.service

创建或编辑 Nginx 的 systemd 服务文件 /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

关键部分解释如下:

  • [Unit] 部分定义了服务的描述、依赖和启动顺序。
  • [Service] 部分定义了服务的启动类型、启动前的检查命令、启动命令、重载和停止命令。
  • [Install] 部分定义了服务在系统中的安装模式,通常为 multi-user.target

保存并退出编辑器后,执行以下命令重新加载 systemd 配置:

systemctl daemon-reload
4. 启动 Nginx 服务
systemctl start nginx

启动 Nginx 服务,检查服务状态以确保其成功运行:

systemctl status nginx

正常情况下,输出将显示 Nginx 服务已启动并运行,且各个进程状态正常。
在这里插入图片描述

平滑升级

将旧Nginx二进制文件换成新Nginx程序文件(注意先备份)
向master进程发送USR2信号
master进程修改pid文件名加上后缀.oldbin,成为nginx.pid.oldbin
master进程用新Nginx文件启动新master进程成为旧master的子进程,系统中将有新旧两个Nginx主
进程共同提供Web服务,当前新的请求仍然由旧Nginx的worker进程进行处理,将新生成的master进
程的PID存放至新生成的pid文件nginx.pid
向旧的Nginx服务进程发送WINCH信号,使旧的Nginx worker进程平滑停止
向旧master进程发送QUIT信号,关闭老master,并删除Nginx.pid.oldbin文件
如果发现升级有问题,可以回滚∶向老master发送HUP,向新master发送QUIT

1. 解压源码包

[root@Nginx ~]# tar zxf nginx-1.26.1.tar.gz 

功能:将 nginx-1.26.1.tar.gz 文件解压到当前目录。tar 命令用于解压归档文件,zxf 参数表示使用 gzip 解压并提取文件。

2. 进入 Nginx 源码目录

[root@Nginx ~]# cd nginx-1.26.1/

功能:进入解压后的 Nginx 源码目录,以便进行配置和编译。

3. 解压额外的模块

[root@Nginx ~]# tar zxf echo-nginx-module-0.63.tar.gz 

功能:解压 echo-nginx-module-0.63.tar.gz 文件,该文件包含额外的 Nginx 模块。

4. 配置 Nginx

[root@Nginx nginx-1.26.1]# ./configure --prefix=/usr/local/nginx --add-module=/root/echo-nginx-module-0.63 --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

功能:配置 Nginx 编译选项。

  • --prefix=/usr/local/nginx:指定 Nginx 安装路径。
  • --add-module=/root/echo-nginx-module-0.63:添加第三方模块。
  • --user=nginx --group=nginx:设置运行 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:启用 Perl 兼容正则表达式库。
  • --with-stream:启用流模块。
  • --with-stream_ssl_module:启用流 SSL 支持。
  • --with-stream_realip_module:启用流真实 IP 支持。

5. 编译 Nginx

[root@Nginx nginx-1.26.1]# make

功能:编译 Nginx 源码,生成可执行文件。

6. 查看编译后的文件信息

[root@Nginx nginx-1.26.1]# ll objs/nginx /usr/local/nginx/sbin/nginx
-rwxr-xr-x 1 root root 6177320 Aug 20 15:37 objs/nginx
-rwxr-xr-x 1 root root 5679504 Aug 20 15:00 /usr/local/nginx/sbin/nginx

功能:列出 objs/nginx/usr/local/nginx/sbin/nginx 文件的信息,确认编译成功并显示文件大小和时间戳。

7. 替换 Nginx 可执行文件

[root@Nginx sbin]# cp nginx nginx.1
[root@Nginx sbin]# \cp -f /root/nginx-1.26.1/objs/nginx /usr/local/nginx/sbin

功能:备份当前 Nginx 可执行文件 nginxnginx.1,然后将新编译的 nginx 文件复制到 /usr/local/nginx/sbin 目录中,替换旧的可执行文件。

8. 测试 Nginx 配置文件

[root@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

功能:测试 Nginx 配置文件是否正确,确保配置语法无误。

9. 重新加载 Nginx 配置

[root@Nginx sbin]# kill -USR2 36606
[root@Nginx sbin]# ps aux | grep nginx
root       36606  0.0  0.1   9840  2564 ?        Ss   15:08   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      36607  0.0  0.2  13700  4852 ?        S    15:08   0:00 nginx: worker process
root       36608  0.0  0.4 235988  8876 pts/0    T    15:08   0:00 systemctl status nginx
root       42580  0.0  0.3   9876  6084 ?        S    15:50   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      42581  0.0  0.2  13736  4764 ?        S    15:50   0:00 nginx: worker process
root       42583  0.0  0.1 221668  2292 pts/0    S+   15:50   0:00 grep --color=auto nginx
[root@Nginx sbin]# kill -WINCH 36606
[root@Nginx sbin]# kill -QUIT 36606

功能

  • kill -USR2 36606:发送 USR2 信号给旧的 Nginx 主进程,触发其重新加载配置。
  • ps aux | grep nginx:检查 Nginx 进程的状态。
  • kill -WINCH 36606:发送 WINCH 信号给旧的主进程,告诉它将工作进程切换到新的主进程。
  • kill -QUIT 36606:发送 QUIT 信号给旧的主进程,平稳退出。

10. 验证 Nginx 是否正常运行

[root@Nginx sbin]# curl -I localhost
HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Tue, 20 Aug 2024 07:51:54 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Tue, 20 Aug 2024 07:00:22 GMT
Connection: keep-alive
ETag: "66c43f06-267"
Accept-Ranges: bytes

功能:使用 curl 工具向 localhost 发送 HTTP 请求,检查 Nginx 是否正确响应,确保其正常运行并返回 HTTP 200 状态码。

在这里插入图片描述

回滚

Nginx 服务回滚与测试

1. 停止 Nginx 服务
[root@Nginx sbin]# pkill nginx
  • 使用 pkill nginx 命令停止所有 Nginx 进程。
2. 备份并替换 Nginx 可执行文件
[root@Nginx sbin]# cp nginx nginx.1
[root@Nginx sbin]# ls nginx nginx.1 nginx.2
nginx  nginx.1  nginx.2
  • 创建了 nginx.1 文件作为 nginx 文件的备份。
  • 列出当前目录下的 nginxnginx.1nginx.2 文件。
[root@Nginx sbin]# cp /usr/local/nginx/sbin/nginx.1 /usr/local/nginx/sbin/nginx
cp: overwrite '/usr/local/nginx/sbin/nginx'? y
  • 使用 cp 命令将 nginx.1 文件复制为 nginx 文件,并确认覆盖已存在的 nginx 文件。
3. 检查 Nginx 进程
[root@Nginx sbin]# ps aux | grep nginx
[root@Nginx sbin]# ps aux | grep nginx
root       36608  0.0  0.4 235988  8876 pts/0    T    15:08   0:00 systemctl status nginx
root       42628  0.0  0.1 221668  2352 pts/0    S+   16:05   0:00 grep --color=auto nginx

  • 使用 ps aux | grep nginx 命令检查当前运行的 Nginx 进程。
4. 启动 Nginx 服务
[root@Nginx sbin]# systemctl start nginx
[root@Nginx sbin]# systemctl status nginx
  • 使用 systemctl start nginx 命令启动 Nginx 服务。
  • 使用 systemctl status nginx 命令检查 Nginx 服务的状态。
5. 检查 Nginx 服务状态输出
● nginx.service - The NGINX HTTP and reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
     Active: active (running) since Tue 2024-08-20 16:06:27 CST; 5s ago
    Process: 42632 ExecStartPre=/usr/local/nginx/sbin/nginx -t (code=exited, status=0/SUCCESS)
    Process: 42633 ExecStart=/usr/local/nginx/sbin/nginx (code=exited, status=0/SUCCESS)
   Main PID: 42634 (nginx)
      Tasks: 2 (limit: 10800)
     Memory: 3.1M
        CPU: 12ms
     CGroup: /system.slice/nginx.service
             ├─42634 "nginx: master process /usr/local/nginx/sbin/nginx"
             └─42635 "nginx: worker process"

Aug 20 16:06:27 Nginx.tinminglee.org systemd[1]: Starting The NGINX HTTP and reverse proxy server...
Aug 20 16:06:27 Nginx.tinminglee.org nginx[42632]: nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
Aug 20 16:06:27 Nginx.tinminglee.org nginx[42632]: nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
Aug 20 16:06:27 Nginx.tinminglee.org systemd[1]: Started The NGINX HTTP and reverse proxy server.
  • 显示了 Nginx 服务的状态,确认服务已启动并运行。
  • 确认了 Nginx 配置文件的语法正确,并且测试成功。
  • 显示了 Nginx 的主进程(PID 42634)和工作者进程(PID 42635)。
6. 测试 Nginx 服务
[root@Nginx sbin]# curl -I localhost
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Tue, 20 Aug 2024 08:06:54 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Tue, 20 Aug 2024 07:00:22 GMT
Connection: keep-alive
ETag: "66c43f06-267"
Accept-Ranges: bytes

在这里插入图片描述

一.Nginx 配置文件说明

配置文件组成部分
  • 主配置文件nginx.conf,包含了Nginx的基本配置。
  • 子配置文件:通过include指令从主配置文件中引入,通常位于conf.d/目录下的.conf文件。
  • FastCGI, uWSGI, SCGI:这些协议相关的配置文件,用于处理动态内容。
  • MIME 类型文件mime.types,定义了文件扩展名与其对应的MIME类型。
配置文件格式说明
  • 结构划分:Nginx主配置文件分为四个主要部分:全局配置、事件配置、HTTP配置、邮件配置。
  • 指令与指令块:配置文件由多个指令及其所属的指令块组成。
  • 指令格式:每条指令以;结束,指令与值之间以空格分隔。
  • 指令块:使用{ }将多条指令组织在一起,可以嵌套。
  • include语句:允许合并多个配置文件,增强配置的可维护性。
  • 注释:使用#添加注释。
  • 变量:使用$引用变量。

根据提供的信息,这里概述 Nginx 主配置文件中配置指令的基本用法和一些注意事项。Nginx 是一款广泛使用的高性能 HTTP 和反向代理 Web 服务器。配置文件通常位于 /etc/nginx/nginx.conf 或类似路径下,用于定义 Nginx 的行为和设置。

Nginx 配置指令基本格式

配置指令的基本语法为:

directive value [value2 ...];

其中 directive 是配置指令名称,value 及其后的值是该指令的具体参数。所有指令都必须以分号 ; 结束。

注意事项
  1. 指令结束标志

    • 所有指令必须以分号结尾。
  2. 配置变量

    • 支持使用配置变量。
    • 内建变量:由 Nginx 模块引入,可以直接在配置文件中引用。
    • 自定义变量:通过 set 指令定义,格式为 set variable_name value;
    • 引用变量:使用 $ 符号加上变量名,如 $variable_name

主配置文件结构分为四个主要部分:

  1. Main Block (主配置段): 这是全局配置段,其设置对 HTTP 和 Mail 模块均有效。

    # 全局配置,对 HTTP 和 Mail 均适用
    ...
    
  2. Event Block (事件驱动相关的配置):

    event {
        ...
    }
    
  3. HTTP Block (HTTP/HTTPS 协议相关配置段):

    http {
        ...
    }
    
  4. Additional Blocks (默认配置中未包含的两个额外块):

    • Mail Block (Mail 协议相关配置段):
      mail {
          ...
      }
      
    • Stream Block (Stream 服务器相关配置段):
      stream {
          ...
      }
      

默认的nginx.conf 配置文件格式说明

默认的 nginx.conf 配置文件格式说明如下:

# 全局配置段,对全局生效,主要设置 Nginx 的启动用户/组,启动的工作进程数量,工作模式,
# Nginx 的 PID 路径,日志路径等。
user nginx nginx;
worker_processes 1; # 启动的工作进程数量

# 事件驱动相关的配置
events {
    worker_connections 1024; # 设置单个 Nginx 工作进程可以接受的最大并发连接数
    # 其他事件驱动相关的配置项
}

# HTTP 块是 Nginx 服务器配置中的重要部分,缓存、代理和日志格式定义等绝大多数功能和第三方模块都可以在这里设置。
http {
    include mime.types; # 包含 MIME 类型定义文件
    default_type application/octet-stream; # 默认 MIME 类型

    # 发送文件时启用 sendfile,以提高文件传输速度
    sendfile on;

    # 长连接超时时间,单位是秒
    keepalive_timeout 65;

    # 定义一个或多个 server 块,每个 server 块可以包含多个 location 块
    server {
        listen 80; # 配置 server 监听的端口
        # 服务器名称
        server_name example.com;

        # 在此 server 块内部可以定义更多的 location 块来处理不同 URL 的请求
        location / {
            root /usr/share/nginx/html; # 根目录
            index index.html index.htm; # 默认索引文件
        }

        # 其他 location 块
    }

    # 其他 server 块
}

# 其他配置块,例如 mail 或 stream,如果需要的话
主要配置指令分类:
正常运行必备的配置
  • user: 指定 Nginx 进程运行的用户和组。
  • worker_processes: 设置工作进程的数量。
  • pid: 指定 Nginx 的 PID 文件存放位置。
  • error_log: 指定错误日志文件的位置。
优化性能相关的配置
  • worker_connections: 每个工作进程可以接受的最大并发连接数。
  • sendfile: 控制是否使用 sendfile 系统调用来传输文件,以提高传输效率。
  • keepalive_timeout: 设置长连接的超时时间。
  • open_file_cache: 缓存打开的文件句柄,减少系统开销。
用于调试及定位问题相关的配置
  • debug_connection: 设置调试信息输出。
  • debug_points: 在特定条件下触发调试点。
  • log_format: 自定义日志格式,便于分析问题。
事件驱动相关的配置
  • use: 选择事件模型(例如 epoll, kqueue 等)。
  • multi_accept: 控制是否允许多个连接同时被接受。
  • accept_mutex: 控制在多线程环境下是否对连接接受进行序列化。

二 全局配置段

全局配置段 (Main) 是 Nginx 配置文件中的一个重要部分,它包含了确保 Nginx 正常运行所必需的基本配置项。以下是全局配置段中常见的配置指令分类及其说明:

正常运行必备的配置
  • user: 指定启动 Nginx 工作进程的用户和组。这有助于控制 Nginx 的权限级别,通常设置为非特权用户以增加安全性。

    user nginx nginx;
    
  • worker_processes: 设置启动的工作进程数量。通常推荐设置为服务器的 CPU 核心数,或者使用 auto 让 Nginx 自动检测并设置。

    worker_processes 1; # 或者 worker_processes auto;
    
  • worker_cpu_affinity: 将 Nginx 工作进程绑定到特定的 CPU 核心。这有助于减少进程在不同核心间的上下文切换,从而提高性能。默认情况下,Nginx 不会将进程绑定到特定的核心。

    worker_cpu_affinity 00000001 00000010 00000100 00001000 | auto;
    
优化性能相关的配置
  • worker_connections: 每个工作进程可以处理的最大并发连接数。对于 Web 服务器,最大并发数为 worker_connections * worker_processes;对于反向代理服务器,最大并发数大约为 (worker_connections * worker_processes) / 2
    events {
        worker_connections 1024;
    }
    
用于调试及定位问题相关的配置
  • error_log: 设置错误日志的路径和级别,这对于调试问题非常有用。

    error_log /var/log/nginx/error.log warn;
    
  • debug_connection: 开启调试模式,用于诊断连接问题。

    debug_connection on;
    
  • debug_points: 在特定条件下触发调试点,帮助诊断问题。

    debug_points stop;
    
事件驱动相关的配置
  • events: 包含所有与事件处理相关的配置,例如使用的事件驱动模型、最大并发连接数等。
    events {
        use epoll; # 选择事件驱动模型
        multi_accept on; # 允许多个连接同时被接受
        accept_mutex on; # 控制多线程环境下连接接受的序列化
        worker_connections 1024;
    }
    

web站点

使用以下命令打开并编辑Nginx的主配置文件nginx.conf

[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf

确保主配置文件中包含对子配置文件的引用,通常可以在文件末尾添加以下行:

include /usr/local/nginx/conf.d/*.conf;

在这里插入图片描述

设置地址解析
在这里插入图片描述

创建用于存放虚拟主机配置的目录:

[root@Nginx ~]# mkdir -p /usr/local/nginx/conf.d

接下来,创建并编辑虚拟主机配置文件vhost.conf

[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

在文件中添加如下配置,以创建一个监听80端口并响应www.timinglee.org域名的虚拟主机:

server {
    listen 80;
    server_name www.timinglee.org;
    
    location / {
        root /data/web/html;
    }
}

若需要自定义Vim编辑器的配置,可以编辑用户的.vimrc文件:

[root@Nginx ~]# vim ~/.vimrc

若有需要,可再次打开虚拟主机配置文件进行编辑:

[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

执行以下命令,创建站点目录并添加测试文件index.html

[root@Nginx ~]# mkdir -p /data/web/html
[root@Nginx ~]# echo www.timinglee.org > /data/web/html/index.html

测试通过后,使用以下命令重载Nginx配置:

[root@Nginx ~]# nginx -s reload

测试
在浏览器中输入 http://www.timinglee.org/
在这里插入图片描述

实验1 nginx下的用户认证

步骤1:创建.htpasswd文件并添加用户

首先,使用htpasswd命令创建一个.htpasswd文件,并添加第一个用户admin。以下命令将会创建一个新文件并为用户admin设置密码:

[root@Nginx sbin]# htpasswd -cm /usr/local/nginx/.htpasswd admin
New password: 
Re-type new password: 
Adding password for user admin
步骤2:验证用户信息

使用cat命令查看.htpasswd文件,验证用户admin的密码信息是否正确添加:

[root@Nginx sbin]# cat /usr/local/nginx/.htpasswd
admin:$apr1$YA7aV290$/mFtcSkFTXxD0mv914D7j0
步骤3:添加其他用户

可以使用以下命令向已存在的.htpasswd文件中添加更多用户,如lee

[root@Nginx sbin]# htpasswd -m /usr/local/nginx/.htpasswd lee
New password: 
Re-type new password: 
Adding password for user lee

再次查看文件,以确保用户lee的信息也已成功添加:

[root@Nginx sbin]# cat /usr/local/nginx/.htpasswd
admin:$apr1$YA7aV290$/mFtcSkFTXxD0mv914D7j0
lee:$apr1$OMKtEE7H$pjbqR2LRVf6m.8ERF2rjw.
步骤4:创建受保护的目录并添加测试文件

接下来,创建一个用于存放受保护内容的目录,并在其中创建一个测试文件index.html

[root@Nginx sbin]# mkdir -p /data/web/lee
[root@Nginx sbin]# echo lee > /data/web/lee/index.html
步骤5:编辑Nginx配置文件以设置虚拟主机和访问控制

打开并编辑Nginx的虚拟主机配置文件:

[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

在配置文件中添加以下内容,配置虚拟主机并设置路径/lee的访问控制:

server {
    listen 80;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;

    location /lee {
        root /data/web;
        auth_basic "login password !!";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }
}

在此配置中,server块定义了虚拟主机的基本设置,location /lee块设置了访问路径/lee的密码保护。

保存配置文件后,重载Nginx服务以应用新的配置:

[root@Nginx ~]# nginx -s reload

在这里插入图片描述

在这里插入图片描述

实验3 nginx自定义错误页面

配置Nginx虚拟主机、为特定路径设置访问控制,并添加自定义的404错误页面。

步骤1:编辑Nginx虚拟主机配置文件
首先,打开并编辑Nginx的虚拟主机配置文件:

[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

在配置文件中添加以下内容,定义虚拟主机的基本设置,设置特定路径的访问控制,以及配置自定义404错误页面:

server { 
    listen 80;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;
    error_page 404 /40x.html;
    
    location /lee {
        root /data/web;
        auth_basic "login password !!";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    } 
    
    location = /40x.html {               
        root /data/web/errorpage;
    }
}

此配置包含以下内容:

  • listen 80;:监听80端口。
  • server_name www.timinglee.org;:指定虚拟主机域名。
  • root /data/web/html;index index.html;:设置网站的根目录和默认首页。
  • error_page 404 /40x.html;:定义404错误时跳转到自定义的错误页面。
  • location /lee:设置路径/lee的访问控制,需通过HTTP基本认证访问。
  • location = /40x.html:指定404错误页面的文件位置。

步骤2:创建自定义错误页面目录及文件
接下来,创建用于存放自定义错误页面的目录,并添加404错误页面:

[root@Nginx ~]# mkdir -p /data/web/errorpage
[root@Nginx ~]# echo "error page" > /data/web/errorpage/40x.html

此操作将创建/data/web/errorpage目录,并在其中创建名为40x.html的错误页面。

步骤3:重载Nginx服务以应用配置更改
保存配置文件后,重载Nginx服务以应用新的配置:

[root@Nginx ~]# nginx -s reload

测试

在这里插入图片描述

Nginx自定义日志及测试

步骤1:编辑Nginx虚拟主机配置文件
打开并编辑Nginx的虚拟主机配置文件:

[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

在配置文件中添加以下内容:

server {
    listen 80;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;
    error_page 404 /40x.html;
    
    # 自定义错误日志
    error_log /var/log/timinglee.org/error.log;

    # 自定义访问日志
    access_log /var/log/timinglee.org/access.log;

    location /lee {
        root /data/web;
        auth_basic "login password !!";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }
    
    location = /40x.html {
        root /data/web/errorpage;
    }
}

步骤2:创建日志目录
创建用于存储日志文件的目录:

[root@Nginx ~]# mkdir /var/log/timinglee.org

步骤3:重新加载Nginx配置
重新加载Nginx以应用新的配置:

[root@Nginx ~]# nginx -s reload

步骤4:测试配置
使用curl命令请求一个不存在的页面,以触发404错误页面,并验证自定义错误页面的显示:

[root@Nginx ~]# curl www.timinglee.org/aaa

输出:
在这里插入图片描述

该命令应返回自定义的错误页面内容“error page”,表示配置正确。

nginx中的文件检测

步骤1:编辑Nginx虚拟主机配置文件

打开并编辑Nginx的虚拟主机配置文件:

[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

server 块中添加或更新 try_files 指令:

server {
    listen 80;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;

    # 设置自定义错误页面
    error_page 500 502 503 504 /error/default.html;

    # 使用 try_files 指令尝试访问文件
    try_files $uri $uri.html $uri/index.html /error/default.html;

    location /lee {
        root /data/web;
        auth_basic "login password !!";
        auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }

    location = /error/default.html {
        root /data/web/html;
    }
}
步骤2:重新加载Nginx配置

应用新的配置:

[root@Nginx ~]# nginx -s reload
步骤3:测试配置

使用 curl 命令测试不同类型的请求,检查配置效果:

  1. 访问存在的页面:

    [root@Nginx ~]# curl www.timinglee.org
    

    输出:

    www.timinglee.org
    

    这表明 index.html 文件被正确加载。

  2. 访问不存在的页面:

    [root@Nginx ~]# curl www.timinglee.org/e
    

    输出:

    <html>
    <head><title>500 Internal Server Error</title></head>
    <body>
    <center><h1>500 Internal Server Error</h1></center>
    <hr><center>nginx/1.24.0</center>
    </body>
    </html>
    

    这表明返回了500错误页面。

  3. 创建自定义错误页面:
    创建目录和错误页面:

    [root@Nginx ~]# mkdir /data/web/html/error
    [root@Nginx ~]# echo "error default" > /data/web/html/error/default.html
    
  4. 重新测试访问不存在的页面:

    [root@Nginx ~]# curl www.timinglee.org/e
    

    输出:

    error default
    

    这表明自定义的错误页面“error default”已成功显示。

nginx中的长链接管理

首先,编辑Nginx主配置文件来设置 keepalive_requests 参数:

[root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf

在配置文件添加以下内容:

在这里插入图片描述

保存并退出配置文件。

步骤2:安装Telnet工具

安装Telnet工具以测试HTTP连接:

[root@Nginx ~]# dnf install telnet -y

步骤3:使用Telnet测试连接

通过Telnet连接到Nginx服务器并检查连接状态:

[root@Nginx ~]# telnet www.timinglee.org 80

输出:

Trying 127.0.0.1...
Connected to www.timinglee.org.
Escape character is '^]'.

连接成功后,可以通过输入HTTP请求来检查服务器响应。输入以下内容并按 Enter 键:

GET / HTTP/1.1
HOST: www.timinglee.org

注意: 在输入HTTP请求时,确保在最后一行按两次 Enter 键以发送请求。

步骤4:使用Curl测试HTTP版本和功能

使用Curl工具检查服务器的HTTP版本和功能:

[root@Nginx ~]# curl -V www.timinglee.org

输出:

curl 7.76.1 (x86_64-redhat-linux-gnu) libcurl/7.76.1 OpenSSL/3.0.1 zlib/1.2.11 brotli/1.0.9 libidn2/2.3.0 libpsl/0.21.1 (+libidn2/2.3.0) libssh/0.9.6/openssl/zlib nghttp2/1.43.0
Release-Date: 2021-04-14
Protocols: dict file ftp ftps gopher gophers http https imap imaps ldap ldaps mqtt pop3 pop3s rtsp scp sftp smb smbs smtp smtps telnet tftp 
Features: alt-svc AsynchDNS brotli GSS-API HTTP2 HTTPS-proxy IDN IPv6 Kerberos Largefile libz NTLM NTLM_WB PSL SPNEGO SSL TLS-SRP UnixSockets

下载服务器的设定及优化

步骤1:配置Nginx
  1. 编辑Nginx主配置文件

    打开Nginx主配置文件进行编辑:

    [root@Nginx ~]# vim /usr/local/nginx/conf/nginx.conf
    
  2. 创建下载目录

    创建一个用于存放下载文件的目录:

    [root@Nginx ~]# mkdir /data/web/download
    
  3. 生成测试文件

    创建一个100MB的测试文件,用于验证下载功能:

    [root@Nginx ~]# dd if=/dev/zero of=/data/web/download/leefile bs=1M count=100
    
  4. 配置虚拟主机

    编辑虚拟主机配置文件,设置下载服务:

    [root@Nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
    

    在配置文件中添加以下内容:

    location /download {
        root /data/web;
        autoindex on;
        autoindex_localtime on;
        autoindex_exact_size off;
        limit_rate 0;
    }
    

    配置说明:

    • root /data/web;:设置文件存储的根目录。
    • autoindex on;:启用自动索引功能,显示目录列表。
    • autoindex_localtime on;:显示本地时间。
    • autoindex_exact_size off;:简化文件大小显示。
    • limit_rate 0;:设置文件下载速度限制为无限制。
  5. 重新加载Nginx配置

    保存并退出配置文件后,重新加载Nginx以使配置生效:

    [root@Nginx ~]# nginx -s reload
    
步骤2:测试下载功能
  1. 测试目录索引

    使用 curl 命令访问下载目录,检查是否能正确显示文件列表:

    [root@Nginx ~]# curl http://www.timinglee.org/download/
    

    输出:

    <html>
    <head><title>Index of /download/</title></head>
    <body>
    <h1>Index of /download/</h1><hr><pre><a href="../">../</a>
    <a href="leefile">leefile</a>                                            20-Aug-2024 21:34    100M
    </pre><hr></body>
    </html>
    

在这里插入图片描述

Nginx 状态页面配置教程

1. 检查 Nginx 版本

使用以下命令检查当前安装的 Nginx 版本及其配置选项:

[root@Nginx ~]# nginx -V

输出:

nginx version: nginx/1.24.0
built by gcc 11.2.1 20220127 (Red Hat 11.2.1-9) (GCC) 
built with OpenSSL 3.0.1 14 Dec 2021
TLS SNI support enabled
configure arguments: --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

确保 Nginx 是使用 --with-http_stub_status_module 选项构建的,以支持状态页面功能。

2. 配置 Nginx 状态页面

编辑 Nginx 配置文件 /usr/local/nginx/conf.d/vhost.conf

[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

在配置文件中添加以下内容:

server {
    listen 80;
    server_name status.timinglee.org;
    root /data/web/html;
    index index.html;

    location /status {
        stub_status;
        # auth_basic "login";
        # auth_basic_user_file /usr/local/nginx/.htpasswd;
    }
}

测试

打开网址
http://status.timinglee.org/status

在这里插入图片描述

3. 配置访问控制(可选)

如果需要限制访问状态页面的 IP 地址,可以在 /etc/hosts 文件中添加如下配置:

[root@Nginx ~]# vim /etc/hosts

确保 /etc/hosts 文件包含如下条目(此条目通常用于本地测试,实际部署时应设置正确的 DNS 解析):

172.25.254.100  Nginx.timinglee.org status.timinglee.org

然后,编辑 Nginx 配置以限制访问状态页面的 IP 地址:

[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf

location /status 配置中添加访问控制:

location /status {
    stub_status;
    allow 172.25.254.1;  # 允许的 IP 地址
    deny all;            # 拒绝所有其他 IP 地址
}
4. 重新加载 Nginx 配置

保存配置文件后,重新加载 Nginx 配置以应用更改:

[root@Nginx ~]# nginx -s reload
5. 测试状态页面

通过浏览器或 curl 命令访问状态页面:

[root@Nginx ~]# curl http://status.timinglee.org/status

如果访问被拒绝,可能会看到如下错误页面:

<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.24.0</center>
</body>
</html>

这表明访问控制配置可能存在问题,需要确认 IP 地址是否被允许访问。

Nginx 数据压缩功能

1. 安装必要的依赖

在编译 Nginx 时,需安装以下依赖以支持数据压缩功能:

dnf install gcc pcre-devel zlib-devel openssl-devel -y

这些包提供了编译 Nginx 所需的基础库和工具。

2. 配置 Nginx 启用压缩

编辑 Nginx 配置文件 nginx.conf,启用 Gzip 压缩功能:

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf

在配置文件中添加或修改以下设置:

```nginx
gzip on;
gzip_comp_level 5;
gzip_min_length 1k;
gzip_http_version 1.1;
gzip_vary on;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/gif image/png;

  • gzip on;:启用 Gzip 压缩功能。
  • gzip_comp_level 5;:设置压缩级别,范围从 1 到 9。级别 5 提供了压缩率和处理速度的平衡。
  • gzip_min_length 1k;:设置压缩的最低文件大小。小于该大小的文件不会被压缩。
  • gzip_http_version 1.1;:设置 Gzip 压缩的最低 HTTP 版本。1.1 支持 Gzip 压缩。
  • gzip_vary on;:启用 Vary: Accept-Encoding 头,以便缓存服务器处理不同的编码类型。
  • gzip_types:定义需要压缩的 MIME 类型。包括了文本、JavaScript、CSS、XML 和图像文件等。

保存配置文件后,重新加载 Nginx 配置:

[root@Nginx ~]# nginx -s reload
3. 测试压缩功能

创建测试文件并测试其压缩效果:

[root@Nginx ~]# echo hello timinelee > /data/web/html/small.html
cat /usr/local/nginx/logs/access.log > /data/web/html/big.html

使用 curl 命令测试小文件和大文件的响应头:

[root@Nginx ~]# curl --head --compressed 172.25.254.100/small.html
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Tue, 20 Aug 2024 14:40:29 GMT
Content-Type: text/html
Content-Length: 16
Last-Modified: Tue, 20 Aug 2024 14:39:30 GMT
Connection: keep-alive
ETag: "66c4aaa2-10"
Accept-Ranges: bytes
[root@Nginx ~]# curl --head --compressed 172.25.254.100/big.html
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Tue, 20 Aug 2024 14:40:55 GMT
Content-Type: text/html
Last-Modified: Tue, 20 Aug 2024 14:40:00 GMT
Connection: keep-alive
Vary: Accept-Encoding
ETag: W/"66c4aac0-363b"
Content-Encoding: gzip
  • 对于 small.html,未启用压缩,因此 Content-Encoding 头部不存在。
  • 对于 big.html,启用了 Gzip 压缩,因此 Content-Encoding 头部为 gzip

Nginx 变量使用与配置指南

1. Nginx 变量概述

Nginx 支持使用内置变量和自定义变量。内置变量由 Nginx 模块自动提供,用于获取与客户端请求相关的各种信息。自定义变量则由用户在配置文件中定义,用于存储特定的值或结果。

2. 内置变量

内置变量由 Nginx 提供,涵盖了大量与请求和服务器状态相关的信息。以下是一些常用内置变量及其功能:

  • $remote_addr:客户端的 IP 地址。
  • $args:URL 中的所有参数。例如,https://search.jd.com/Search?keyword=手机&enc=utf-8 的返回结果为 keyword=手机&enc=utf-8
  • $is_args:如果 URL 中包含参数,则为 ?,否则为空。
  • $document_root:当前请求的根目录路径,例如 /webdata/nginx/timinglee.org/lee
  • $document_uri:当前请求的 URI,不包括参数。例如,http://lee.timinglee.org/var?id=11111 的返回结果为 /var
  • $host:请求的主机名。
  • $limit_rate:配置的限制速率值。如果未设置,则为 0
  • $remote_port:客户端请求 Nginx 时使用的端口。
  • $remote_user:经过 Auth Basic Module 验证的用户名。
  • $request_body_file:反向代理时发送给后端服务器的本地文件名。
  • $request_method:请求方法,如 GET、PUT、DELETE 等。
  • $request_filename:当前请求的资源文件的磁盘路径。
  • $request_uri:包含参数的原始 URI。
  • $scheme:请求的协议,如 http、https 等。
  • $server_protocol:请求使用的协议版本,如 HTTP/1.0、HTTP/1.1、HTTP/2.0。
  • $server_addr:服务器的 IP 地址。
  • $server_name:虚拟主机的主机名。
  • $server_port:虚拟主机的端口号。
  • $http_user_agent:客户端浏览器的详细信息。
  • $http_cookie:客户端的所有 cookie 信息。
  • $cookie_<name>:指定 cookie 的值。
  • $http_<name>:请求报文中的指定首部字段。
  • $sent_http_<name>:响应报文中的指定首部字段。
  • $arg_<name>:URL 中指定参数的值。
3. 自定义变量

在 Nginx 配置文件中,可以使用 set 指令定义自定义变量。语法格式如下:

set $variable value;

示例配置:

server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdata/nginx/timinglee.org/lee;

    location /var {
        default_type text/html;
        echo $remote_addr;
        echo $args;
        echo $document_root;
        echo $document_uri;
        echo $host;
        echo $http_user_agent;
        echo $request_filename;
        echo $scheme;
        echo $scheme://$host$document_uri?$args;
        echo $http_cookie;
        echo $cookie_key2;
        echo $http_Accept;
    }
}

实验:

[root@Nginx ~]# cd /usr/local/nginx/
[root@Nginx nginx]# ls
client_body_temp  conf.d        html  proxy_temp  scgi_temp
conf              fastcgi_temp  logs  sbin        uwsgi_temp
[root@Nginx nginx]# cd conf.d/
[root@Nginx conf.d]# 

[root@Nginx conf.d]# nginx -s reload

[root@Nginx nginx-1.24.0]# vim /etc/hosts

172.25.254.100  Nginx.tinminglee.org status.timinglee.org var.timinglee.org

[root@Nginx ~]# curl var.timinglee.org/var
172.25.254.100


/data/web/html
/var
var.timinglee.org
48604

GET
/data/web/html/var
/var
http
HTTP/1.1
172.25.254.100
var.timinglee.org
80
curl/7.76.1


测试在这里插入图片描述

(2)自定义变量

[root@Nginx ~]# cd /usr/local/nginx/conf.d/
[root@Nginx conf.d]# ls
status.conf  vars.conf  vhost.conf
[root@Nginx conf.d]# vim vars.conf 
[root@Nginx conf.d]# 
server {
    listen 80;
    server_name var.timinglee.org;
    root /data/web/html;
    index index.html;

    location /var {
        default_type text/html;
        set $timinglee lee;
        echo $timinglee;
    }
}

在这里插入图片描述

4. Nginx Rewrite 模块

Nginx 的 ngx_http_rewrite_module 模块允许对 URL 进行重写。此功能使用 Perl 兼容正则表达式 (PCRE) 实现。配置示例如下:

常用指令:

  • if 指令:用于条件匹配和选择不同的配置。语法如下:
if (condition) {
    action
}

条件示例:

  • =: 比较变量和字符串是否相等。
  • !=: 比较变量和字符串是否不相等。
  • ~: 区分大小写的正则表达式匹配。
  • !~: 区分大小写的正则表达式不匹配。
  • ~*: 不区分大小写的正则表达式匹配。
  • !~*: 不区分大小写的正则表达式不匹配。
  • -f!-f: 判断文件是否存在。
  • -d!-d: 判断目录是否存在。
  • -x!-x: 判断文件是否可执行。
  • -e!-e: 判断文件或目录是否存在,包括软链接。

示例配置:

server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdata/nginx/timinglee.org/lee;

    location /test {
        index index.html;
        default_type text/html;
        if ($scheme = http) {
            echo "if ---------> $scheme";
        }
        if ($scheme = https) {
            echo "if ---------> $scheme";
        }
    }

    location /test2 {
        if (!-e $request_filename) {
            echo "$request_filename is not exist";
            return 409;
        }
    }
}

实验



[root@Nginx conf.d]# curl var.timing.org/test2/index.html
curl: (6) Could not resolve host: var.timing.org
[root@Nginx conf.d]# curl var.timinglee.org/test2/index.html
/data/web/html/test2/index.html is not exist
[root@Nginx conf.d]# mkd
mkdict    mkdir     mkdosfs   mkdumprd  
[root@Nginx conf.d]# mkdir -p var.timinglee.org/test2/
[root@Nginx conf.d]# rm -fr var.timinglee.org/test2/
[root@Nginx conf.d]# mkdir /data/web/html/test2
[root@Nginx conf.d]#  echo test2 > /data/web/html/test2/index.html
[root@Nginx conf.d]# curl var.timinglee.org/test2/index.html
test2

在这里插入图片描述

set 指令

set 指令用于定义一个变量,并将其赋值为文本、变量或两者的组合。定义格式为 set $key valuevalue 可以是纯文本、Nginx 内置变量,或这两者的组合。

示例配置:

server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdata/nginx/timinglee.org/lee;

    location /test3 {
        set $name lee;
        echo $name;
    }
}

在此配置中,$name 被设置为 lee,并通过 echo 指令输出。

break 指令

break 指令用于中断当前作用域(例如 location 块)中的其他 Nginx 配置。在遇到 break 指令时,Nginx 会停止处理该作用域内的后续配置,并返回到上一层作用域继续处理。break 指令可以在 server 块和 location 块中使用,但不会影响在 ngx_http_rewrite_module 模块中的指令。

示例配置:

server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdata/nginx/timinglee.org/lee;

    location /break {
        default_type text/html;
        set $name lee;
        echo $name;
        break;
        set $port $server_port;
        echo $port;
    }
}

在这个示例中,break 指令会阻止后续的 setecho $port 指令的执行,只会输出 lee
实验


[root@Nginx conf.d]# vim vars.conf 
[root@Nginx conf.d]# nginx -s reload


测试
[root@Nginx conf.d]# curl  var.timinglee.org/break
lee

[root@Nginx conf.d]# curl -A "firefox"  var.timinglee.org/break
lee
666
[root@Nginx conf.d]# 

在这里插入图片描述

return 指令

return 指令用于结束请求的处理并直接返回响应状态码,可以指定重定向 URL(如 301、302 状态码)或提示文本(如 403、500 状态码)。return 指令会终止该指令后的所有配置。

示例配置:

server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdata/nginx/timinglee.org/lee;

    location /return {
        default_type text/html;
        if (!-e $request_filename) {
            return 301 http://www.baidu.com;
        }
        echo "$request_filename is exist";
    }
}

在此配置中,如果 $request_filename 不存在,将返回 301 重定向到百度;如果存在,则输出文件存在的信息。

实验

[root@Nginx conf.d]# vim vars.conf 
[root@Nginx conf.d]# nginx -s reload

   location /return {
        default_type text/html;
        if ( !-e $request_filename){
            return 301 http://www.baidu.com;
        }
        echo "$request_filename is exist";
    }


测试
[root@Nginx conf.d]# curl -I var.timinglee.org/return
HTTP/1.1 301 Moved Permanently
Server: nginx/1.24.0
Date: Wed, 21 Aug 2024 15:57:08 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://www.baidu.com

[root@Nginx conf.d]#  mkdir  -p /data/web/html/return
[root@Nginx conf.d]# curl -I var.timinglee.org/return
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Wed, 21 Aug 2024 15:58:47 GMT
Content-Type: text/html
Connection: keep-alive
Vary: Accept-Encoding

[root@Nginx conf.d]#  curl var.timinglee.org/return
/data/web/html/return is exist
[root@Nginx conf.d]# 


在这里插入图片描述

rewrite 指令

rewrite 指令用于根据正则表达式匹配和修改 URI。可以设置多个 rewrite 指令,按顺序进行 URI 的匹配和替换。rewrite 指令的语法格式为 rewrite regex replacement [flag]

正则表达式的基本格式:

  • .:匹配任意字符(除换行符外)
  • \w:匹配字母、数字、下划线或汉字
  • \s:匹配任意空白符
  • \d:匹配数字
  • ^:匹配字符串的开始
  • $:匹配字符串的结束
  • *:匹配零次或多次
  • +:匹配一次或多次
  • ?:匹配零次或一次
  • {n}:匹配 n 次
  • {n,}:匹配 n 次或更多次
  • {n,m}:匹配 n 到 m 次

rewrite 指令的标志位(flag)包括:

  • redirect:临时重定向(状态码 302),客户端会重新发起请求
  • permanent:永久重定向(状态码 301),客户端会缓存重定向
  • break:停止对当前 URI 在当前 location 中的后续 rewrite 操作,跳转至当前 location 中配置块之后的其它配置
  • last:停止对当前 URI 在当前 location 中的后续 rewrite 操作,并启动新一轮的重写检查

示例配置:

server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdata/nginx/timinglee.org/lee;

    location /rewrite {
        rewrite ^/old-url$ /new-url permanent;
    }
}

在此配置中,rewrite 指令会将 /old-url 永久重定向到 /new-url

域名重定向概述

本节将详细介绍如何使用 Nginx 配置文件中的 rewrite 指令来实现域名的永久 (301) 和临时 (302) 重定向。这两种重定向类型的主要区别在于客户端是否缓存重定向信息。

永久重定向 (301)

永久重定向用于指示域名永久性地移动到了新位置。这意味着客户端浏览器会缓存该重定向信息,即使 Nginx 服务器不可达,浏览器也能利用缓存信息继续执行重定向。

示例配置
server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdata/nginx/timinglee.org/lee;
    location / {
        rewrite ^/ http://lee.timinglee.com permanent;
    }
}

在这个例子中,所有对 lee.timinglee.org 的请求都将被永久重定向到 lee.timinglee.compermanent 关键字指定了 HTTP 状态码为 301

临时重定向 (302)

临时重定向用于指示域名暂时性地移动到了新位置。这通常意味着客户端浏览器不会缓存重定向信息,因此如果 Nginx 服务器不可达,浏览器将无法利用缓存信息进行重定向。

示例配置
server {
    listen 80;
    server_name lee.timinglee.org;
    root /webdata/nginx/timinglee.org/lee;
    location / {
        rewrite ^/ http://lee.timinglee.com redirect;
    }
}

在此示例中,所有对 lee.timinglee.org 的请求将被临时重定向到 lee.timinglee.comredirect 关键字指定了 HTTP 状态码为 302

测试配置

为了验证这些配置的有效性,可以使用以下步骤进行测试:

  1. 保存配置文件

    • 将永久重定向的配置保存到 /usr/local/nginx/conf.d/vhosts.conf
    • 同样地,将临时重定向的配置保存到相同的文件中,但确保注释掉其中一种重定向模式。
  2. 重启 Nginx

    • 通过执行 nginx -t 来检查配置文件是否有语法错误。
    • 如果没有错误,使用 nginx -s reload 来重启 Nginx 服务。
  3. 访问域名

    • 使用 Web 浏览器访问 http://lee.timinglee.org 来测试永久重定向。
    • 同样地,访问该地址来测试临时重定向(需要确保使用了正确的配置)。
  • 当使用 rewrite 指令时,确保正确设置了 rootserver_name
  • rewrite 指令中的正则表达式(例如 ^/)用来匹配 URL。
  • 为了避免无限循环重定向,确保目标 URL 是明确的且有效。
  • 永久重定向 (permanent) 会缓存重定向信息,而临时重定向 (redirect) 不会缓存。
  • 在实际部署前,务必进行充分的测试以确保一切按预期工作。
  • 实验
实验

```bash 


    location / {
        root /data/web/var;
        index index.html;
       #  rewrite / http://www.timinglee.com permanent;
        #rewrite / http://www.timinglee.com redirect;
    }
}

[root@Nginx conf.d]# mkdir /data/web/var -p
[root@Nginx conf.d]# echo var page > /data/web/var/index.html
[root@Nginx conf.d]# curl www.timinglee.org
var.timinglee.org
[root@Nginx conf.d]# 

[root@Nginx conf.d]# curl -I  var.timinglee.org
HTTP/1.1 301 Moved Permanently
Server: nginx/1.24.0
Date: Wed, 21 Aug 2024 16:27:38 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://www.timinglee.com


[root@Nginx conf.d]# curl var.timinglee.org
var page



server {
    listen 80;
    server_name var.timinglee.org;
    root /data/web/html;
    index index.html;
    location / {
        root /data/web/var;
        index index.html;
         rewrite / http://www.timinglee.com permanent;
        #rewrite / http://www.timinglee.com redirect;
    }
}

永久重定向301

[root@Nginx conf.d]# vim vars.conf 
[root@Nginx conf.d]# nginx -s reload
[root@Nginx conf.d]# curl var.timinglee.org
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.24.0</center>
</body>
</html>
[root@Nginx conf.d]# 
[root@Nginx conf.d]# curl -I  var.timinglee.org
HTTP/1.1 301 Moved Permanently
Server: nginx/1.24.0
Date: Wed, 21 Aug 2024 16:43:13 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://www.timinglee.com





#临时重定向302
[root@Nginx conf.d]# vim vars.conf 
[root@Nginx conf.d]# nginx -s reload
[root@Nginx conf.d]# curl -I  var.timinglee.org
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.24.0
Date: Wed, 21 Aug 2024 16:45:23 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: http://www.timinglee.com

全站防盗

Nginx HTTPS 配置及重定向设置

为域名www.timinglee.org配置Nginx服务器以支持HTTPS,并实现从HTTP到HTTPS的自动重定向。

1. 创建SSL证书

首先,使用openssl命令生成自签名的SSL证书和私钥,并将其保存在Nginx服务器的/usr/local/nginx/certs/目录下:

[root@nginx ~]# cd /usr/local/nginx/
[root@nginx nginx]# mkdir certs
[root@nginx nginx]# openssl req -newkey rsa:2048 -nodes -sha256 -keyout /usr/local/nginx/certs/timinglee.org.key -x509 -days 365 -out /usr/local/nginx/certs/timinglee.org.crt

生成的证书文件timinglee.org.crt和密钥文件timinglee.org.key将用于配置Nginx的SSL支持。

2. 配置Nginx服务器

在Nginx的配置文件/usr/local/nginx/conf.d/vars.conf中,为域名www.timinglee.org设置服务器块以支持HTTPS,并实现HTTP到HTTPS的自动重定向:

server {
    listen 80;
    listen 443 ssl;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;

    ssl_certificate /usr/local/nginx/certs/timinglee.org.crt;
    ssl_certificate_key /usr/local/nginx/certs/timinglee.org.key;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;

    location / {
        if ( $scheme = http ){
            rewrite /(.*) https://$host/$1 redirect;  # 将HTTP请求重定向到HTTPS
        }
        if ( !-e $request_filename ){
            rewrite /(.*) https://$host/index.html redirect;  # 如果请求的文件不存在,重定向到index.html
        }
    }
}

该配置实现以下功能:

  • 监听80端口(HTTP)和443端口(HTTPS)。
  • 使用ssl_certificatessl_certificate_key指令配置SSL证书和私钥。
  • ssl_session_cachessl_session_timeout用于管理SSL会话缓存。
  • 通过rewrite指令将HTTP请求自动重定向到HTTPS。
  • 如果请求的文件不存在,则重定向到index.html
3. 重载Nginx配置

在配置文件修改完成后,需重载Nginx以应用新配置:

[root@nginx ~]# nginx -s reload
4. 验证配置

使用curl命令验证域名www.timinglee.org的HTTP请求是否正确重定向到HTTPS:

[root@nginx conf.d]# curl -I www.timinglee.org
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.24.0
Date: Thu, 22 Aug 2024 01:26:06 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: https://www.timinglee.org/

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

防盗链

主要是设置Nginx来防止图片被盗链使用,也就是防止其他网站直接链接你的网站上的图片。通过配置Nginx,你可以确保只有来自特定来源的请求可以访问你网站上的图片文件。

配置解析
  1. 创建目录和移动图片:

    • mkdir -p /data/web/html/images: 创建图片存放的目录。
    • mv 22.png /data/web/html: 将22.png移动到web根目录。
    • mv 33.png /data/web/html/images/: 将33.png移动到/images目录。
  2. 配置Nginx:

    • 打开/usr/local/nginx/conf.d/vars.conf,添加如下内容:
      server {
          listen 80;
          listen 443 ssl;
          server_name www.timinglee.org;
          root /data/web/html;
          index index.html;
          ssl_certificate /usr/local/nginx/certs/timinglee.org.crt;
          ssl_certificate_key /usr/local/nginx/certs/timinglee.org.key;
          ssl_session_cache    shared:SSL:1m;
          ssl_session_timeout  5m;
      
          location /images {
              valid_referers none blocked server_names *.timinglee.org ~/.baidu/.;
              if ( $invalid_referer ) {
                  return 404;
              }
          }
      }
      
    • 解释配置:
      • valid_referers:指定哪些Referer头部被认为是有效的。none表示没有Referer的请求,blocked表示没有Referer或被代理或防火墙隐藏的请求,server_names表示来自当前服务器名称的请求。*.timinglee.org表示来自你的域名的请求。
      • if ($invalid_referer) { return 404; }:如果请求的Referer不在有效列表中,则返回404错误。
  3. 在另一个服务器上测试盗链:

    • 安装httpd并创建一个简单的HTML页面来测试防盗链功能。
测试步骤
  1. 在另一台服务器上设置测试环境

    • 安装Apache (httpd) 并启动它。
    • 创建一个index.html文件,内容如教程所示,引用了你网站上的图片33.png
  2. 访问测试页面

    • 启动Apache服务器后,通过浏览器访问这个测试页面。
    • 如果防盗链配置正确,图片33.png将不会显示(会返回404错误),因为请求的Referer不在允许列表中。
结果
  • 如果配置正确,当访问http://www.timinglee.org/images/33.png 时,除非请求来源于指定的Referer,否则Nginx会返回404错误。
  • 可以通过修改或添加更多valid_referers选项来允许其他来源访问图片,或者更严格地限制图片访问。


在这里插入图片描述

成功
在这里插入图片描述

反向代理

你的代码和步骤大体上是正确的,但有一些细节可能需要注意。根据你的描述,我将分析和复现步骤,编写一个详细的教程,以确保你能顺利完成HTTP反向代理的配置。

1. HTTP反向代理配置教程

1.1 准备环境

两个HTTP服务器 node1node2,以及一个Nginx服务器 nginx

node1node2 上安装并配置HTTP服务器:
  1. 安装HTTP服务器

    # 在 node1 和 node2 上执行
    dnf install httpd -y
    
  2. 启动并设置开机自启动

    # 在 node1 和 node2 上执行
    systemctl enable --now httpd
    
  3. 配置HTTP服务器

    • node1
      echo 172.25.254.10 > /var/www/html/index.html
      
    • node2
      echo 172.25.254.20 > /var/www/html/index.html
      vim /etc/httpd/conf/httpd.conf
      
      httpd.conf 文件中添加或修改以下行,将HTTP服务器监听端口改为8080:
      Listen 8080
      
      保存并退出后,重启httpd服务:
      systemctl restart httpd
      
  4. 测试HTTP服务器是否正常工作

    • nginx 上使用 curl 命令测试 node1node2
      curl 172.25.254.10
      172.25.254.10
      
      
      
      curl 172.25.254.20
      172.25.254.20
      
      
      
1.2 在 nginx 上配置反向代理
  1. 编辑Nginx配置文件

    vim /usr/local/nginx/conf.d/vhost.conf
    

    添加以下配置:

    server {
        listen 80;
        server_name www.timinglee.org;
    
        location / {
            proxy_pass http://172.25.254.10:80;
        }
    
        location /static {
            proxy_pass http://172.25.254.20:8080;
        }
    }
    
  2. 重新加载Nginx配置

    nginx -s reload
    
1.3 测试反向代理
  1. 测试根目录的代理

    curl www.timinglee.org
    # 输出: 172.25.254.10
    
  2. 测试 /static 路径的代理

    curl www.timinglee.org/static/
    # 如果没有配置static目录,会返回404错误页面
    
  3. node2 上创建 static 目录并测试

    • 创建目录并添加测试文件:
      mkdir -p /var/www/html/static
      echo static 172.25.254.20 > /var/www/html/static/index.html
      
    • nginx 上再次测试:
      curl www.timinglee.org/static/
      # 输出: static 172.25.254.20
      

此配置实现了基本的HTTP反向代理功能,通过指定不同的 location 实现不同路径的代理。通过测试,你可以验证反向代理是否按预期工作。如果在配置过程中遇到任何问题,请确保检查防火墙设置,确保端口(如80和8080)已开放并且未被其他服务占用。

动静分离

在这段代码中,目标是通过 Nginx 实现动静分离,也就是将动态内容(如 PHP 文件)交给一个服务器处理,静态内容(如图片、CSS、JS 等)交给另一个服务器处理。

1. 环境准备

两个 HTTP 服务器:

  • 172.25.254.10:处理动态内容(如 PHP)。
  • 172.25.254.20:处理静态内容。
2. 配置动态服务器(172.25.254.10
  1. 安装 PHP 和 HTTP 服务:

    [root@http ~]# dnf install php -y
    [root@http ~]# dnf install httpd -y
    
  2. 创建 PHP 测试文件:

    [root@http ~]# vim /var/www/html/index.php
    

    文件内容如下:

    <?php
      phpinfo();
    ?>
    
  3. 启动并配置 HTTP 服务:

    [root@http ~]# systemctl enable --now httpd
    [root@http ~]# systemctl restart httpd
    
3. 配置静态服务器(172.25.254.20
  1. 创建静态文件目录:

    [root@html2 ~]# mkdir -p /var/www/html/static
    [root@html2 ~]# echo "static 172.25.254.20" > /var/www/html/static/index.html
    
  2. 启动并配置 HTTP 服务:

    [root@html2 ~]# dnf install httpd -y
    [root@html2 ~]# systemctl enable --now httpd
    [root@html2 ~]# systemctl restart httpd
    
4. 配置 Nginx 作为反向代理(Nginx 服务器)
  1. 编辑 Nginx 配置文件:

    [root@Nginx conf.d]# vim /usr/local/nginx/conf.d/vhost.conf
    

    配置内容如下:

    server {
        listen 80;
        server_name www.timinglee.org;
    
        # 动态内容处理
        location ~ \.php$ {
            proxy_pass http://172.25.254.10:80;
    
        }
    
        # 静态内容处理
        location /static {
            proxy_pass http://172.25.254.20:8080;
        }
    }
    
  2. 重新加载 Nginx 配置:

    [root@Nginx conf.d]# nginx -s reload
    
5. 测试配置
  1. 验证动态内容:

    访问 http://www.timinglee.org/index.php,如果配置正确,你应该看到 PHP 的 phpinfo() 页面。

  2. 验证静态内容:

    访问 http://www.timinglee.org/static/,应该显示 static 172.25.254.20
    在这里插入图片描述

总结

  • 动静分离:通过 Nginx 的反向代理功能,将动态请求(PHP)交给 172.25.254.10 处理,将静态请求(如图片、CSS)交给 172.25.254.20 处理。
  • 修正:配置 Nginx 处理 .php 文件时,确保使用 fastcgi 参数,并在 php-fpm 上运行 PHP 服务。
    在这里插入图片描述
  • 8
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值