企业高性能web服务器---nginx理论+实验

nginx编译安装

编译器介绍

源码安装需要提前准备标准的编译器,GCC的全称是(GNU Compiler collection),其有GNU开发,并以
GPL即LGPL许可,是自由的类UNIX即苹果电脑Mac OS X操作系统的标准编译器,因为GCC原本只能处理C语
言,所以原名为GNU C语言编译器,后来得到快速发展,可以处理C++,Fortran,pascal,objective C,
java以及Ada等其他语言,此外还需要Automake工具,以完成自动创建Makefile的工作,Nginx的一些模块
需要依赖第三方库,比如: pcre(支持rewrite),zlib(支持gzip模块)和openssl(支持ssl模块)
等。

编译安装 Nginx

官方源码包下载地址

https://nginx.org/en/download.html

安装编译器

[root@Nginx ~]# dnf install gcc pcre-devel zlib-devel openssl-devel -y

下载nginx

[root@Nginx ~]# wget https://nginx.org/download/nginx-1.24.0.tar.gz

解压

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

创建一个名为nginx的用户账户,该账户被设计为仅用于运行Web服务器服务(如Nginx),而不允许用户登录系统

[root@Nginx ~]# useradd  -s /sbin/nologin -M nginx

切换到 Nginx 源码目录

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

配置nginx

[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 \          
--with-stream_realip_module        
​
这个命令运行 Nginx 的 configure 脚本,以设置编译时的各种选项。这些选项包括:
​
--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:启用通过 HTTP 头部修改客户端 IP 地址的功能。
--with-http_stub_status_module:启用状态页面,用于监控 Nginx 的运行状态。
--with-http_gzip_static_module:启用预压缩文件的 gzip 支持。
--with-pcre:启用 PCRE 正则表达式库的支持(注意:Nginx 1.11.0 及更高版本通常会自动检测并启用 PCRE)。
--with-stream、--with-stream_ssl_module 和 --with-stream_realip_module:启用 TCP/UDP 代理(stream)模块及其 SSL 和 IP 透传功能。
​

编译和安装 Nginx

[root@Nginx nginx-1.24.0]# make && make install
 
这个命令首先运行 make 来编译 Nginx,然后使用 && 运算符(表示如果前一个命令成功执行,则执行下一个命令)运行 make install 来安装 Nginx。安装完成后,Nginx 将被放置在前面通过 --prefix 选项指定的目录中。

编译参数

编辑 Bash 配置文件---修改 PATH 环境变量
[root@Nginx ~]# vim ~/.bash_profile
export PATH=$PATH:/usr/local/nginx/sbin
应用更改
[root@Nginx ~]# source ~/.bash_profile

平滑升级和回滚案例

平滑

下载nginx

wget https://nginx.org/download/nginx-1.26.2.tar.gz

下载安装这个模块

echo-nginx-module-0.63.tar.gz

解压

tar zxf nginx-1.26.2.tar.gz

切换到 Nginx 源码目录

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

开始编译新版本

[root@nginx1 nginx-1.26.2]# ./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_gzip_static_module --with-http_stub_status_module --with-pcre --with-stream --with-stream_ssl_module
​
 #只要make无需要make install
[root@nginx1 nginx-1.26.2]# make
​
./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@nginx1 sbin]# curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.24.0
Date: Thu, 15 Aug 2024 12:54:32 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Thu, 15 Aug 2024 12:53:23 GMT
Connection: keep-alive
ETag: "66bdfa43-267"
Accept-Ranges: bytes
​

#查看两个版本

[root@nginx1 nginx-1.26.2]# ll objs/nginx /usr/local/nginx/sbin/nginx
-rwxr-xr-x 1 root root 6150896  8月 15 16:39 objs/nginx
-rwxr-xr-x 1 root root 5679504  8月 15 13:11 /usr/local/nginx/sbin/nginx

#把之前的旧版的nginx命令备份

[root@nginx1 ~]# cd /usr/local/nginx/sbin/
[root@nginx1 sbin]# cp nginx nginx.old

#把新版本的nginx命令复制过去

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

查看

[root@nginx1 sbin]# ll
总用量 11556
-rwxr-xr-x 1 root root 6150896  8月 15 20:57 nginx
-rwxr-xr-x 1 root root 5679504  8月 15 20:55 nginx.old
​

查找与Nginx相关的所有进程信息

