【超详细】Nginx功能和详细配置,附带实例解析

目录

一、企业高性能web服务器

1.1 Web服务介绍

1.2 Apache 经典的Web服务端

1.2.1 Apache prefork 模型

1.2.2 Apache worker 模型

1.2.3 Apache event 模型

二、Nginx特点和用途

三、Nginx实例解析

3.1 实例1:编译安装nginx

3.2 实例2: 平滑升级和回滚

3.2.1 平滑升级

3.2.2 回滚

3.3 options

3.4 Nginx启动文件

四、Nginx 核心配置

4.1 修改全局配置文件 

4.2 新建web站点

4.3 location

4.4 nginx的用户认证

4.5 自定义错误页面

4.6 自定义错误日志

4.7 检测文件是否存在

4.8 长链接

4.9 下载服务器配置

五、Nginx高级配置

5.1 nginx的状态页

5.2 nginx压缩

5.3 nginx变量使用

六、Nginx Rewrite功能

6.1 if判定

6.2 break指令

6.3 return 指令

6.4 rewrite指令

6.4.1 rewrite flag介绍

6.4.2 临时和永久设置

6.4.3 break和last

6.4.4 全站加密

6.4.5 防盗链

七、反向代理

7.1 http反向代理

7.1.1 指定location实现反向代理

7.1.2 缓存功能

7.2 http反向代理负载均衡

7.2.1 示例:后端多台web服务器

7.3 Nginx四层负载均衡

7.3.1 DNS

7.3.2 数据库

7.4 实现FastCGI

7.4.1 实例:Nginx和php-fpm在同一服务器

7.4.2 实例:php的动态扩展模块

7.4.3 php高速缓存

八、nginx的二次开发

8.1 编译安装 openresty


一、企业高性能web服务器

1.1 Web服务介绍

正常情况下的单次web服务访问流程:

企业高性能Web服务器Nginx是一个开源的、高性能的http和反向代理服务器,同时也支持IMAP/POP3/SMTP协议。因其卓越的性能、稳定性、丰富的/功能以及简单的配置收到企业欢迎。

而在企业环境中,Nginx称为高性能的Web服务器,应用在托管网站和Web应用程序,并处理大量的并发连接,由于比传统的Appache在资源消耗上更加高效,而成为企业处理流量网站和Web应用的理想选择。

此外,Nginx还被用作反向代理和负载均衡器。作为反向代理,Nginx可以接收来自客户端的请求,并将这些请求转发到后端的一组服务器上。通过负载均衡策略,Nginx将请求分配给这些服务器,以确保负载均衡,以提高系统的整体性能和可靠性。

1.2 Apache 经典的Web服务端

Apache通过编译安装实现特定的功能

1.2.1 Apache prefork 模型

  • 预派生模式,有一个主控制进程,然后生成多个子进程,使用select模型,最大并发1024

  • 每个子进程有一个独立的线程响应用户请求

  • 相对比较占用内存,但是比较稳定,可以设置最大和最小进程数

  • 是最古老的一种模式,也是最稳定的模式,适用于访问量不是很大的场景

优点:稳定

缺点:每个用户请求需要对应开启一个进程,占用资源较多,并发性差,不适用于高并发场景

1.2.2 Apache worker 模型

  • 一种多进程和多线程混合的模型

  • 有一个控制进程,启动多个子进程

  • 每个子进程里面包含固定的线程

  • 使用线程程来处理请求

  • 当线程不够使用的时候会再启动一个新的子进程,然后在进程里面再启动线程处理请求

  • 由于其使用了线程处理请求,因此可以承受更高的并发

优点:相比prefork 占用的内存较少,可以同时处理更多的请求

缺点:使用keepalive的长连接方式,某个线程会一直被占据,即使没有传输数据,也需要一直等待到超 时才会被释放。如果过多的线程,被这样占据,也会导致在高并发场景下的无服务线程可用

1.2.3 Apache event 模型

与worker模式很像,最大的区别是:解决了keepalived场景下长期被占用的线程的资源问题,

优点:当有真实请求过来的时候,将请求传递给服务线程,执行完毕后,又允许它释放,增强了高并发场景下的请求处理能力。

缺点:没有线程安全控制

二、Nginx特点和用途

  • 高性能的HTTP服务器:Nginx设计用于处理高并发连接,并且比传统的服务器(如Apache)在资源消耗上更为高效。这使得它非常适合作为Web服务器,特别是在需要处理大量并发请求的场景中。

  • 反向代理和负载均衡:Nginx可以作为反向代理服务器,将客户端的请求转发到后端的一组服务器上,并根据配置的负载均衡策略(如轮询、最少连接等)来分配请求。这有助于提升应用的可用性和响应速度。

  • HTTP/2和HTTP/3支持:Nginx支持HTTP/2和HTTP/3协议,这些协议提供了比HTTP/1.1更快的传输速度和更好的性能。

  • 静态文件服务:Nginx非常适合用于服务静态文件(如HTML、CSS、JavaScript、图片等),因为它可以直接从磁盘读取文件并发送给客户端,而无需通过应用程序服务器。

  • SSL/TLS终止:Nginx支持SSL/TLS协议,可以用于加密和解密HTTPS流量,保护用户数据的安全。

  • 模块化设计:Nginx采用模块化设计,可以根据需要加载不同的模块来扩展其功能。这包括第三方模块,这些模块提供了额外的功能,如缓存、安全、日志记录等。

  • 热部署:Nginx支持在不中断服务的情况下升级和重新加载配置,这对于生产环境来说非常重要。

三、Nginx实例解析

3.1 实例1:编译安装nginx

在教学中通常使用 dnf install nginx,而在企业场合中,绝大多数使用的编译安装nginx

实验环境: 【RHEL 9.2】  别名:nginx.chuling.org IP地址:172.25.254.10

#下载需要的安装包
[root@Nginx ~]# dnf install gcc pcre-devel zlib-devel openssl-devel -y
[root@nginx ~]# tar zxf nginx-1.24.0.tar.gz 
#添加用户
[root@Nginx nginx-1.24.0]# useradd -s /sbin/nologin -M nginx
#参数含义阐述
[root@nginx nginx-1.24.0]# ./configure --prefix=/usr/local/nginx \
--user=nginx \            # 指定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 \ # 支持压缩
--with-pcre \              # 支持正则
--with-stream \            # 支持tcp反向代理
--with-stream_ssl_module \ # 支持tcp的ssl加密
--with-stream_realip_module # 支持tcp的透传ip
​
​#源码编译
[root@nginx nginx-1.24.0]# ./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
[root@nginx nginx-1.24.0]# ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README
#编译安装
[root@nginx nginx-1.24.0]# make && make install
...
​
[root@nginx nginx-1.24.0]# ls /usr/local/nginx/
conf  html  logs  sbin
#conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和fastcgi_params两个文件,配置文件一般都有一个样板配置文件,是以.default为后缀,使用时可将其复制并将default后缀去掉即可。
#html:目录中保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的web文件是默认的错误页面提示页面。
#logs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比
如/var/logs/nginx里面。
#sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。
​
[root@nginx nginx-1.24.0]# cd /usr/local/nginx/sbin/
[root@nginx sbin]# ls
nginx
​
#把nginx软件的命令执行路径添加到环境变量中
[root@nginx nginx]# vi ~/.bash_profile
export PATH=$PATH:/usr/local/nginx/sbin
[root@nginx nginx]# source ~/.bash_profile
​
#查看磁盘使用量
[root@nginx nginx]# du -sh /usr/local/nginx/sbin/nginx 
5.5M    /usr/local/nginx/sbin/nginx
​#测试
[root@nginx nginx]# nginx
[root@nginx nginx]# curl 172.25.254.10
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
[root@nginx sbin]# id nginx 
uid=1000(nginx) gid=1000(nginx) groups=1000(nginx)

