当前位置: 首页 > news >正文

Nginx相关实验(2)

nginx的一些高级配置

nginx状态页

基于nginx 模块 ngx_http_stub_status_module 实现, 在编译安装nginx的时候需要添加编译参数 --with-http_stub_status_module 否则配置完成之后监测会是提示语法错误

#检查模块是否配置 如果不存在需要添加模块重新编译
nginx -V 2>&1 | grep stub

#配置文件
vim /usr/local/nginx/conf.d/vhosts.conf
location /status {stub_status;	auth_basic "status page";	auth_basic_user_file "/usr/local/nginx/.htpasswd";	
#stub_status; 启动状态页
# auth_basic "status page"; 启用了 HTTP 基本认证(Basic Authentication),用于保护 /status 页面,防止未经授权的访问。
"status page" 是认证提示信息,当用户访问 /status 页面时,浏览器会弹出一个认证框,提示用户输入用户名和密码。
#auth_basic_user_file "/usr/local/nginx/.htpasswd"; 指定了存储用户认证信息的文件路径为 /usr/local/nginx/.htpasswd#本地解析	在windows中	找到C:\Windows\System32\drivers\etc 此路径下的hosts文件,以记事本方式打开 加入虚拟机ip和自定义域名

 

 测试:在浏览器输入自定义域名 www.test.org/status

nginx压缩功能

#参数说明
#启用或禁用gzip压缩,默认关闭
gzip on | off; 
#压缩比由低到高从1到9,默认为1,值越高压缩后文件越小,但是消耗cpu比较高。基本设定未4或者5gzip_comp_level 4;#禁用IE6 gzip功能,早期的IE6之前的版本不支持压缩
gzip_disable "MSIE [1-6]\."; 
#gzip压缩的最小文件,小于设置值的文件将不会压缩
gzip_min_length 1k; 
#启用压缩功能时,协议的最小版本,默认HTTP/1.1gzip_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@webserver ~]# vim /usr/local/nginx/conf/nginx.conf
gzip  on;gzip_comp_level 4;gzip_disable "MSIE [1-6]\.";gzip_min_length 1024k;gzip_types mime-type;gzip_vary on;gzip_static on;

常用内置变量

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

添加echo工具

#首先需要下载echo的压缩包传入虚拟机中
[root@webserver ~]# ls
anaconda-ks.cfg  Downloads                      Music                Pictures    Templates
Desktop          echo-nginx-module-0.63         nginx-1.26.1         Public      Videos
Documents        echo-nginx-module-0.63.tar.gz  nginx-1.26.1.tar.gz  rh9.3.repo

相关配置

#解压到/root目录下
tar zxf echo-nginx-module-0.63.tar.gz#查看当前编译环境的模块,在最后加上解压后的echo模块并编译
nginx -V
nginx version: nginx/1.26.1
built by gcc 11.4.1 20230605 (Red Hat 11.4.1-2) (GCC)
built with OpenSSL 3.0.7 1 Nov 2022
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 --add-module=/root/echo-nginx-module-0.63#添加echo模块并验证./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --add-module=/root/echo-nginx-module-0.63make 	#编译#编译完成后进入到objs下 用新的nginx文件替换掉旧的
cd nginx-1.26.1/
cd objs/
cp nginx /usr/local/nginx/sbin/nginx#验证是否成功添加
nginx -V 2>&1 | grep echo

#在配置文件中开启模块并配置对应选项即可使用
vim /usr/local/nginx/conf.d/vhosts.conflocation /vars {default_type test/html;echo $uri;echo $server_addr;#验证语法并重启服务
nginx -t
systemctl restart nginx 或者 nginx -s reload#输出效果
curl www.test.org/vars
/vars
192.168.75.10

自动跳转https

基于通信安全考虑公司网站要求全站 https,因此要求将在不影响用户请求的情况下将http请求全 部自动跳转至 https,另外也可以实现部分 location 跳转

vim /usr/local/nginx/conf.d/vhosts.conflocation / {	#匹配所有以/开头的路径if ($scheme = http){	#$scheme 是 Nginx 的内置变量,表示当前请求的协议,通常是 http 或 https。rewrite /(.*) https://$host/$1;	#将http请求重定向到对应的https地址}}#重启并访问
nginx -s reloadcurl -vL www.test.org
*   Trying 192.168.75.10:80...
* Connected to www.test.org (192.168.75.10) port 80 (#0)
> GET / HTTP/1.1
> Host: www.test.org
> User-Agent: curl/7.76.1
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Moved Temporarily
< Server: nginx/1.26.1
< Date: Sun, 27 Jul 2025 03:04:48 GMT
< Content-Type: text/html
< Content-Length: 145
< Connection: keep-alive
< Keep-Alive: timeout=50
< Location: https://www.test.org/	#可见已经被替换成https

判断文件是否存在

当用户访问到公司网站的时输入了一个错误的URL,可以将用户重定向至官网首页

vim /usr/local/nginx/conf.d/vhosts.conflocation / {if (!-e $request_filename){rewrite /(.*) http://$host/index.html;	}	[root@webserver conf.d]# curl -L www.test.org/1	#访问一个不存在的地址,自动跳转到主界面
web_html

防盗链

防盗链基于客户端携带的referer实现,referer是记录打开一个页面之前记录是从哪个页面跳转过来的标 记信息,如果别人只链接了自己网站图片或某个单独的资源,而不是打开了网站的整个页面,这就是盗 链,referer就是之前的那个网站域名,正常的referer信息有以下几种:

none:   #请求报文首部没有referer首部,            #比如用户直接在浏览器输入域名访问web网站,就没有referer信息。
blocked:      #请求报文有referer首部,但无有效值,比如为空。
server_names:       #referer首部中包含本主机名及即nginx 监听的server_name。arbitrary_string:   #自定义指定字符串,但可使用*作通配符。示例: *.test.org 
www.test.*regular expression: #被指定的正则表达式模式匹配到的字符串,要使用~开头,例如:
~.*\.test\.com

实现盗链

#新建一个主机192.168.75.20,盗取另一台主机www.test.org的信息
yum install httpd -y	#下载httpd
vim /var/www/html/index.html	#写入盗链web页面
<html><head><meta http-equiv=Content-Type content="text/html;charset=utf-8"><title>盗链</title></head><body><h1 style="color:red">Y</h1><p><a href=http://www.test.org>N</a>A</p></body></html>vim /etc/hosts	#本地解析
192.168.75.20   rs1 www.test.orgsystemctl enable --now httpd	#重启服务参数解释:
none:允许没有 referer 的请求(比如直接输入地址访问)。
blocked:允许 referer 被防火墙或代理隐藏的请求。
server_names:允许当前 server_name 下的所有域名。
*.test.org:允许所有以 .test.org 结尾的子域名。
~/.baidu/.:正则匹配,允许 referer 中包含 baidu 的请求(如 www.baidu.com、map.baidu.com 等)。

此时在浏览器中发现可以正常获取信息

点击字母n可以正常访问

防止盗链

#在nginx配置文件中写入location / {valid_referers none blocked server_names *.test.org ~/.baidu/.;if ($invalid_referer){return 404;}}#重启服务

再次访问发现无法获取

nginx实现动静分离

需要三台主机

192.168.75.10 #nginx
192.168.75.20 #rs1 httpd,作为静态服务器
192.168.75.30 #rs2 php,作为动态服务器

配置

nginx:
#编辑配置文件
[root@webserver conf.d]# vim vhosts.conf
server{listen  80;server_name www.test.org;location / {proxy_pass http://192.168.75.20:80;}location ~\.(php|jsp|js)$ {proxy_pass http://192.168.75.30:80;}
}rs1
#下载httpd
yum install httpd -y
#关闭防火墙
systemctl disable --now firewalld.service
#启动httpd服务
systemctl enable --now httpd
#写入默认发布信息
mkdir /var/www/html/static
echo static 192.168.75.20 >/var/www/html/static/index.htmlrs2:
yum install httpd -y
yum install php -y
systemctl restart httpd.service
mkdir /var/www/html/php
vim /var/www/html/php/index.php
[root@rs2 ~]# cat /var/www/html/php/index.php
<?phpphpinfo();
?>
systemctl status firewalld.service

测试:在浏览器中输入www.test.org/php/index.php

输入www.test.org/static 自动跳转到如下图所示:

缓存功能

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

参数解释:

proxy_cache zone_name | off; 默认off#指明调用的缓存,或关闭缓存机制;Context:http, server, location#zone_name 表示缓存的名称.需要由proxy_cache_path事先定义proxy_cache_key string;#缓存中用于“键”的内容,默认值:proxy_cache_key $scheme$proxy_host$request_uri;proxy_cache_valid [code ...] time;#定义对特定响应码的响应内容的缓存时长,定义在http{...}中
示例:proxy_cache_valid 200 302 10m;proxy_cache_valid 404 1m;proxy_cache_path;#定义可用于proxy功能的缓存;Context:http 
proxy_cache_path path [levels=levels] [use_temp_path=on|off] 
keys_zone=zone_name:size [inactive=time] [max_size=size] [manager_files=number] 
[manager_sleep=time] [manager_threshold=time] [loader_files=number] 
[loader_sleep=time] [loader_threshold=time] [purger=on|off] 
[purger_files=number] [purger_sleep=time] [purger_threshold=time];#示例:在http配置定义缓存信息
proxy_cache_path /var/cache/nginx/proxy_cache #定义缓存保存路径,proxy_cache会自动创建
levels=1:2:2    #定义缓存目录结构层次 #1:2:2可以生成
2^4x2^8x2^8=2^20=1048576个目录
keys_zone=proxycache:20m   #指内存中缓存的大小,主要用于存放key和metadata       
(如:使用次数)		#一般1M可存放8000个左右的keyinactive=120s     #缓存有效时间                
max_size=10g;        #最大磁盘占用空间,磁盘存入文件内容的缓存空间最大#调用缓存功能,需要定义在相应的配置段,如server{...};或者location等
proxy_cache proxycache;proxy_cache_key $request_uri;       #对指定的数据进行MD5的运算做为缓存的keyproxy_cache_valid 200 302 301 10m;  #指定的状态码返回的数据缓存多长时间
proxy_cache_valid any 1m;           #除指定的状态码返回的数据以外的缓存多长时间,必须设置,否则不会缓存proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | 
http_502 | http_503 | http_504 | http_403 | http_404 | off ;      #默认是off
#在被代理的后端服务器出现哪种情况下,可直接使用过期的缓存响应客户端
#示例
proxy_cache_use_stale error http_502 http_503;proxy_cache_methods GET | HEAD | POST ...;#对哪些客户端请求方法对应的响应进行缓存,GET和HEAD方法总是被缓存

配置

#全局配置
[root@webserver conf.d]# vim /usr/local/nginx/conf/nginx.conf#  gzip_static on;proxy_cache_path /usr/local/nginx/cache levels=1:2:2 keys_zone=proxycache:20m inactive=120s max_size=1g;#子配置文件
[root@webserver conf.d]# vim /usr/local/nginx/conf.d/vhosts.confserver{listen  80;server_name www.test.org;location / {proxy_pass http://192.168.75.20:80;proxy_cache proxycache;proxy_cache_key $request_uri;proxy_cache_valid 200 302 10m;proxy_cache_valid 404 1m;}location ~\.(php|jsp|js)$ {proxy_pass http://192.168.75.30:80;}
}#无缓存环境压测
[root@webserver conf.d]# ab -n 10000 -c 500 http://www.test.org/index.htmlConcurrency Level:      500
Time taken for tests:   3.086 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      2640000 bytes
HTML transferred:       140000 bytes
Requests per second:    3240.10 [#/sec] (mean)
Time per request:       154.316 [ms] (mean)
Time per request:       0.309 [ms] (mean, across all concurrent requests)
Transfer rate:          835.34 [Kbytes/sec] received#有缓存环境压测
[root@webserver conf.d]# ab -n 10000 -c 500 http://www.test.org/index.htmlConcurrency Level:      500
Time taken for tests:   0.502 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      2640000 bytes
HTML transferred:       140000 bytes
Requests per second:    19932.51 [#/sec] (mean)
Time per request:       25.085 [ms] (mean)
Time per request:       0.050 [ms] (mean, across all concurrent requests)
Transfer rate:          5138.85 [Kbytes/sec] received	#通过此条对比发现快了不少

配置前 

配置后

负载均衡实例: MySQL

mysql准备

#准备两台后端服务器 并安装mysql
yum install mariadb -y#更改mysql的id方便测试
[root@rs1 ~]# vim /etc/my.cnf.d/mariadb-server.cnf
[mysqld]
server-id=20rs2同理,将server-id改为30

#启动mariadbsystemctl start mariadb#创建用户mysql -e "grant all on *.* to yna@'%' identified by 'yna';"#远程登陆测试,在rs1上测试rs2,在rs2上测试rs1
[root@rs1 ~]# mysql -uyna -pyna -h 192.168.75.30 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
|          30 |
+-------------+[root@rs2 ~]# mysql -uyna -pyna -h 192.168.75.20 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
|          20 |
+-------------+

nginx配置

#创建一个目录,存放有关mysql的负载均衡配置文件
[root@webserver conf.d]# mkdir /usr/local/nginx/tcp.d#编辑配置文件
[root@webserver tcp.d]# vim my.confstream {upstream mysql_server{server 192.168.75.20:3306 max_fails=3 fail_timeout=30s;server 192.168.75.30:3306 max_fails=3 fail_timeout=30s;}server{listen 192.168.75.10:3306;proxy_pass mysql_server;proxy_connect_timeout 30s;proxy_timeout 300s;}
}#将子配置文件的位置写入主配置文件当中,注意不要写到http{}模块中
vim /usr/local/nginx/conf/nginx.service

验证 

#验证语法无错误后重启
[root@webserver tcp.d]# 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@webserver tcp.d]# systemctl restart nginx.service在rs中通过nginx负载ip连接mysql[root@rs1 ~]# mysql -uyna -pyna -h 192.168.75.10 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
|          20 |
+-------------+
[root@rs1 ~]# mysql -uyna -pyna -h 192.168.75.10 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
|          30 |
+-------------+

#停止rs1上的mysql服务,就只会看到rs2响应
[root@rs1 ~]# systemctl stop mariadb.service[root@rs2 ~]#  mysql -uyna -pyna -h 192.168.75.10 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
|          30 |
+-------------+
[root@rs2 ~]#  mysql -uyna -pyna -h 192.168.75.10 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
|          30 |
+-------------+

nginx代理dns做负载均衡

实验需要三台主机,一台nginx,两台dns

nginx:192.168.75.10

rs1:192.168.75.20 rs2:192.168.75.30

dns配置

#在rs1和rs2上安装dns
yum install bind -y#编辑dns配置文件
vim /etc/named.conf1. `// listen-on port 53 { 127.0.0.1; };`  当前被注释掉(行首 `//`)。若取消注释,表示让 named 只在 IPv4 的 127.0.0.1:53 上监听,不对其他网卡开放。2. `// listen-on-v6 port 53 { ::1; };`  同样被注释。若取消,表示让 named 只在 IPv6 的 ::1(本地环回):53 上监听。3. `// allow-query { localhost; };`  被注释时,默认允许所有客户端查询;若取消注释,则只允许来自 localhost(127.0.0.1/::1)的查询,其他地址将被拒绝。4. `dnssec-validation no;`  关闭 DNSSEC 签名校验。named 不会对收到的应答做 DNSSEC 验证,可减少计算量,但也会失去对伪造应答的防护。若需安全,应设为 `yes` 并配置信任锚(trust-anchors)。

将框选出的选项注释掉,最后一个由yes改为no

vim /etc/named.rfc1912.zones
#加入下面这段代码,其中域名可以自定义
zone "test.org" IN {	type master;file "test.org.zone";allow-update { none; };- zone "test.org" IN  声明一个 DNS 区域(zone),负责解析的域名是 `test.org`,`IN` 表示 Internet 类别(也是最常用的类别)。- type master;  指定本机是该区域的主服务器(master),即权威数据源在本机。- file "test.org.zone"; 区域数据文件存放路径(相对于 `options` 中 `directory` 指定的目录),文件里保存了所有 `test.org` 的记录(如 A、MX、NS 等)。- allow-update { none; };禁止任何人通过动态 DNS(DDNS)更新该区域,提高安全性。

#编辑文件test.org.zone
[root@rs1 named]# vim /etc/named/test.org.zone
$TTL 1D
@       IN SOA  dns.test.org  root.test.org. (0       ; serial1D      ; refresh1H      ; retry1W      ; expire3H )    ; minimumNS      dns.test.org.dns     A       192.168.75.20	#本机IP#rs2同样配置即可

测试配置是否生效

#重启服务
systemctl restart named[root@rs1 named]# dig @192.168.75.20 dns.test.org[root@rs2 named]# dig @192.168.75.30 dns.test.org

nginx配置

#创建一个目录,存放有关dns的负载均衡配置文件
[root@webserver conf.d]# mkdir /usr/local/nginx/tcp.d#编辑配置文件
[root@webserver tcp.d]# vim my.conf
stream {
upstream dns_server{server 192.168.75.20:53 max_fails=3 fail_timeout=30s;server 192.168.75.30:53 max_fails=3 fail_timeout=30s;}server{listen 53 udp;proxy_pass dns_server;}server{listen 53;proxy_pass dns_server;}
}
#将创建的子配置文件写入主配置文件中#检验语法无误后重启服务
[root@webserver tcp.d]# 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@webserver tcp.d]# systemctl restart nginx.service

验证结果

#在后端服务器上通过访问域名查看访问是否轮询
[root@rs1 named]# dig @192.168.75.10 dns.test.org

 FastCGI

  1. 本质:FastCGI 不是软件,而是一个 常驻型(long-lived)通信协议,位于 Web 服务器与后端解释器(PHP、Python、Ruby…)之间。

  2. 解决的问题:传统 CGI 每次请求都要“fork-执行-退出”,高并发时 CPU 和内存开销极大;FastCGI 通过 进程池复用 避免频繁创建销毁进程,从而提高吞吐、降低延迟。

  3. 常见实现: • PHP:php-fpm(内置 FastCGI 管理器) • Python:flup、uWSGI(兼容 FastCGI) • 通用:spawn-fcgi、fcgiwrap

源码编译安装php

#首先需要准备好php的压缩包
php-8.3.9.tar.gz#解压
tar zxf php-8.3.9.tar.gz#安装依赖
yum install -y bzip2 systemd-devel libxml2-devel sqlite-devel libcurl-devel.x86_64 libpng-devel.x86_64 #准备好oniguruma-6.9.6-1.el9.6.x86_64.rpm和oniguruma-devel-6.9.6-1.el9.6.x86_64.rpm包#更新oniguruma-6.9.6-1.el9.6.x86_64.rpm包
yum update oniguruma-6.9.6-1.el9.6.x86_64.rpm#安装oniguruma-devel-6.9.6-1.el9.6.x86_64.rpm
yum install oniguruma-devel-6.9.6-1.el9.6.x86_64.rpm -y#进入php目录下,检测环境
cd php-8.3.9/./configure \
--prefix=/usr/local/php \
--with-config-file-path=/usr/local/php/etc \
--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-sockets \
--enable-soap \
--enable-xml \
--enable-ftp \
--enable-gd \
--enable-exif \
--enable-mbstring \
--enable-bcmath \
--with-fpm-systemd#检测无误后编译并安装
make
make install

php配置优化

cd /usr/local/php/etc
cp php-fpm.conf.default php-fpm.conf
vim php-fpm.conf#去掉此行注释
pid = run/php-fpm.pid       #指定pid文件存放位置cd php-fpm.d/
cp www.conf.default www.conf#生成主配置文件
cd /root/php-8.3.9/
cp php.ini-production /usr/local/php/etc/php.ini
vim /usr/local/php/etc/php.ini[Date]; Defines the default timezone used by the date functions; https://php.net/date.timezonedate.timezone = Asia/Shanghai       #修改时区#在主配置文件中将本机ip改为允许所有ipcd php-8.3.9/vim /usr/local/php/etc/php-fpm.d/www.conf;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 0.0.0.0:9000	#改为0.0.0.#生成启动文件cd /root/php-8.3.9/cp sapi/fpm/php-fpm.service /lib/systemd/system/# Mounts the /usr, /boot, and /etc directories read-only for processes invoked by this unit.#ProtectSystem=full         #注释该内容cp sapi/fpm/php-fpm.service /lib/systemd/system/systemctl daemon-reloadsystemctl restart php-fpm.service[root@webserver php-8.3.9]# netstat -antulpe | grep php	#查看php服务是否启动
tcp        0      0 0.0.0.0:9000            0.0.0.0:*               LISTEN      0          137571     162490/php-fpm: mas

准备php测试页面

[root@webserver ~]# cd /usr/local/nginx/html/
[root@webserver html]# vim index.php
<?phpphpinfo();
?>

配置nginx转发

[root@webserver html]# cd /usr/local/nginx/conf.d
[root@webserver conf.d]# vim vhosts.confserver {listen 80;server_name www.test.org;location ~ \.php$ {fastcgi_pass 127.0.0.1:9000;fastcgi_index index.php;fastcgi_param SCRIPT_FILRNAME /scripts$fastcgi_script_name;include fastcgi.conf;}
}#验证语法并重启服务
[root@webserver ~]# 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@webserver ~]# nginx -s reload

测试,浏览器中输入www.test.org/index.php

添加php环境变量

[root@webserver ~]# vim ~/.bash_profile# .bash_profile# Get the aliases and functions
if [ -f ~/.bashrc ]; then. ~/.bashrc
fi# User specific environment and startup programsexport PATH=$PATH:/usr/local/nginx/sbin:/usr/local/php/bin #在后面加上:/usr/local/php

php扩展模块

memcache模块

#安装memcache模块
tar zxf memcache-8.2.tgzcd memcache-8.2/yum install autoconf[root@webserver memcache-8.2]# phpize
Configuring for:
PHP Api Version:         20230831
Zend Module Api No:      20230831
Zend Extension Api No:   420230831./configuremakemake install[root@webserver memcache-8.2]# ls /usr/local/php/lib/php/extensions/no-debug-non-zts-20230831/
memcache.so  opcache.so#复制测试文件到nginx发布目录中并更改配置cp example.php memcache.php /usr/local/nginx/html/vim /usr/local/nginx/html/memcache.phpdefine('ADMIN_USERNAME','yna');  // Admin Username
define('ADMIN_PASSWORD','yna');  // Admin Password
define('DATE_FORMAT','Y/m/d H:i:s');
define('GRAPH_SIZE',200);
define('MAX_ITEM_DUMP',50);
$MEMCACHE_SERVERS[] = 'localhost:11211'; // add more as an array
#$MEMCACHE_SERVERS[] = 'mymemcache-server2:11211'; // add more as an array#配置php 加载memcache模块
vim /usr/local/php/etc/php.ini;extension=zipextension=memcache;zend_extension=opcachesystemctl reload  php-fpm[root@wb-nginx memcache-8.2]# yum install memcached -y[root@wb-nginx memcache-8.2]# systemctl enable --now memcached.service
Created symlink /etc/systemd/system/multi-user.target.wants/memcached.service → /usr/lib/systemd/system/memcached.service.[root@webserver memcache-8.2]# php -m | grep mem
memcachecat /etc/sysconfig/memcachedPORT="11211"USER="memcached"cMAXCONN="1024"CACHESIZE="64"OPTIONS="-l 0.0.0.0,::1"

测试

#进入到memcache下,进行压测测试
[root@webserver memcache-8.2]# ab -n 1000 -c 50 http://www.test.org/example.php访问 http://php.test.org/example.php 不断刷新
访问 http://php.test.org/memcache.php 查看命中效果

php高速缓存

当客户端向nginx发送请求时,nginx会通过php来请求memcache。如此一来,响应速度会受限于php,但是做完高速缓存后,在nginx第二次请求相同的数据时,会直接访问memcache而跳过php,这样就加快了响应速度

配置

#在nginx中添加模块:memc和srcache
tar xzf memc-nginx-module-0.20.tar.gz
tar xzf srcache-nginx-module-0.33.tar.gzcd nginx-1.26.1/
./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --add-module=/root/memc-nginx-module-0.20 --add-module=/root/echo-nginx-module-0.63 --add-module=/root/srcache-nginx-module-0.33make编译后不需要make install
#关闭nginx
systemctl stop nginx.service#使用新的nginx覆盖掉旧的即可
cd objs/
cp nginx /usr/local/nginx/sbin/#编辑配置文件
vim /usr/local/nginx/conf.d/vhosts.confupstream memcache{server 127.0.0.1:11211;keepalive 512;
}server{listen 80;server_name www.test.org;location /memc {internal;memc_connect_timeout 100ms;memc_send_timeout 100ms;memc_read_timeout 100ms;set $memc_key $query_string;set $memc_exptime 300;memc_pass memcache;}location ~ \.php$ {set $key $uri$args;srcache_fetch GET /memc $key;srcache_store PUT /memc $key;fastcgi_pass 127.0.0.1:9000;fastcgi_index index.php;fastcgi_param SCRIPT_FILRNAME /scripts$fastcgi_script_name;include fastcgi.conf;}
}

测试

#压测测试
#配置高速缓存前
[root@webserver conf.d]# ab -n10000 -c500 http://www.test.org/index.phpServer Software:        nginx/1.26.1
Server Hostname:        www.test.org
Server Port:            80Document Path:          /index.php
Document Length:        75004 bytesConcurrency Level:      500
Time taken for tests:   2.098 seconds
Complete requests:      10000
Failed requests:        1006(Connect: 0, Receive: 0, Length: 1006, Exceptions: 0)
Total transferred:      751888304 bytes
HTML transferred:       750038398 bytes
Requests per second:    4767.55 [#/sec] (mean)
Time per request:       104.876 [ms] (mean)
Time per request:       0.210 [ms] (mean, across all concurrent requests)
Transfer rate:          350064.85 [Kbytes/sec] received

#配置php高速缓存后
[root@webserver conf.d]# ab -n10000 -c500 http://www.test.org/index.phpServer Software:        nginx/1.26.1
Server Hostname:        www.test.org
Server Port:            80Document Path:          /index.php
Document Length:        75003 bytesConcurrency Level:      500
Time taken for tests:   1.118 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      752130000 bytes
HTML transferred:       750030000 bytes
Requests per second:    8945.84 [#/sec] (mean)
Time per request:       55.892 [ms] (mean)
Time per request:       0.112 [ms] (mean, across all concurrent requests)
Transfer rate:          657073.70 [Kbytes/sec] received

nginx二次开发版本

编译安装 openresty

tar zxf openresty-1.25.3.1.tar.gzcd openresty-1.25.3.1/./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_modulegmake
gmake install#添加环境变量
vim ~/.bash_profile# .bash_profile# Get the aliases and functions
if [ -f ~/.bashrc ]; then. ~/.bashrc
fi# User specific environment and startup programsexport PATH=$PATH:/usr/local/nginx/sbin:/usr/local/php/bin:/apps/openresty/bin
#加入openresty的实际的安装目录下的bin /apps/openresty/binsource ~/.bash_profile#查看版本
[root@webserver openresty]# openresty -V
nginx version: openresty/1.25.3.1
built by gcc 11.4.1 20230605 (Red Hat 11.4.1-2) (GCC)
built with OpenSSL 3.0.7 1 Nov 2022
TLS SNI support enabled
configure arguments: --prefix=/apps/openresty/nginx --with-cc-opt=-O2 --add-module=../ngx_devel_kit-0.3.3 --add-module=../echo-nginx-module-0.63 --add-module=../xss-nginx-module-0.06 --add-module=../ngx_coolkit-0.2 --add-module=../set-misc-nginx-module-0.33 --add-module=../form-input-nginx-module-0.12 --add-module=../encrypted-session-nginx-module-0.09 --add-module=../srcache-nginx-module-0.33 --add-module=../ngx_lua-0.10.26 --add-module=../ngx_lua_upstream-0.07 --add-module=../headers-more-nginx-module-0.37 --add-module=../array-var-nginx-module-0.06 --add-module=../memc-nginx-module-0.20 --add-module=../redis2-nginx-module-0.15 --add-module=../redis-nginx-module-0.3.9 --add-module=../rds-json-nginx-module-0.16 --add-module=../rds-csv-nginx-module-0.09 --add-module=../ngx_stream_lua-0.0.14 --with-ld-opt=-Wl,-rpath,/apps/openresty/luajit/lib --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --with-stream --without-pcre2 --with-stream_ssl_preread_module#启动服务
openresty

浏览器访问测试

http://www.dtcms.com/a/312378.html

相关文章:

  • 【2025/08/03】GitHub 今日热门项目
  • C# LINQ(LINQ to XML)
  • CAP 理论笔记
  • CUDA杂记--nvcc使用介绍
  • GitHub 趋势日报 (2025年08月02日)
  • 控制建模matlab练习07:比例积分控制-③PI控制器的应用
  • 深入掌握 ExcelJS:Node.js 中强大的 Excel 操作库
  • 小红书开源dots.ocr:单一视觉语言模型中的多语言文档布局解析
  • WebRTC前处理模块技术详解:音频3A处理与视频优化实践
  • ⭐CVPR2025 3D 生成新框架|Kiss3DGen 让 2D 扩散模型玩转 3D 资产生成
  • sqli-labs:Less-26关卡详细解析
  • 【数据迁移】Windows11 下将 Ubuntu 从 C 盘迁移到 D 盘
  • Spring Boot 的事务注解 @Transactional 失效的几种情况
  • MCU中的复位生成器(Reset Generator)是什么?
  • 智能手表项目:原理图
  • kotlin kmp 跨平台环境使用sqldelight
  • Shell脚本-变量如何定义
  • webrtc弱网-QualityScaler 源码分析与算法原理
  • npm ERR! code CERT_HAS_EXPIRED:解决证书过期问题
  • `npm error code CERT_HAS_EXPIRED‘ 问题
  • Azure DevOps — Kubernetes 上的自托管代理 — 第3部分
  • JVM-垃圾回收器与内存分配策略详解
  • Node.js 服务可以实现哪些功能
  • 【python实用小脚本-169】『Python』所见即所得 Markdown 编辑器:写完即出网页预览——告别“写完→保存→刷新”三连
  • 深度学习周报(7.28~8.3)
  • 【机器学习③】 | CNN篇
  • 分享链接实现状态共享
  • 嵌入式相关书籍
  • Javaweb————Windows11系统和idea2023旗舰版手动配置Tomcat9全流程解析
  • FreeRTOS源码分析三:列表数据结构