[root@nginx1 sbin]# ps aux | grep nginx
avahi        875  0.0  0.1  15468  6384 ?        Ss   19:44   0:00 avahi-daemon: running [nginx1.local]
root       10384  0.0  0.0   9840   928 ?        Ss   20:54   0:00 nginx: master process nginx
nginx      10385  0.0  0.1  13700  4728 ?        S    20:54   0:00 nginx: worker process
root       10427  0.0  0.0 221816  2484 pts/1    S+   20:58   0:00 grep --color=auto nginx
[root@nginx1 sbin]# kill -USR2 10384
​
#USR2 平滑升级可执行程序,将存储有旧版本主进程PID的文件重命名为nginx.pid.oldbin,并启动新的
nginx
 #此时两个master的进程都在运行,只是旧的master不在监听,由新的master监听80
 #此时Nginx开启一个新的master进程,这个master进程会生成新的worker进程,这就是升级后的Nginx进
程,此时老的进程不会自动退出,但是当接收到新的请求不作处理而是交给新的进程处理。
[root@nginx1 sbin]# ps aux | grep nginx 
avahi        875  0.0  0.1  15468  6384 ?        Ss   19:44   0:00 avahi-daemon: running [nginx1.local]
root       10384  0.0  0.0   9840  2744 ?        Ss   20:54   0:00 nginx: master process nginx
nginx      10385  0.0  0.1  13700  4728 ?        S    20:54   0:00 nginx: worker process
root       10431  0.0  0.1   9864  5972 ?        S    20:59   0:00 nginx: master process nginx
nginx      10432  0.0  0.1  13724  4824 ?        S    20:59   0:00 nginx: worker process
root       10437  0.0  0.0 221816  2480 pts/1    S+   21:00   0:00 grep --color=auto nginx

#检测版本信息

[root@nginx1 sbin]# curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.24.0   #依旧是旧版本
Date: Thu, 15 Aug 2024 12:54:32 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Thu, 15 Aug 2024 12:53:23 GMT
Connection: keep-alive
ETag: "66bdfa43-267"
Accept-Ranges: bytes

#回收旧版本

[root@nginx1 sbin]# kill -WINCH 10384  #回收旧版本
[root@nginx1 sbin]# ps aux | grep nginx 
avahi        875  0.0  0.1  15468  6384 ?        Ss   19:44   0:00 avahi-daemon: running [nginx1.local]
root       10384  0.0  0.0   9840  2744 ?        Ss   20:54   0:00 nginx: master process nginx
root       10431  0.0  0.1   9864  5972 ?        S    20:59   0:00 nginx: master process nginx
nginx      10432  0.0  0.1  13724  5352 ?        S    20:59   0:00 nginx: worker process
root       10475  0.0  0.0 221816  2424 pts/1    S+   21:07   0:00 grep --color=auto nginx
​#检测版本信息
[root@nginx1 sbin]# curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.26.2    #新版本生效
Date: Thu, 15 Aug 2024 13:08:21 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Thu, 15 Aug 2024 12:53:23 GMT
Connection: keep-alive
ETag: "66bdfa43-267"
Accept-Ranges: bytes
​

回滚

#如果升级的版本发现问题需要回滚,可以重新拉起旧版本的worker

[root@nginx1 sbin]# cp nginx nginx.new
[root@nginx1 sbin]# ls
nginx  nginx.new  nginx.old
[root@nginx1 sbin]# \cp -f nginx.old nginx
[root@nginx1 sbin]# ls
nginx  nginx.new  nginx.old
​
[root@nginx1 sbin]# kill -HUP 10384
​
[root@nginx1 sbin]# ps aux | grep nginx 
avahi        875  0.0  0.1  15468  6384 ?        Ss   19:44   0:00 avahi-daemon: running [nginx1.local]
root       10384  0.0  0.0   9840  2744 ?        Ss   20:54   0:00 nginx: master process nginx
root       10431  0.0  0.1   9864  5972 ?        S    20:59   0:00 nginx: master process nginx
nginx      10432  0.0  0.1  13724  5352 ?        S    20:59   0:00 nginx: worker process
nginx      10479  0.0  0.1  13700  4728 ?        S    21:09   0:00 nginx: worker process
root       10481  0.0  0.0 221816  2308 pts/1    S+   21:09   0:00 grep --color=auto nginx
​
[root@nginx1 sbin]# kill -WINCH 10431
​
[root@nginx1 sbin]# ps aux | grep nginx 
avahi        875  0.0  0.1  15468  6384 ?        Ss   19:44   0:00 avahi-daemon: running [nginx1.local]
root       10384  0.0  0.0   9840  2744 ?        Ss   20:54   0:00 nginx: master process nginx
root       10431  0.0  0.1   9864  6424 ?        S    20:59   0:00 nginx: master process nginx
nginx      10479  0.0  0.1  13700  4728 ?        S    21:09   0:00 nginx: worker process
root       10485  0.0  0.0 221816  2488 pts/1    S+   21:11   0:00 grep --color=auto nginx
​
[root@nginx1 sbin]# curl -I 172.25.254.100
HTTP/1.1 200 OK
Server: nginx/1.24.0   #版本回滚完成
Date: Thu, 15 Aug 2024 13:12:14 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Thu, 15 Aug 2024 12:53:23 GMT
Connection: keep-alive
ETag: "66bdfa43-267"
Accept-Ranges: bytes