3.2 实例2: 平滑升级和回滚

3.2.1 平滑升级

#解压软件包
[root@nginx ~]# ls
anaconda-ks.cfg  echo-nginx-module-0.63.tar.gz  nginx-1.24.0  nginx-1.24.0.tar.gz  nginx-1.26.1  nginx-1.26.1.tar.gz
[root@nginx ~]# tar zxf nginx-1.26.1.tar.gz 
[root@nginx ~]# tar zxf echo-nginx-module-0.63.tar.gz 
[root@nginx ~]# cd nginx-1.26.1
[root@nginx nginx-1.26.1]# ls
auto     CHANGES.ru  configure  html     man     src
CHANGES  conf        contrib    LICENSE  README
​
#加入模板参数检测
[root@nginx nginx-1.26.1]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --add-module=/root/echo-nginx-module-0.63 --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
​
[root@nginx nginx-1.26.1]# ls
auto     CHANGES.ru  configure  html     Makefile  objs    src
CHANGES  conf        contrib    LICENSE  man       README
[root@nginx nginx-1.26.1]# make  #
[root@nginx nginx-1.26.1]# cd objs/
[root@nginx objs]# ls
autoconf.err  nginx    ngx_auto_config.h   ngx_modules.c  src
Makefile      nginx.8  ngx_auto_headers.h  ngx_modules.o
[root@nginx objs]# cd /usr/local/nginx/sbin/
[root@nginx sbin]# ls  (如果里面不止一个,则需做一下几步)
nginx
​
​
{
[root@nginx sbin]# nginx -s stop
[root@nginx ~]# rm -rf /usr/local/nginx/
[root@nginx ~]# cd /root/nginx-1.24.0/
[root@nginx nginx-1.24.0]# ls
auto        conf       html      man     src
CHANGES     configure  LICENSE   objs
CHANGES.ru  contrib    Makefile  README
[root@nginx nginx-1.24.0]# make install
​
}
​
#先把nginx备份
[root@nginx sbin]# cp nginx nginx.old
[root@nginx sbin]# ls
nginx  nginx.old
​
#把新版本的nginx命令复制过去
[root@nginx sbin]# \cp -f /root/nginx-1.26.1/objs/nginx /usr/local/nginx/sbin
[root@nginx sbin]# ps -aux | grep nginx
avahi        896  0.0  0.1  15532  6196 ?        Ss   20:18   0:00 avahi-daemon: running [nginx.local]
root        5307  0.0  0.0   9856   928 ?        Ss   21:03   0:00 nginx: master process nginx
nginx       5308  0.0  0.1  13752  5244 ?        S    21:03   0:00 nginx: worker process
root        5324  0.0  0.0 221664  2240 pts/0    S+   21:04   0:00 grep --color=auto nginx
[root@nginx sbin]# pidof nginx
5308 5307
​
#把旧的work回收,使用新的进程。
[root@nginx sbin]# kill -USR2 5307  #nginx worker ID
[root@nginx sbin]# ps -aux | grep nginx
avahi        896  0.0  0.1  15532  6196 ?        Ss   20:18   0:00 avahi-daemon: running [nginx.local]
root        5307  0.0  0.0   9856  2524 ?        Ss   21:03   0:00 nginx: master process nginx
nginx       5308  0.0  0.1  13752  5244 ?        S    21:03   0:00 nginx: worker process
root        5325  0.0  0.1   9884  6028 ?        S    21:05   0:00 nginx: master process nginx
nginx       5326  0.0  0.1  13780  4712 ?        S    21:05   0:00 nginx: worker process
root        5329  0.0  0.0 221664  2252 pts/0    S+   21:05   0:00 grep --color=auto nginx
​
[root@nginx sbin]# curl -I 172.25.254.10
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Fri, 16 Aug 2024 13:05:39 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Fri, 16 Aug 2024 13:02:49 GMT
Connection: keep-alive
ETag: "66bf4df9-267"
Accept-Ranges: bytes
​
​
[root@nginx sbin]#  kill -WINCH 5307
[root@nginx sbin]# ps -aux | grep nginx
avahi        896  0.0  0.1  15532  6196 ?        Ss   20:18   0:00 avahi-daemon: running [nginx.local]
root        5307  0.0  0.0   9856  2524 ?        Ss   21:03   0:00 nginx: master process nginx
root        5325  0.0  0.1   9884  6028 ?        S    21:05   0:00 nginx: master process nginx
nginx       5326  0.0  0.1  13780  4712 ?        S    21:05   0:00 nginx: worker process
root        5331  0.0  0.0 221664  2232 pts/0    S+   21:06   0:00 grep --color=auto nginx
​
​
#升级情况
[root@nginx sbin]# curl -I 172.25.254.10
HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Fri, 16 Aug 2024 13:06:30 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Fri, 16 Aug 2024 13:02:49 GMT
Connection: keep-alive
ETag: "66bf4df9-267"
Accept-Ranges: bytes

3.2.2 回滚

#处理进程
[root@nginx sbin]# kill -HUP 5307
[root@nginx sbin]# ps -aux | grep nginx
avahi        896  0.0  0.1  15532  6196 ?        Ss   20:18   0:00 avahi-daemon: running [nginx.local]
root        5307  0.0  0.0   9856  2524 ?        Ss   21:03   0:00 nginx: master process nginx
root        5325  0.0  0.1   9884  6028 ?        S    21:05   0:00 nginx: master process nginx
nginx       5326  0.0  0.1  13780  5256 ?        S    21:05   0:00 nginx: worker process
nginx       5333  0.0  0.1  13752  4700 ?        S    21:06   0:00 nginx: worker process
root        5335  0.0  0.0 221664  2256 pts/0    S+   21:06   0:00 grep --color=auto nginx
​
​
#回收新版本
[root@nginx sbin]# kill -WINCH 5325
[root@nginx sbin]# ps -aux | grep nginx
avahi        896  0.0  0.1  15532  6196 ?        Ss   20:18   0:00 avahi-daemon: running [nginx.local]
root        5307  0.0  0.0   9856  2524 ?        Ss   21:03   0:00 nginx: master process nginx
root        5325  0.0  0.1   9884  6028 ?        S    21:05   0:00 nginx: master process nginx
nginx       5333  0.0  0.1  13752  4700 ?        S    21:06   0:00 nginx: worker process
root        5337  0.0  0.0 221664  2252 pts/0    S+   21:07   0:00 grep --color=auto nginx
​
#提示回滚成功
[root@nginx sbin]# curl -I 172.25.254.10
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Fri, 16 Aug 2024 13:07:38 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Fri, 16 Aug 2024 13:02:49 GMT
Connection: keep-alive
ETag: "66bf4df9-267"
Accept-Ranges: bytes

3.3 options

[root@Nginx ~]# nginx -v
nginx version: nginx/1.18.0
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]
Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit #显示版本和编译参数
-t : test configuration and exit #测试配置文件是否异
-T : test configuration, dump it and exit #测试并打印
-q : suppress non-error messages during configuration testing #静默
模式
-s signal : send signal to a master process: stop, quit, reopen, reload #
发送信号,reload信号 会生成新的worker,但master不会重新生成
-p prefix : set prefix path (default: /etc/nginx/) #指定Nginx 目录
-c filename : set configuration file (default: /etc/nginx/nginx.conf) #
配置文件路径
-g directives : set global directives out of configuration file #设置全局指令,注意和配置文件不要同时配置,否则冲突

3.4 Nginx启动文件

#配置nginx服务文件
[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
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
#重新加载服务
[root@Nginx ~]# systemctl daemon-reload
[root@Nginx ~]# systemctl start nginx

四、Nginx 核心配置

  • 配置文件由指令与指令块构成

  • 每条指令以;分号结尾,指令与值之间以空格符号分隔

  • 可以将多条指令放在同一行,用分号分隔即可,但可读性差,不推荐指令块以{ }大括号将多条指令组织在一起,且可以嵌套指令块include语句允许组合多个配置文件以提升可维护性

  • 使用#符号添加注释,提高可读性

  • 使用$符号使用变量

  • 部分指令的参数支持正则表达式

主配置文件结构如下表:

main block:主配置段,即全局配置段,对http,mail都有效

结构名说明
event事件驱动相关的配置
http/https协议相关配置段
mail协议相关配置段
stream服务器相关配置段

4.1 修改全局配置文件 

# 全局配置文件
[root@nginx ~]# vi /usr/local/nginx/conf/nginx.conf
user  nginx;
worker_processes  auto; # 进程数
worker_cpu_affinity 0001 0010 0100 1000; #绑定进程数
....
events {
    worker_connections  100000;   #支持的链接数量,取决于系统能够打开多少文件
}
.....
#gzip  on;
    include "/usr/local/nginx/conf.d/*.conf";  #子配置文件
​
[root@nginx ~]# nginx -s reload
​
#查看系统打开文件的数量是多少
[root@nginx ~]# ulimit -a
#修改系统打开的文件数量
[root@nginx ~]# vim /etc/security/limits.conf
nginx            -        nofile          100000
# 再次查看系统打开文件的数量是多少
[root@nginx ~]# sudo -u nginx ulimit -a

4.2 新建web站点

[root@nginx ~]# mkdir -p /usr/local/nginx/conf.d
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.chuling.org;
    root /data/web/html;
    index index.html;
}
​
[root@nginx ~]# mkdir -p /data/web/html
[root@nginx ~]# echo www.test.org > /data/web/html/index.html
[root@nginx ~]# 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
[root@nginx ~]# nginx -s reload
​
#查看日志
​
#查看错误日志
[root@nginx ~]# tail -f /usr/local/nginx/logs/error.log 
root:

指定web的家目录,在定义location的时候,文件的绝对路径等于 root+location3.2

[root@nginx ~]# mkdir /data/web/test1 -p
​
#当你去访问/test1的时候 我带你访问 /detaweb/test1
[root@nginx ~]# vi /usr/local/nginx/conf.d/vhost.conf 
server {
    listen 80;
    server_name www.test.org;
    root /data/web/html;
    index index.html;
    location /test1/ {
        root /data/web;
    }
}
[root@nginx ~]# echo /data/web/test1 > /data/web/test1/index.html
[root@nginx ~]# 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
[root@nginx ~]# nginx -s reload
alias:

定义路径别名,会把访问的路径重新定义到其指定的路径,文档映射的另一种机制;仅能用于location上下文,此指令使用较少

[root@nginx ~]# cat /usr/local/nginx/conf.d/vhost.conf 
server {
    listen 80;
    server_name www.test.org;
    root /data/web/html;
    index index.html;
    location /test1/ {
        root /data/web;
    }
    location /test2 {
        alias /data/web/test1;
    }
}
[root@nginx ~]# 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
[root@nginx ~]# nginx -s reload

4.3 location

# 语法规则:
location [ = | ~ | ~* | ^~ ] uri { ... }
​
=       #只能精确指定文件,用于标准uri前,需要请求字串与uri精确匹配,大小敏感,如果匹配成功就停止向下匹配并立即处理请求
^~      #用于标准uri前,表示包含正则表达式,并且匹配以指定的正则表达式开头, #对uri的最左边部分做匹配检查,不区分字符大小写
~       #用于标准uri前,表示包含正则表达式,并且区分大小写
~*      #用于标准uri前,表示包含正则表达式,并且不区分大写
不带符号 #匹配起始于此uri的所有的uri
\       #用于标准uri前,表示包含正则表达式并且转义字符。可以将 . * ?等转义为普通符号
​
新版本:1.26
#匹配目录优先级从高到低:
(~* = ~)> 不带符号 > ^~ > =  (=号不支持目录所以排在最后)
#匹配文件优先级从高到低:
= > (~* = ~) > 不带符号 > ^~ 
= 号后面只能跟文件,不能跟目录

#测试简单目录优先级,精确匹配
[root@nginx ~]# mkdir /data/web{1,2}
[root@nginx ~]# mkdir /data/web{1,2}/test
[root@nginx ~]# echo web1 test > /data/web1/test/index.html
[root@nginx ~]# echo web2 test > /data/web2/test/index.html
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.test.org;
    root /data/web/html;
    index index.html;
​
    location /test {
        root /data/web1;
    }
​
    location = /test {
        root /data/web2;
    }
}
​
[root@nginx ~]# nginx -s reload
​
#测试
访问http://172.25.254.10/test/
出现web1 test
#测试模糊匹配
[root@nginx ~]# mkdir -p /data/web1/{test1,tee}
[root@nginx ~]# echo test1 > /data/web1/test1/index.html
[root@nginx ~]# echo tee > /data/web1/tee/index.html
[root@nginx ~]# mkdir -p /data/web1/lee
[root@nginx ~]# echo lee > /data/web1/lee/index.html
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.test.org;
    root /data/web/html;
    index index.html;
​
    location ^~ /t {
        root /data/web1;
    }
}
​
[root@nginx ~]# nginx -s reload
​
#测试
访问http://172.25.254.10/tee/
显示tee
访问http://172.25.254.10/lee/
显示404

4.4 nginx的用户认证

# 创建默认认证文件
[root@nginx ~]#htpasswd -cm /usr/local/nginx/.htpasswd admin
redhat
[root@nginx ~]#htpasswd -m /usr/local/nginx/.htpasswd lee #有这个文件去掉c选项
redhat
​
[root@nginx ~]# mkdir /data/web/lee
[root@nginx ~]# echo lee > /data/web/lee/index.html
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.test.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";
    }
}
[root@nginx ~]# nginx -s reload
​
#测试
访问172.25.254.10/lee
输入用户名和密码,显示lee

4.5 自定义错误页面

[root@nginx ~]# mkdir /data/web/errorpage -p
[root@nginx ~]# echo  error page > /data/web/errorpage/40x.html
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    error_page 404 /40x.html;
    
    location = /40x.html {
        root /data/web/errorpage;
    }
}
[root@nginx ~]# nginx -s reload
​
测试:
[root@node100 ~]# curl www.chuling.org/testa
error page
或者在浏览器访问www.chuling.org/testa
出现error page

4.6 自定义错误日志