nginx命令常用参数 

nginx -V 查看版本级详细配置参数

nginx -t 检测配置文件是否有问题

nginx -T 检测并打印

nginx -q 打开静默模式

nginx -s reload 发送信号,reload信号 会生成新的worker,但master不会重新生成

nginx -g 设置全局指令,注意和 配置文件不要同时配置,否则冲突

如下:

就可以用这个命令了

如下:一下就开启了6个worker_process

如果不注释运行nginx -g "worker_processes 6;"就会出错

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   #在启动nginx服务是这些都会被自动激                                                                               #活
Wants=network-online.target                                          #期望这个服务在开启的时候是激活的
​
[Service]
Type=forking                                    #类型
PIDFile=/usr/local/nginx/logs/nginx.pid         #pid位置
ExecStartPre=/usr/local/nginx/sbin/nginx -t     #真实命令启动之前要先用nginx -t命令检测
ExecStart=/usr/local/nginx/sbin/nginx           #真实启动的命令
ExecReload=/usr/local/nginx/sbin/nginx -s reload #执行reload
ExecStop=/bin/kill -s QUIT $MAINPID             #执行stop
PrivateTmp=true                                 
​
[Install]
WantedBy=multi-user.target
​
推出保存
使其生效[root@Nginx ~]# systemctl daemon-reload
       [root@Nginx ~]# systemctl enable --now  nginx.service 
​

查看nginx pid的位置

Nginx 核心配置详解

nginx全局配置参数优化调整

worker_processes设置为auto时,Nginx会自动检测服务器的CPU核心数,并尝试将工作进程的数量设置为与CPU核心数相同

实现 nginx 的高并发配置

首先安装ab工具

[root@nginx1 logs]# dnf install httpd-tools -y

测试 :[root@nginx1 logs]# ab -n 10000 -c 5000 http://172.25.254.100/index.html

#默认配置不支持高并发,会出现以下错误日志

#修改配置

[root@nginx1 ~]# vim /etc/security/limits.conf

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

重新启动--[root@nginx1 ~]# nginx -s reload

再测试:[root@nginx1 logs]# ab -n 10000 -c 500 http://172.25.254.100/index.html


新建一个 PC web 站点

1.定义子配置文件路径

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

2.创建虚拟主机网站配置

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

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

[root@nginx1 ~]# mkdir -p /data/web/html -----建立目录

[root@nginx1 ~]# echo www.timinglee.org > /data/web/html/index.html

[root@nginx1 ~]# nginx -s reload

加入解析

测试

nginx配置中的root和alias

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

root示例:

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

[root@nginx1 ~]# mkdir /data/web/test1 -p 建立目录

[root@nginx1 ~]# echo /data/web/test1 > /data/web/test1/index.html

测试

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

alias示例:

server {
    listen 80;
    server_name www.timinglee.org;
    root /data/web/html;
    index index.html;
    location /test1 {
            root /data/web;
    }
    location /test2 {
        alias /data/web/test1;
    }
}
测试

Nginx 账户认证功能

设置用户和密码

[root@nginx1 ~]# htpasswd -cm /usr/local/nginx/.htpasswd admin 123

[root@nginx1 ~]# htpasswd -m /usr/local/nginx/.htpasswd lee 123

[root@nginx1 ~]# mkdir /data/web/lee

[root@nginx1 ~]# echo lee > /data/web/lee/index.html

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

[root@nginx1 ~]# nginx -s reload

测试

 

nginx自定义错误页面

测试:浏览器访问www.timinglee.org/testa 显示404

编辑配置文件

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

建立目录

[root@nginx1 ~]# mkdir -p /data/web/errorpage [root@nginx1 ~]# echo error page > /data/web/errorpage/40x.html [root@nginx1 ~]# nginx -s reload

再次测试

nginx自定义日志

日志存放位置

编辑配置文件

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

[root@nginx1 ~]#nginx -s reload

建立目录:

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

测试

nginx中的文件检测

编辑配置文件

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

[root@nginx1 ~]#nginx -s reload

文件存在时
[root@nginx1 ~]# curl www.timinglee.org
www.timinglee.org
删除文件
[root@nginx1 ~]# rm -rf /data/web/html/index.html 
[root@nginx1 ~]# rm -rf /data/web/html/error/
访问报500错误
[root@nginx1 ~]# curl www.timinglee.org
<html>
<head><title>500 Internal Server Error</title></head>
<body>
<center><h1>500 Internal Server Error</h1></center>
<hr><center>nginx/1.26.2</center>
</body>
</html>
建立目录
[root@nginx1 ~]# mkdir /data/web/html/error
[root@nginx1 ~]# echo error default > /data/web/html/error/default.html
再次访问就会跳转到default.html页面出现error default
[root@nginx1 ~]# curl www.timinglee.org
error default

nginx中的长链接管理

安装的长链接测试工具

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

测试---首先没配置keepalive_requests=2时----可以一直建立连接

[root@nginx1 ~]# telnet www.timinglee.org 80
Trying 172.25.254.100...
Connected to www.timinglee.org.
Escape character is '^]'.
GET / HTTP/1.1               ##输入动作
Host: www.timinglee.org       ##输入访问HOS
                               ##输入回车
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Tue, 20 Aug 2024 10:28:30 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Tue, 20 Aug 2024 10:17:04 GMT
Connection: keep-alive
ETag: "66c46d20-12"
Accept-Ranges: bytes
​
www.timinglee.org
​
GET / HTTP/1.1
Host: www.timinglee.org
​
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Tue, 20 Aug 2024 10:28:51 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Tue, 20 Aug 2024 10:17:04 GMT
Connection: keep-alive
ETag: "66c46d20-12"
Accept-Ranges: bytes
​
www.timinglee.org
GET / HTTP/1.1
Host: www.timinglee.org
​
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Tue, 20 Aug 2024 10:29:01 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Tue, 20 Aug 2024 10:17:04 GMT
Connection: keep-alive
ETag: "66c46d20-12"
Accept-Ranges: bytes
​
www.timinglee.org
GET / HTTP/1.1
Host: www.timinglee.org
​
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Tue, 20 Aug 2024 10:29:08 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Tue, 20 Aug 2024 10:17:04 GMT
Connection: keep-alive
ETag: "66c46d20-12"
Accept-Ranges: bytes
​
www.timinglee.org
​

编辑配置文件

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

测试:当配置keepalive_requests=2是。就只能建立两次连接,两次后退出

测试:当配置 keepalive_timeout=10秒时

[root@nginx1 ~]# telnet www.timinglee.org 80
Trying 172.25.254.100...
Connected to www.timinglee.org.
Escape character is '^]'.
GET / HTTP/1.1            #第一次
Host: www.timinglee.org
​
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Tue, 20 Aug 2024 10:43:56 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Tue, 20 Aug 2024 10:17:04 GMT
Connection: keep-alive
ETag: "66c46d20-12"
Accept-Ranges: bytes
​
www.timinglee.org
GET / HTTP/1.1                #第二次
Host: www.timinglee.org
​
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Tue, 20 Aug 2024 10:44:01 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Tue, 20 Aug 2024 10:17:04 GMT
Connection: keep-alive
ETag: "66c46d20-12"
Accept-Ranges: bytes
​
www.timinglee.org
GET / HTTP/1.1                  #第三次
Host: www.timinglee.org
​
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Tue, 20 Aug 2024 10:44:05 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Tue, 20 Aug 2024 10:17:04 GMT
Connection: keep-alive
ETag: "66c46d20-12"
Accept-Ranges: bytes
​
www.timinglee.org
GET / HTTP/1.1                #第四次
Host: www.timinglee.org
​
HTTP/1.1 200 OK
Server: nginx/1.26.2
Date: Tue, 20 Aug 2024 10:44:10 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Tue, 20 Aug 2024 10:17:04 GMT
Connection: keep-alive
ETag: "66c46d20-12"
Accept-Ranges: bytes
​
www.timinglee.org
Connection closed by foreign host.   # 超过10秒自动退出
[root@nginx1 ~]# 
​