[root@nginx ~]# mkdir /var/log/chuling.org
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    error_log /var/log/chuling.org/error.log;
    access_log /var/log/chuling.org/access.log;
}
​
[root@nginx ~]# nginx -s reload
​
#测试
[root@nginx ~]# curl www.chuling.org
[root@nginx ~]# cat /var/log/chuling.org/access.log
[root@nginx ~]# curl www.chuling.org/aaa
[root@nginx ~]# cat /var/log/chuling.org/error.log

4.7 检测文件是否存在

[root@nginx ~]# rm -rf /data/web/html/index.html
[root@nginx ~]# rm -rf /data/web/html/error/
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    error_log /var/log/chuling.org/error.log;
    access_log /var/log/chuling.org/access.log;
    try_files $uri $uri.html $uri/index.html /error/default.html;
​
}
[root@nginx ~]# nginx -s reload;
​
#测试
[root@nginx ~]# curl www.chuling.org
500
​
[root@nginx ~]# mkdir /data/web/html/error
[root@nginx ~]# echo error default > /data/web/html/error/default.html
​
#测试
[root@nginx ~]# curl www.chuling.org
error default

4.8 长链接

[root@nginx ~]# echo www.chuling.org > /data/web/html/index.html
​
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
http {
    keepalive_timeout 65;
    keepalive_requests 2;
}
[root@nginx ~]# nginx -s reload
​
# 长链接测试工具
[root@nginx ~]#dnf install telnet -y
# 测试
[root@nginx ~]#telnet www.chuling.org 80
GET / HTTP/1.1
Host: www.chuling.org
​
Server: nginx/1.24.0
Date: Fri, 16 Aug 2024 06:45:42 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Fri, 16 Aug 2024 06:45:22 GMT
Connection: keep-alive
ETag: "66bef582-12"
Accept-Ranges: bytes
​

4.9 下载服务器配置

#注意:download不需要index.html文件
[root@Nginx ~]# mkdir /data/web/download
[root@Nginx ~]# dd if=/dev/zero of=/data/web/download/leefile bs=1M count=100
​
[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhosts.conf
server {
​
    location /download {
        autoindex on; #自动索引功能
        autoindex_exact_size on; #计算文件确切大小(单位bytes),此为默认值,off只显示大概大小(单位kb、mb、gb)
        autoindex_localtime on; #on表示显示本机时间而非GMT(格林威治)时间,默为为off显示GMT时间
        limit_rate 1024k; #限速,默认不限速 
    }
}
​
#重启Nginx并访问测试下载页面
http://www.chuling.org/download/
​
[root@nginx ~]# wget http://www.chuling.org/download/leefile
--2024-08-16 15:23:25--  http://www.chuling.org/download/leefile
Resolving www.chuling.org (www.chuling.org)... 172.25.254.10
Connecting to www.chulinge.org (www.chuling.org)|172.25.254.10|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 104857600 (100M) [application/octet-stream]
Saving to: ‘leefile’
​
leefile               5%[                   ]   5.00M  1.01MB/s    eta 94s    ^C

五、Nginx高级配置

5.1 nginx的状态页

[root@nginx ~]# vim /usr/local/nginx/conf.d/status.conf
server {
    listen 80;
    server_name status.chuling.org;
    root /data/web/html;
    index index.html;
    
    location /status {
        stub_status;
        allow 172.25.254.1; #指定给谁看
        deny all;
        #auth_basic "login";
        #auth_basic_user_file "/usr/local/nginx/.htpasswd";
    }
}
[root@nginx ~]# nginx -s reload
​
#测试
记得在windows做解析  172.25.254.10 status.chuling.org
​
访问http://status.chuling.org/status
​
Active connections: 1 
server accepts handled requests
 21 21 25 
Reading: 0 Writing: 1 Waiting: 0 
​
[root@nginx ~]# curl status.chuling.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>

5.2 nginx压缩

不会压缩原文件,只是在传输过程中对文件进行压缩。

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
http {
    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;
}
[root@nginx ~]# nginx -s reload
​
[root@nginx ~]# echo hello timinglee >  /data/web/html/small.html
[root@nginx ~]# du -sh /usr/local/nginx/loges/access.log   #查看这个文件多大
[root@nginx ~]# cat /usr/local/nginx/loges/access.log > /data/web/html/big.html
​
​
#测试,查看是否被压缩
[root@nginx ~]# curl --head --compressed 172.25.254.10/small.html
[root@nginx ~]# curl --head --compressed 172.25.254.10/big.html

5.3 nginx变量使用

nginx的变量可以在配置文件中引用,作为功能判断或者日志等场景使用

变量可以分为内置变量和自定义变量

内置变量是由nginx模块自带,通过变量可以获取到众多的与客户端访问相关的值。

常用的配置

$remote_addr;
#存放了客户端的地址,注意是客户端的公网IP
$args;
#变量中存放了URL中的所有参数
#例如:https://search.jd.com/Search?keyword=手机&enc=utf-8
#返回结果为: keyword=手机&enc=utf-8
$is_args
#如果有参数为? 否则为空
$document_root;
#保存了针对当前资源的请求的系统根目录,例如:/webdata/nginx/timinglee.org/lee。
$document_uri;
#保存了当前请求中不包含参数的URI,注意是不包含请求的指令
#比如:http://lee.timinglee.org/var?\id=11111会被定义为/var
#返回结果为:/var
$host;
#存放了请求的host名称
limit_rate 10240;
echo $limit_rate;
#如果nginx服务器使用limit_rate配置了显示网络速率,则会显示,如果没有设置, 则显示0
$remote_port;
#客户端请求Nginx服务器时随机打开的端口,这是每个客户端自己的端口
$remote_user;
#已经经过Auth Basic Module验证的用户名
$request_body_file;
#做反向代理时发给后端服务器的本地资源的名称
$request_method;
#请求资源的方式,GET/PUT/DELETE等
$request_filename;
#当前请求的资源文件的磁盘路径,由root或alias指令与URI请求生成的文件绝对路径,
#如:webdata/nginx/timinglee.org/lee/var/index.html
$request_uri;
#包含请求参数的原始URI,不包含主机名,相当于:$document_uri?$args,
#例如:/main/index.do?id=20190221&partner=search
$scheme;
#请求的协议,例如:http,https,ftp等
$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>
#name为任意请求报文首部字部cookie的key名
$http_<name>
#name为任意请求报文首部字段,表示记录请求报文的首部字段,ame的对应的首部字段名需要为小写,如果有
横线需要替换为下划线
#示例:
echo $http_user_agent;
echo $http_host;
$sent_http_<name>
#name为响应报文的首部字段,name的对应的首部字段名需要为小写,如果有横线需要替换为下划线,此变量有
问题
echo $sent_http_server;
$arg_<name>
#此变量存放了URL中的指定参数,name为请求url中指定的参数
echo $arg_id;
示例:

#nginx的内置变量
​
server {
    listen 80;
    server_name var.chuling.org;
    root /data/web/html;
    index index.html;
​
    location /var {
        default_type text/html;
        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 $http_cookie;
        echo $cookie_key2;
    }
}
​
​
#nginx自定义变量
server {
    listen 80;
    server_name var.chuling.org;
    root /data/web/html;
    index index.html;
​
    location /var {
        default_type text/html;
        set $chuling lee;
        echo $chuling;
    }
}
​
​
# 测试
curl -b "key1=lee,key2=lee1" -u lee:lee var.chuling.org/var?name=lee&&id=6666

六、Nginx Rewrite功能

6.1 if判定

[root@nginx ~]# mkdir /data/web/html/test2
[root@nginx ~]# echo test2 > /data/web/html/test2/index.html
​
[root@nginx ~]# vim /location /test2 {
        if ( !-e $request_filename ){
            echo "$request_filename is not exist";
        }
    }