nginx作为下载服务器配置

相关指令、

autoindex on | off;             #自动文件索引功能,默为off
 autoindex_exact_size on | off;  #计算文件确切大小(单位bytes),off 显示大概大小(单位K、M),默认on
 autoindex_localtime on | off ;  #显示本机时间而非GMT(格林威治)时间,默认off
 autoindex_format html | xml | json | jsonp; #显示索引的页面文件风格,默认html        
limit_rate rate;        #限制响应客户端传输速率(除GET和HEAD以外的所有方法),单位
B/s,bytes/second,         #默认值0,表示无限制,此指令由               
​
ngx_http_core_module提供
set $limit_rate 4k;       #也可以通变量限速,单位B/s,同时设置,此项优级高.
建立下载目录

[root@nginx1 ~]# mkdir /data/web/download

做一个1M大小为100的文件

[root@nginx1 ~]# dd if=/dev/zero of=/data/web/download/leefile bs=1M count=100 记录了100+0 的读入 记录了100+0 的写出 104857600字节(105 MB,100 MiB)已复制,0.0811884 s,1.3 GB/s

编辑配置文件

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

[root@nginx1 ~]# nginx -s reload

测试: 此时无法显示一个列表

加参数

再测试

更改时间为现在的时间和更改文件大小

测试

设置限速

测试

Nginx 高级配置

Nginx 状态页

编辑配置文件

[root@nginx1 ~]# cd /usr/local/nginx/conf.d/

[root@nginx1 conf.d]# vim status.conf

打开hosts添加解析

测试

accepts: #统计总值,Nginx自启动后已经接受的客户端请求连接的总数。

handled: #统计总值,Nginx自启动后已经处理完成的客户端请求连接总数 #通常等于accepts,除非有因worker_connections限制等被拒绝的

requests: #统计总值,Nginx自启动后客户端发来的总的请求数

没刷新一次,requests值就会加一次

不能随便让人看,设定一下

做本地解析

[root@nginx1 conf.d]# vim /etc/hosts

测试 ----本地拒绝

真实主机 172.25.254.1 正常访问

nginx数据压缩功能

Nginx支持对指定类型的文件进行压缩然后再传输给客户端,而且压缩还可以设置压缩比例,压缩后的文 件大小将比源文件显著变小,样有助于降低出口带宽的利用率,降低企业的IT支出,不过会占用相 应的CPU资源。 Nginx对文件的压缩功能是依赖于模块 ngx_http_gzip_module,默认是内置模块

配置指令如下:

#启用或禁用gzip压缩,默认关闭
gzip on | off; 
#压缩比由低到高从1到9,默认为1,值越高压缩后文件越小,但是消耗cpu比较高。基本设定未4或者5
 gzip_comp_level 4;
 #禁用IE6 gzip功能,早期的IE6之前的版本不支持压缩
gzip_disable "MSIE [1-6]\."; 
#gzip压缩的最小文件,小于设置值的文件将不会压缩
gzip_min_length 1k; 
#启用压缩功能时,协议的最小版本,默认HTTP/1.1
 gzip_http_version 1.0 | 1.1; 
#指定Nginx服务需要向服务器申请的缓存空间的个数和大小,平台不同,默认:32 4k或者16 8k;
 gzip_buffers number size;  
#指明仅对哪些类型的资源执行压缩操作;默认为gzip_types text/html,不用显示指定,否则出错
gzip_types mime-type ...; 
#如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”,一般建议打开
gzip_vary on | off; 
#预压缩,即直接从磁盘找到对应文件的gz后缀的式的压缩文件返回给用户,无需消耗服务器CPU
 #注意: 来自于ngx_http_gzip_static_module模块
gzip_static on | off

编辑配置文件

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

生成一个小于1k的文件

[root@nginx1 ~]# echo hello timinglee > /data/web/html/small.html

建立一个大文件

[root@nginx1 ~]# du -sh /usr/local/nginx/logs/access.log 1.1M /usr/local/nginx/logs/access.log [root@nginx1 ~]# cat /usr/local/nginx/logs/access.log > /data/web/html/big.html

测试

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名
#示例: 
echo $http_user_agent; 
echo $http_host;
 $http_<name>
 #name为任意请求报文首部字段,表示记录请求报文的首部字段,ame的对应的首部字段名需要为小写,如果有