/local/nginx/conf.d/vars.conf
​
[root@nginx ~]# nginx -s reload
​
#测试
[root@nginx ~]# curl var.chuling.org/test2/index.html 
test2

6.2 break指令

[root@nginx ~]# vim /usr/local/nginx/conf.d/vars.conf
 location /break {
        default_type text/html;
        set $name lee;
        echo $name;
        if ( $http_user_agent = "curl/7.76.1" ){
            break;
        }
        set $id 666;
        echo $id;
    }
[root@nginx ~]# nginx -s reload
​
#测试
[root@nginx ~]# curl  var.chuling.org/break
lee
​
[root@nginx ~]# curl -A "firefox"  var.chuling.org/break
lee
666

6.3 return 指令

[root@nginx ~]# vim /usr/local/nginx/conf.d/vars.conf
   location /return {
        default_type text/html;
        if ( !-e $request_filename){
            return 301 http://www.baidu.com;
        }
        echo "$request_filename is exist";
    }
​
[root@nginx ~]# nginx -s reload
​
​
#测试
#return不存在时
[root@nginx ~]# ll /data/web/html
total 24
-rw-r--r-- 1 root root 15423 Aug 16 16:16 big.html
drwxr-xr-x 2 root root    26 Aug 16 14:34 error
-rw-r--r-- 1 root root    18 Aug 18 11:04 index.html
-rw-r--r-- 1 root root    16 Aug 16 16:15 small.html
drwxr-xr-x 2 root root    24 Aug 18 11:45 test2
drwxr-xr-x 2 root root    24 Aug 18 10:41 var
[root@nginx ~]# curl -I var.chuling.org/return
HTTP/1.1 301 Moved Permanently
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 03:54:09 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://www.baidu.com
​
[root@nginx ~]# mkdir  -p /data/web/html/return
[root@nginx ~]# curl -I var.chuling.org/return
HTTP/1.1 200 OK
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 03:54:33 GMT
Content-Type: text/html
Connection: keep-alive
​
[root@nginx ~]# curl var.chuling.org/return
/data/web/html/return is exist

6.4 rewrite指令

6.4.1 rewrite flag介绍

redirect;
#临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URL给客户端
#由客户端重新发起请求;使用相对路径,或者http://或https://开头,状态码:302
permanent;
#重写完成后以永久重定向方式直接返回重写后生成的新URL给客户端
#由客户端重新发起请求,状态码:301
break;
#重写完成后,停止对当前URL在当前location中后续的其它重写操作
#而后直接跳转至重写规则配置块之后的其它配置,结束循环,建议在location中使用
#适用于一个URL一次重写
last;
#重写完成后,停止对当前URI在当前location中后续的其它重写操作,
#而后对新的URL启动新一轮重写检查,不建议在location中使用
#适用于一个URL多次重写,要注意避免出现超过十次以及URL重写后返回错误的给用户

6.4.2 临时和永久设置

# 前期准备
[root@nginx ~]# vim /usr/local/nginx/conf.d/vars.conf
server {
    listen 80;
    server_name var.chuling.org;
    root /data/web/html;
    index index.html;
    location / {
        root /data/web/var;
        index index.html;
        #rewrite / http://www.chuling.com permanent;
        #rewrite / http://www.chuling.com redirect;
    }
}
[root@nginx ~]# nginx -s reload
[root@nginx ~]# echo var page > /data/web/var/index.html
[root@nginx conf.d]# curl www.chuling.org
www.timinglee.com
[root@nginx conf.d]# curl var.chuling.org
var page
​
​
​
# 永久重定向301
[root@nginx ~]# vim /usr/local/nginx/conf.d/vars.conf
location / {
        root /data/web/var;
        index index.html;
        rewrite / http://www.chuling.com permanent;
        #rewrite / http://www.chuling.com redirect;
    }
[root@nginx ~]# nginx -s reload
​
[root@nginx conf.d]# curl -I var.chuling.org
HTTP/1.1 301 Moved Permanently
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 12:13:09 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://www.chuling.com
​
#临时重定向302
[root@nginx ~]# vim /usr/local/nginx/conf.d/vars.conf
location / {
        root /data/web/var;
        index index.html;
        #rewrite / http://www.chuling.com permanent;
        rewrite / http://www.chuling.com redirect;
    }
[root@nginx ~]# nginx -s reload
​
[root@nginx conf.d]# curl -I var.chuling.org
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 12:13:41 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: http://www.chuling.com

6.4.3 break和last

[root@nginx ~]# mkdir  /data/web/html/{test1,test2,break,last} -p[root@nginx ~]# echo test1 > /data/web/html/test1/index.html
[root@nginx ~]# echo test2 > /data/web/html/test2/index.html
[root@nginx ~]# echo last > /data/web/html/last/index.html
[root@nginx ~]# echo break > /data/web/html/break/index.html
[root@nginx ~]# vim /usr/local/nginx/conf.d/vars.conf
server {
    listen 80;
    server_name var.chuling.org;
    root /data/web/html;
    index index.html;
​
    location /break {
        root /data/web/html;
        rewrite ^/break/(.*) /test1/$1 break;
        rewrite ^/test1/(.*) /test1/$2;
    }
    location /last {
        root /data/web/html;
        rewrite ^/last/(.*) /test1/$1 last;
        rewrite ^/test1/(.*) /test2/$1;
    }
    location /test1 {
        default_type test/html;
        return 666 "test1 hahahahahaha ";
    }
    location /test2 {
        root /data/web/html;
    }
}
​
[root@nginx ~]# nginx -s reload
​
#测试
[root@nginx ~]# curl var.chuling.org/break/index.html
test1
[root@nginx ~]# curl var.chuling.org/last/index.html
test1 hahahahahaha

6.4.4 全站加密

[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/chuling.org.key -x509 -days 365 -out /usr/local/nginx/certs/chuling.org.crt
[root@nginx ~]# vim /usr/local/nginx/conf.d/vars.conf
server {
    listen 80;
    listen 443 ssl;
    server_name www.chuling.org;
    root /data/web/html;
    index index.html;
    ssl_certificate /usr/local/nginx/certs/chuling.org.crt;
    ssl_certificate_key /usr/local/nginx/certs/chuling.org.key;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;
​
    location / {
        if ( $scheme = http ){
            rewrite /(.*) https://$host/$1 redirect;
        }
        if ( !-e $request_filename ){
            rewrite /(.*) https://$host/index.html redirect;      #如果$request_filename不存在,则触发index.html
        }
    }
}
​
​
[root@nginx ~]# nginx -s reload
[root@nginx conf.d]# curl -I www.chuling.org
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.26.1
Date: Sun, 18 Aug 2024 12:53:40 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: https://www.chuling.org

6.4.5 防盗链

#盗链的实现
[root@nginx ~]# mkdir -p /data/web/html/images
[root@nginx ~]# mv daolian.png /data/web/html
[root@nginx ~]# mv lee.png /data/web/html/images/
​
#node1
[root@node1 ~]# dnf install httpd -y
[root@node1 ~]# cd /var/www/html
[root@node1 html]# vim index.html
<html>
<head>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<title>盗链</title>
</head>
<body>
<img src="http://www.chuling.org/images/lee.png" >
<h1 style="color:red">梅兰竹菊</h1>
<p><a href=http://www.chuling.org>点击查看详情</a>你喜欢的都在这里</p>
</body>
</html>
# 防盗链
[root@nginx ~]# vim /usr/local/nginx/conf.d/vars.conf
server {
    listen 80;
    listen 443 ssl;
    server_name www.chuling.org;
    root /data/web/html;
    index index.html;
    ssl_certificate /usr/local/nginx/certs/chuling.org.crt;
    ssl_certificate_key /usr/local/nginx/certs/chuling.org.key;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;
​
    location /images {
        valid_referers none blocked server_names *.chuling.org ~/.baidu/.;
        if ( $invalid_referer ) {
            return 404;
        }
    }
}
[root@nginx ~]# nginx -s reload

七、反向代理

7.1 http反向代理

7.1.1 指定location实现反向代理

1.1指定location实现反向代理
# node1、node2
[root@node1 ~]# dnf install httpd -y
[root@node1 ~]# systemctl enable --now httpd
[root@node1 ~]# echo 172.25.254.110 > /var/www/html/index.html
[root@node2 ~]# systemctl enable --now httpd
[root@node2 ~]# echo 172.25.254.120 > /var/www/html/index.html
[root@node2 ~]# vim /etc/httpd/conf/httpd.conf
Listen 8080
[root@node2 ~]# systemctl restart httpd
​
​
# 测试
[root@nginx ~]# curl 172.25.254.110
172.25.254.110
[root@nginx ~]# curl 172.25.254.120
172.25.254.120
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
server {
    listen 80;
    server_name www.chuling.org;
​
    location / {
        proxy_pass http://172.25.254.110:80;
    }
​
    location /static {
        proxy_pass http://172.25.254.120:8080;
    }
}
​
[root@nginx ~]# nginx -s reload
​
#测试
[root@nginx ~]# curl www.chuling.org
172.25.254.10
[root@nginx ~]# curl www.chuling.org/static/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body></html>
(node2没有static目录)
​
​
[root@node2 ~]# mkdir -p /var/www/html/static
[root@node2 ~]# echo static 172.25.254.120 > /var/www/html/static/index.html
​
#测试
[root@nginx ~]# curl www.chuling.org
172.25.254.110
[root@nginx ~]# curl www.chuling.org/static/
static 172.25.254.120

7.1.2 缓存功能

[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
#gzip  on;    
proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2:2 keys_zone=proxycache:20m inactive=120s max_size=1g;
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
location /static {
        proxy_pass http://172.25.254.120:8080;
        proxy_cache proxycache;
        proxy_cache_key $request_uri;
        proxy_cache_valid 200 302 301 10m;
        proxy_cache_valid any 1m;
    }
[root@nginx ~]# nginx -s reload
[root@node1 ~]# vim /etc/hosts
​
172.25.254.10   node1.chuling.org www.chuling.org
​
#测试
[root@node1 ~]# ab -n1000 -c100 http://www.chuling.org/static/index.html
Requests per second:    8908.92 [#/sec] (mean) (未做缓存)
Requests per second:    12933.77 [#/sec] (mean)

7.2 http反向代理负载均衡

7.2.1 示例:后端多台web服务器

172.25.254.10 #Nginx 代理服务器
172.25.254.110 #后端web A,Apache部署
172.25.254.120 #后端web B,Apache部署
# 部署后端 Apache服务器
[root@node1 ~]# dnf install httpd -y
[root@node1 ~]# echo "172.25.254.110" > /var/www/html/index.html
[root@node1 ~]# systemctl enable --now httpd
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
upstream webcluster {
    server 172.25.254.110:80 fail_timeout=15s max_fails=3;
    server 172.25.254.120:8080 fail_timeout=15s max_fails=3;
    server 172.25.254.10:80 backup;
}
​
server {
    listen 80;
    server_name www.chuling.org;
​
    location / {
        proxy_pass http://webcluster;
    }
​
}
​
[root@nginx ~]# nginx -s reload
​
#测试
[root@nginx ~]# curl www.chuling.org
172.25.254.110
[root@nginx ~]# curl www.chuling.org
172.25.254.120
upstream webcluster {
    ip_hash;
    server 172.25.254.110:80 fail_timeout=15s max_fails=3;
    server 172.25.254.120:8080 fail_timeout=15s max_fails=3;
    #server 172.25.254.10:80 backup;
}
[root@nginx ~]# curl www.chuling.org
172.25.254.110
upstream webcluster {
    #ip_hash;
    hash $request_uri consistent;
    server 172.25.254.110:80 fail_timeout=15s max_fails=3;
    server 172.25.254.120:8080 fail_timeout=15s max_fails=3;
    #server 172.25.254.10:80 backup;
}
[root@nginx ~]# curl www.timinglee.org
172.25.254.120

# 基于Cookie 实现会话绑定
upstream webcluster {
    #ip_hash;
    #hash $request_uri consistent;
    hash $cookie_lee;
    server 172.25.254.110:80 fail_timeout=15s max_fails=3;
    server 172.25.254.120:8080 fail_timeout=15s max_fails=3;
    #server 172.25.254.10:80 backup;
}
​
​
[root@nginx ~]# curl www.chulinge.org
172.25.254.110
[root@nginx ~]# curl www.chuling.org
172.25.254.120
[root@nginx ~]# curl -b "lee=1" www.chuling.org
172.25.254.110
[root@nginx ~]# curl -b "lee=1" www.chuling.org
172.25.254.110

7.3 Nginx四层负载均衡

7.3.1 DNS

# 环境 node1\node2
[root@node1 ~]# dnf install bind -y
[root@node1 ~]# vim /etc/named.conf 
//      listen-on port 53 { 127.0.0.1; };
//      listen-on-v6 port 53 { ::1; };
//      allow-query     { localhost; };
​
dnssec-validation no;
[root@node1 ~]# vim /etc/named.rfc1912.zones 
zone "timinglee.org" IN {
        type master;
        file "chuling.org.zone";
        allow-update { none; };
};
​
[root@node1 ~]# cd /var/named
[root@node1 named]# cp named.localhost chuling.org.zone -p
[root@node1 named]# vim chuling.org.zone
$TTL 1D
@       IN SOA  ns.chuling.org root.chuling.org. (
                                        0       ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
        NS      ns.chuling.org.
NS      A       172.25.254.10
www     A       172.25.254.10
​
[root@node1 named]# systemctl start named
[root@node1 named]# dig www.chuling.org @172.25.254.110
[root@node1 named]# scp -p /etc/named.{conf,rfc1912.zones} root@172.25.254.120:/etc/
[root@node1 named]# scp -p /var/named/chuling.org.zone root@172.25.254.20:/var/named/chuling.org.zone
[root@node2 named]# chgrp named chuling.org.zone 
[root@node2 named]# systemctl restart named
[root@node2 named]# dig www.chuling.org @172.25.254.120
[root@nginx ~]# vim /usr/local/nginx/conf/nginx.conf
include "/usr/local/nginx/tcpconf.d/*.conf";
[root@nginx ~]# mkdir -p /usr/local/nginx/tcpconf.d
[root@nginx ~]# vim /usr/local/nginx/tcpconf.d/dns.conf 
stream {
    upstream dns {
        server 172.25.254.110:53 fail_timeout=15s max_fails=3;
        server 172.25.254.120:53 fail_timeout=15s max_fails=3;
    }
​
    server {
        listen 53 udp reuseport;
        proxy_timeout 20s;
        proxy_pass dns;
    }
}
[root@nginx ~]# nginx -s reload
​
​
#测试
[root@nginx ~]# dig www.chuling.org @172.25.254.10
​
; <<>> DiG 9.16.23-RH <<>> www.chuling.org @172.25.254.10
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 28013
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
​
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: b7555ae27da74d590100000066c216da67395c8bb9e26570 (good)
;; QUESTION SECTION:
;www.chuling.org.     IN  A
​
;; ANSWER SECTION:
www.chuling.org.  86400   IN  A   172.25.254.110
​
[root@nginx ~]# dig www.chuling.org @172.25.254.10
; <<>> DiG 9.16.23-RH <<>> www.chuling.org @172.25.254.10
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 56262
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
​
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: 2a17fdf418eb234d0100000066c216e6f94e6503ec327810 (good)
;; QUESTION SECTION:
;www.chuling.org.     IN  A
​
;; ANSWER SECTION:
www.chuling.org.  86400   IN  A   172.25.254.20

7.3.2 数据库

# node1\node2
[root@node1 ~]# dnf install mariadb-server -y
[root@node1 ~]# vim /etc/my.cnf.d/mariadb-server.cnf
[mysqld]
server-id=10
[root@node1 ~]# systemctl start mariadb.service 
# 授权
MariaDB [(none)]> CREATE USER lee@'%' identified by 'lee';
Query OK, 0 rows affected (0.002 sec)
​
MariaDB [(none)]> GRANT ALL ON *.* to lee@'%';
Query OK, 0 rows affected (0.001 sec)
[root@nginx ~]# vim /usr/local/nginx/tcpconf.d/dns.conf 
stream {
    upstream dns {
        server 172.25.254.110:53 fail_timeout=15s max_fails=3;
        server 172.25.254.120:53 fail_timeout=15s max_fails=3;
    }
    upstream mysql {
        server 172.25.254.110:3306 fail_timeout=15s max_fails=3;
        server 172.25.254.120:3306 fail_timeout=15s max_fails=3;
​
    }
​
    server {
        listen 3306;
        proxy_timeout 60s;
        proxy_pass mysql;
    }
​
    server {
        listen 53 udp reuseport;
        proxy_timeout 20s;
        proxy_pass dns;
    }
}
[root@nginx ~]# nginx -s reload
[root@nginx ~]# dnf install mariadb -y #下载数据库的客户端
​
​
# 测试
[root@nginx ~]# mysql -u lee -p -h 172.25.254.10
lee
MariaDB [(none)]> SELECT @@server_id
    -> ;
+-------------+
| @@server_id |
+-------------+
|          20 |
+-------------+
1 row in set (0.001 sec)
[root@nginx ~]# mysql -u lee -p -h 172.25.254.10
lee
MariaDB [(none)]> SELECT @@server_id;
+-------------+
| @@server_id |
+-------------+
|          10 |
+-------------+
1 row in set (0.002 sec)

7.4 实现FastCGI

        CGI协议虽然解决了语言解析器和 Web Server 之间通讯的问题,但是它的效率很低,因为 Web Server每收到一个请求都会创建一个CGI进程,PHP解析器都会解析php.ini文件,初始化环境,请求结束的时候再关闭进程,对于每一个创建的CGI进程都会执行这些操作,所以效率很低,而FastCGI是用来提高CGI性能的,FastCGI每次处理完请求之后不会关闭掉进程,而是保留这个进程,使这个进程可以处理多个请求。这样的话每个请求都不用再重新创建一个进程了,大大提升了处理效率

        PHP-FPM(FastCGI Process Manager:

FastCGI进程管理器)是一个实现了Fastcgi的程序,并且提供进程管理的功能。

进程包括master进程和worker进程。master进程只有一个,负责监听端口,接受来自web server

的请求。

worker进程一般会有多个,每个进程中会嵌入一个PHP解析器,进行PHP代码的处理。

7.4.1 实例:Nginx和php-fpm在同一服务器

# nginx源码安装
[root@nginx ~]# systemctl stop nginx
[root@nginx ~]# cd /usr/local/
[root@nginx local]# rm -rf /usr/local/nginx/
[root@nginx ~]# tar zxf srcache-nginx-module-0.33.tar.gz 
[root@nginx ~]# tar zxf memc-nginx-module-0.20.tar.gz 
[root@nginx ~]# cd nginx-1.26.1/
./configure --prefix=/usr/local/nginx --add-module=/root/echo-nginx-module-0.63 --add-module=/root/memc-nginx-module-0.20 --add-module=/root/srcache-nginx-module-0.33 --user=nginx --group=nginx --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-stream --with-stream_ssl_module --with-stream_realip_module --with-pcre
[root@nginx nginx-1.26.1]# systemctl start nginx
[root@nginx nginx-1.26.1]# nginx -V
[root@nginx nginx-1.26.1]# ps -aux | grep nginx
root        5493  0.0  0.0   9908   924 ?        Ss   10:43   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx       5494  0.0  0.1  13804  4708 ?        S    10:43   0:00 nginx: worker process
root        5509  0.0  0.0 221664  2252 pts/0    S+   10:44   0:00 grep --color=auto nginx
​
# php源码安装
[root@nginx ~]# tar zxf php-8.3.9.tar.gz 
[root@nginx ~]# cd php-8.3.9/
[root@nginx php-8.3.9]# yum install -y bzip2 systemd-devel libxml2-devel sqlite-devel libpng-devel libcurl-devel
[root@nginx ~]# https://mirrors.aliyun.com/rockylinux/9.4/devel/x86_64/kickstart/Packages/o/oniguruma-devel-6.9.6-1.el9.5.x86_64.rpm  
[root@nginx ~]# dnf install oniguruma-devel-6.9.6-1.el9.5.x86_64.rpm
[root@nginx php-8.3.9]# ./configure --prefix=/usr/local/php --enable-fpm --with-fpm-user=nginx --with-fpm-group=nginx --with-curl --with-iconv --with-mhash --with-zlib --with-openssl --enable-mysqlnd --with-mysqli --with-pdo-mysql --disable-debug --enable-soap --enable-sockets --enable-xml --enable-ftp --enable-gd --enable-exif --enable-mbstring --enable-bcmath --with-fpm-systemd
[root@nginx php-8.3.9]# ls (有makefile)
[root@nginx php-8.3.9]# make && make install

# php相关配置优化
[root@Nginx ~]# cd /usr/local/php/etc
[root@nginx etc]# ls
php-fpm.conf.default  php-fpm.d
[root@Nginx etc]# cp -p php-fpm.conf.default php-fpm.conf
[root@Nginx etc]# vim php-fpm.conf
#去掉注释
pid = run/php-fpm.pid #指定pid文件存放位置
[root@Nginx etc]# cd php-fpm.d/
[root@nginx php-fpm.d]# ls
www.conf.default
[root@Nginx php-fpm.d]# cp -p www.conf.default www.conf
​
#生成主配置文件
[root@Nginx php-fpm.d]# cd /root/php-8.3.9/
[root@Nginx php-8.3.9]# cp php.ini-production /usr/local/php/etc/php.ini
[root@Nginx ~]# vim /usr/local/php/etc/php.ini
[Date]
; Defines the default timezone used by the date functions
; https://php.net/date.timezone
date.timezone = Asia/Shanghai #修改时区
​
# 查找时区
[root@nginx ~]# timedatectl list-timezones | grep Asia/Shanghai
Asia/Shanghai
​
​
#生成启动文件
[root@Nginx ~]# cd /root/php-8.3.9/sapi/fpm
[root@Nginx fpm]# cp php-fpm.service /lib/systemd/system/
[root@nginx fpm]# vim /lib/systemd/system/php-fpm.service 
# Mounts the /usr, /boot, and /etc directories read-only for processes invoked by this unit.
#ProtectSystem=full #注释该内容
[root@Nginx fpm]# systemctl daemon-reload
[root@Nginx fpm]# systemctl start php-fpm.service
[root@Nginx fpm]# netstat -antlupe | grep php
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN      0          132259     158979/php-fpm: mas 

# php测试页面
[root@nginx ~]# mkdir -p /data/web/php
[root@nginx ~]# cd /usr/local/php/bin/
[root@nginx bin]# vim ~/.bash_
.bash_history  .bash_logout   .bash_profile  
[root@nginx bin]# vim ~/.bash_profile 
export PATH=$PATH:/usr/local/nginx/sbin:/usr/local/php/bin:/usr/local/php/sbin
[root@nginx bin]# source ~/.bash_profile 
[root@nginx bin]# cd /data/web/php/
[root@nginx php]# vim index.php
[root@nginx php]# cat index.php 
<?php
    phpinfo();
?>
[root@nginx conf]# cd /usr/local/nginx/
[root@nginx nginx]# mkdir conf.d
[root@nginx nginx]# vim conf/nginx.conf
include "/usr/local/nginx/conf.d/*.conf";
​
{
[root@nginx ~]# vim /usr/local/php/etc/php-fpm.d/www.conf
listen = 127.0.0.1:9000
}
[root@nginx nginx]# vim conf.d/vhost.conf
server {
    listen 80;
    server_name www.chuling.org;
    root /data/web/html;
    index index.html;
​
    location ~\.php$ {
        root /data/web/php;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi.conf;
    }
}
[root@nginx nginx]# nginx -t
[root@nginx nginx]# nginx -s reload
​
或者
​
[root@nginx ~]# cat /usr/local/nginx/conf.d/vhosts.conf 
fastcgi_pass 172.25.254.10:9000;
[root@nginx nginx]# nginx -s reload
​
[root@nginx ~]# vim /usr/local/php/etc/php-fpm.d/www.conf
listen = 0.0.0.0:9000
[root@nginx ~]# cd /root/php-8.3.9/sapi/fpm/
[root@nginx fpm]# systemctl daemon-reload
[root@nginx fpm]# systemctl start php-fpm.service

7.4.2 实例:php的动态扩展模块

#安装memcache模块
[root@Nginx ~]# tar zxf memcache-8.2.tgz
[root@Nginx ~]# cd memcache-8.2/
[root@Nginx memcache-8.2]# yum install autoconf
[root@Nginx memcache-8.2]# phpize
[root@Nginx memcache-8.2]# ./configure && make && make install
[root@Nginx memcache-8.2]# ls /usr/local/php/lib/php/extensions/no-debug-non-zts-20230831/memcache.so opcache.so

#复制测试文件到nginx发布目录中
[root@Nginx ~]# cd memcache-8.2/
[root@Nginx memcache-8.2]# ls
[root@Nginx memcache-8.2]# cp example.php memcache.php /data/web/php/
[root@Nginx ~]# vim /data/web/php/memcache.php
define('ADMIN_USERNAME','admin'); // Admin Username
define('ADMIN_PASSWORD','lee'); // Admin Password
define('GRAPH_SIZE',200);
define('MAX_ITEM_DUMP',50);
$MEMCACHE_SERVERS[] = '127.0.0.1:11211'; // add more as an array
#$MEMCACHE_SERVERS[] = 'mymemcache-server2:11211'; // add more as an array

# 配置php加载memcache模块
[root@Nginx ~]# vim /usr/local/php/etc/php.ini
;extension=zip
extension=memcache
;zend_extension=opcache
[root@Nginx ~]# systemctl reload php-fpm
# 因为没有指定路劲,所以要移动到默认路径
[root@Nginx ~]# cp /usr/local/php/etc/php.ini /usr/local/php/lib/
[root@Nginx no-debug-non-zts-20230831]# php -m | grep mem
memcache

# 部署memcached
[root@Nginx ~]# yum install memcached -y
[root@Nginx ~]# systemctl enable --now memcached.service
[root@Nginx ~]# netstat -antlupe | grep memcache
tcp 0 0 127.0.0.1:11211 0.0.0.0:* LISTEN
976 1037243 186762/memcached
[root@Nginx ~]# cat /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS="-l 127.0.0.1,::1

# 测试
访问 http://www.chuling.org/example.php 不断刷新
访问 http://www.chuling.org/memcache.php 查看命中效果


#性能对比
[root@nginx ~]# ab -n1000 -c10 http://www.chuling.org/index.php
Failed requests:        111     #访问1000次失败111次,未作memcache时失败900多次

7.4.3 php高速缓存

#编辑nginx配置
[root@Nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
upstream memcache {
    server 127.0.0.1:11211;
    keepalive 512;
}
server {
    listen 80;
    server_name www.chuling.org;
    root /data/web/html;
    index index.html;
    location /memc {
        internal;
        memc_connect_timeout 100ms;
        memc_send_timeout 100ms;
        memc_read_timeout 100ms;
        set $memc_key $query_string; #使用内置变量$query_string来作为key
        set $memc_exptime 300; #缓存失效时间300秒
        memc_pass memcache;
    }
    location ~ \.php$ {
        root /data/web/php;
        set $key $uri$args; #设定key的值
        srcache_fetch GET /memc $key; #检测mem中是否有要访问的php
        srcache_store PUT /memc $key; #缓存为加载的php数据
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi.conf;
    }
}
[root@Nginx ~]# nginx -s reload
​
#测试
[root@nginx ~]# ab -n1000 -c10 http://www.chuling.org/index.php
Failed requests:        0

八、nginx的二次开发

8.1 编译安装 openresty

#nginx配置
[root@nginx ~]# systemctl stop nginx
[root@nginx ~]# netstate -antupe | grep nginx
[root@nginx ~]# killall -9 nginx
[root@nginx ~]# netstate -antupe | grep nginx
​#编译等相关配置
[root@Nginx ~]#dnf -yq install gcc pcre-devel openssl-devel perl
[root@Nginx ~]#useradd -r -s /sbin/nologin nginx
[root@Nginx ~]#cd /usr/local/src
[root@Nginx src]#wget https://openresty.org/download/openresty-1.17.8.2.tar.gz
[root@Nginx src]#tar xf openresty-1.17.8.2.tar.gz
[root@Nginx src]#cd openresty-1.17.8.2/
[root@Nginx openresty-1.17.8.2]#./configure \
--prefix=/apps/openresty \
--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
[root@Nginx openresty-1.17.8.2]#make && make install
[root@Nginx openresty-1.17.8.2]#ln -s /apps/openresty/bin/* /usr/bin/
[root@Nginx openresty-1.17.8.2]#openresty -v
nginx version: openresty/1.17.8.2
[root@Nginx openresty-1.17.8.2]#openresty
[root@Nginx openresty-1.17.8.2]#ps -ef |grep nginx

  • 25
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值