横线需要替换为下划线
$sent_http_<name>
 #name为响应报文的首部字段,name的对应的首部字段名需要为小写,如果有横线需要替换为下划线,此变量有
问题
echo $sent_http_server;
 $arg_<name>
 #此变量存放了URL中的指定参数,name为请求url中指定的参数
echo $arg_id

编辑配置文件

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

测试

Nginx Rewrite 相关功能

Nginx服务器利用 ngx_http_rewrite_module 模块解析和处理rewrite请求

此功能依靠 PCRE(perl compatible regular expression),因此编译之前要安装PCRE库

rewrite是nginx服务器的重要功能之一,用于实现URL的重写,URL的重写是非常有用的功能

比如它可以在我们改变网站结构之后,不需要客户端修改原来的书签,也无需其他网站修改我们的 链接,就可以设置为访问

另外还可以在一定程度上提高网站的安全性。

ngx_http_rewrite_module 模块指令

if 指令

编辑配置文件

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

建立目录

[root@nginx1 ~]# mkdir -p /data/web/html/test2/
[root@nginx1 ~]# echo test2 > /data/web/html/test2/index.html
删除目录

[root@nginx1 ~]# rm -fr /data/web/html/test2/index.html
测试

break 指令

用于中断当前相同作用域(location)中的其他Nginx配置 与该指令处于同一作用域的Nginx配置中,位于它前面的配置生效 位于后面的 ngx_http_rewrite_module 模块中指令就不再执行 Nginx服务器在根据配置处理请求的过程中遇到该指令的时候,回到上一层作用域继续向下读取配置,、 该指令可以在server块和locationif块中使用

编辑配置文件

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

测试访问

 

如果加入break指令;break后面的就不会执行了

测试访问

加if判定,可以指定浏览器访问

测试

 return 指令

return用于完成对请求的处理,并直接向客户端返回响应状态码,比如:可以指定重定向URL(对于特殊重 定向状态码,301/302等) 或者是指定提示文本内容(对于特殊状态码403/500等),处于此指令后的所有配 置都将不被执行,return可以在server、if 和 location块进行配置

编辑

测试--检测

rewrite 指令

通过正则表达式的匹配来改变URI,可以同时存在一个或多个指令,按照顺序依次对URI进行匹配, rewrite主要是针对用户请求的URL或者是URI做具体处理

语法格式 : rewrite regex replacement [flag];

rewrite将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为表达式指定的新的URI 注意:如果在同一级配置块中存在多个rewrite规则,那么会自下而下逐个检查;被某条件规则替换完成 后,会重新一轮的替换检查,隐含有循环机制,但不超过10次;如果超过,提示500响应码,[flag]所表示的 标志位用于控制此循环机制

如果替换后的URL是以http://或https://开头,则替换结果会直接以重定向返回给客户端, 即永久重定向 301

rewrite flag 使用介绍

利用nginx的rewrite的指令,可以实现url的重新跳转,rewrite有四种不同的flag,分别是redirect(临时 重定向302)、permanent(永久重定向301)、break和last。其中前两种是跳转型的flag,后两种是代理型

跳转型指由客户端浏览器重新对新地址进行请求

代理型是在WEB服务器内部实现跳转

rewrite 格式

Syntax: rewrite regex replacement [flag]; #通过正则表达式处理用户请求并返回替换后的数据 包。 Default:  -

 Context: server, location, if

flag 说明

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

rewrite案例: 域名永久与临时重定向

永久重定向301

配置

测试

临时重定向302

配置

测试

rewrite案例: 自动跳转 https

全栈加密

创建密钥和证书

[root@nginx1 ~]# cd /usr/local/nginx/
[root@nginx1 nginx]# mkdir certs

 测试

 http自动跳转到https:

 如果在浏览器直接输入http://www.timinglee.org 可以直接跳转

 

 访问的文件不存在就重定向到主界面

防盗链

#盗链的实现
[root@nginx ~]# mkdir -p /data/web/html/images
将图片 daolian.png /data/web/html
将图片 lee.png /data/web/html/images/
测试机

[root@ceshiji1 ~]# yum install httpd -y
[root@ceshiji1 ~]# cd /var/www/html
[root@ceshiji1 html]# vim index.html

[root@ceshiji1 html]# cat vim index.html
cat: vim: 没有那个文件或目录
<html>
    <head>
        <meta http-equiv=Content-Type content="text/html;charset=utf-8">
        <title>盗链</title>
    </head>
    <body>
        <img src="http://www.timinglee.org/images/lee.png" >
        <h1 style="color:red">欢迎大家</h1>
        <p><a href=http://www.timinglee.org>狂点老王</a>出门见喜</p>
    </body>
</html>

[root@ceshiji1 html]# systemctl restart httpd.service 

浏览器访问172.25.254.10----测试机ip

 

防盗链

[root@nginx1 ~]# vim /usr/local/nginx/conf.d/vhost.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 ){
            rewrite ^/   http://www.timinglee.org/daolian.png;
        }

    }

}

[root@nginx1 ~]# nginx -s reload
浏览器访问172.25.254.10

nginx 反向代理及动静分离实验

首先准备两台服务器nginx_fxdl1,nginx_fxdl2并配置

[root@nginxfxdl1 ~]# yum install httpd -y
[root@nginxfxdl1 ~]# systemctl enable --now httpd
[root@nginxfxdl1 ~]# echo 172.25.254.10 > /var/www/html/index.html
[root@nginxfxdl2 ~]# yum install httpd -y
[root@nginxfxdl2 ~]# systemctl  enable --now httpd
[root@nginxfxdl2 ~]# echo 172.25.254.20 > /var/www/html/index.html

在nginx1主机测试连通性

[root@nginx1 ~]# curl 172.25.254.10
172.25.254.10
[root@nginx1 ~]# curl 172.25.254.20
172.25.254.20

反向代理单台web服务器

将用户对域 www.timinglee.org 的请求转发给后端服务器处理

[root@nginx1 ~]# 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;
    }
}

[root@nginx1 ~]# nginx -s reload

测试

实战案例: 指定 location 实现反向代理

[root@nginx1 ~]# 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;
    }
}

[root@nginx1 ~]# nginx -s reload


#后端web服务器必须要有相对于的访问URL

[root@nginxfxdl2 ~]# mkdir /var/www/html/static
[root@nginxfxdl2 ~]# echo static 172.25.254.20 > /var/www/html/static/index.html
[root@nginxfxdl2 ~]# vim /etc/httpd/conf/httpd.conf 
#找到 Listen  80 改为 Listen  8080
保存退出
[root@nginxfxdl2 ~]# systemctl restart httpd

重启Nginx并访问测试

动静分离访问PHP

#后端web服务器配置PHP

[root@nginxfxdl1 ~]# yum install php -y
[root@nginxfxdl1 ~]# systemctl restart httpd
[root@nginxfxdl1 ~]# vim /var/www/html/index.php
[root@nginxfxdl1 ~]# cat /var/www/html/index.php 
<?php
   phpinfo();
?>
[root@nginxfxdl1 ~]# 
[root@nginx1 ~]# vim /usr/local/nginx/conf.d/vhost.conf
[root@nginx1 ~]# nginx -s reload
[root@nginx1 ~]# cat /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;
	}
 }

测试:浏览器访问www.timinglee.org/index.php

反向代理示例: 缓存功能

缓存功能默认关闭状态,需要先动配置才能启用

[root@nginx1 ~]# vim /usr/local/nginx/conf/nginx.conf    #主配置文件中添加

[root@nginx1 ~]# nginx -s reload
编辑vim /usr/local/nginx/conf.d/vhost.conf

[root@nginx1 ~]#  cat /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;
		proxy_cache proxycache;
        proxy_cache_key $request_uri;
        proxy_cache_valid 200 302 301 10m;
		proxy_cache_valid any 1m;
	}

}

[root@nginx1 ~]# nginx -s reload

在nginx_fxdl1中添加域名

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

测试:[root@nginx1 ~]# ab -n1000 -c100 http://www.timinglee.org/static/index.html

实现 FastCGI

源码编译php

编译需要的包全部解压

memc-nginx-module-0.20.tar.gz   php-8.3.9.tar.gz    srcache-nginx-module-0.33.tar.gz

删除之前的nginx ---重新编译

 ./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

安装 make install

下载安装依赖包

解压php

[root@nginx2 ~]# tar zxf php-8.3.9.tar.gz 

[root@nginx2 php-8.3.9]# ./configure \--prefix=/usr/local/php \--enable-fpm  \--with-iconv \--with-config-file-path=/usr/local/php/etc \--with-fpm-user=nginx \--with-fpm-group=nginx \--with-curl \--with-mhash \--with-zlib \--with-openssl \--enable-mysqlnd \--with-mysqli \--with-pdo-mysql \--disable-debug \--enable-sockets \--enable-soap \--enable-xml \--enable-ftp \--enable-gd \--enable-exif \--enable-mbstring \--enable-bcmath \--with-fpm-systemd    

缺少这个插件

Package 'libcurl', required by 'virtual:world', not found

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables CURL_CFLAGS
and CURL_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.
[root@nginx2 php-8.3.9]# dny install libcurl-devel -y
bash: dny: command not found...

下载后 继续编译
[root@nginx2 php-8.3.9]# yum install libcurl-devel -y

Package 'libpng', required by 'virtual:world', not found

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables PNG_CFLAGS
and PNG_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.

[root@nginx2 php-8.3.9]# yum install libpng-devel-y

继续编译

又缺少这个插件

configure: error: Package requirements (oniguruma) were not met:

Package 'oniguruma', required by 'virtual:world', not found

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

Alternatively, you may set the environment variables ONIG_CFLAGS
and ONIG_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.

下载

[root@nginx2 ~]# dnf install oniguruma-devel-6.9.6-1.el9.5.x86_64.rpm
继续编译

[root@nginx2 php-8.3.9]# ./configure \--prefix=/usr/local/php \--enable-fpm  \--with-iconv \--with-config-file-path=/usr/local/php/etc \--with-fpm-user=nginx \--with-fpm-group=nginx \--with-curl \--with-mhash \--with-zlib \--with-openssl \--enable-mysqlnd \--with-mysqli \--with-pdo-mysql \--disable-debug \--enable-sockets \--enable-soap \--enable-xml \--enable-ftp \--enable-gd \--enable-exif \--enable-mbstring \--enable-bcmath \--with-fpm-systemd  

 证明编译好了

然后--
[root@nginx2 php-8.3.9]# make && make install

一直等待到这里就安装好了

 php相关配置优化

[root@nginx2 etc]# cd php-fpm.d/
[root@nginx2 php-fpm.d]# ls
www.conf.default
[root@nginx2 php-fpm.d]# cp www.conf.default www.conf

生成主配置文件   

如果编译的时候没有加参数--with-config-file-path=/usr/local/php/etc 配置文件就在/usr/local/php/lib/ 如果加了就在/usr/local/php/etc

[root@nginx2 php-8.3.9]# cp php.ini-production /usr/local/php/etc/php.ini

修改时区
[root@nginx2 php-8.3.9]# vim /usr/local/php/etc/php.ini

生成启动文件

[root@nginx2 php-8.3.9]#  cp sapi/fpm/php-fpm.service /lib/systemd/system/
[root@nginx2 php-8.3.9]# vim /lib/systemd/system/php-fpm.service 

配置环境变量

[root@nginx2 ~]# vim .bash_profile

[root@nginx2 ~]# source .bash_profile
定义子配置文件

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

php测试页面

[root@nginx2 ~]# mkdir -p /data/web/php
[root@nginx2~]# cd /usr/local/php/bin/
[root@nginx2 bin]# vim ~/.bash_
.bash_history  .bash_logout   .bash_profile  
[root@nginx2 bin]# vim ~/.bash_profile 
export PATH=$PATH:/usr/local/nginx/sbin:/usr/local/php/bin:/usr/local/php/sbin
[root@nginx2 bin]# source ~/.bash_profile 
[root@nginx2 bin]# cd /data/web/php/

[root@nginx2 conf]# cd /usr/local/nginx/
[root@nginx2 nginx]# mkdir conf.d
[root@nginx2 nginx]# vim conf/nginx.conf

[root@nginx2 ~]# vim /usr/local/php/etc/php-fpm.d/www.conf

php的动态扩展模块(php的缓存模块)

安装memcache模块

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

复制测试文件到nginx发布目录中

[root@Nginx2 ~]# cd memcache-8.2/
[root@Nginx2 memcache-8.2]# ls
[root@Nginx2 memcache-8.2]# cp example.php memcache.php /data/web/php/
[root@Nginx2 ~]# 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@Nginx2 ~]# vim /usr/local/php/etc/php.ini
;extension=zip
extension=memcache
;zend_extension=opcache
[root@Nginx2 ~]# systemctl reload php-fpm
[root@Nginx2 ~]# cp /usr/local/php/etc/php.ini /usr/local/php/lib/   #因为没有指定路劲,所以要移动到默认路径
[root@Nginx2 no-debug-non-zts-20230831]# php -m | grep mem 
memcache

部署memcached

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值