Nginx-web系列

nginx 系列

一 简述

1.1 为什么要使用?

Nginx是一个开源且高性能、可靠的Http Web服务、代理服务。

开源: 直接获取源代码

高性能: 支持海量并发

可靠: 服务稳定

轻量级 占用内存小

长期稳定

Nginx和apache区别

服务 模型 区别 特点
Nginx Epool 异步模型 处理用户请求时 优先放在缓存中 epool模型会直接进行处理 效率高 处理高并发时 性能很好 连接数无上限 复杂性中
Apache Select 同步模型 select模型就会进行一次遍历扫描,逐个执行,从而导致性能低下。 连接数高并发时 性能急剧下降 连接数 有限

1.2 主要用于哪里?

  • nginx web服务
  • 负载均衡服务
  • nginx 缓存服务

二. Nginx 搭建环境

2.1 版本选择

  • 开源软件选择: 选择活跃,资料多

  • 版本选择: 最新稳定版本(stable),上一个最新稳定版, 最新的 lts 版本(长期

    • 维护版本)

2.2 环境准备

服务器名称 IP地址 软件
web01 10.0.0.101 nginx
web02 10.0.0.102 nginx

2.2 yum 直装

#01 配置yum 源
nginx 源  http://nginx.org/en/linux_packages.html#RHEL-CentOS
[root@node02 yum.repos.d]# cat nginx.repo 
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true		
		

#02 安装即可
[root@node02 yum.repos.d]# yum install -y nginx


2.3 nginx 目录结构

#03 下载的配置文件清单
[root@aliyun ~]# rpm -ql nginx
/etc/nginx											#主要配置文件目录
/etc/nginx/conf.d								#分支配置文件 (主配置文件的一部分)
/etc/nginx/conf.d/default.conf	#默认配置文件
/etc/nginx/fastcgi_params				#nginx与fastcgi(php) 配合使用的文件		
/etc/nginx/mime.types						#媒体类型文件
/etc/nginx/modules							#模块
/etc/nginx/nginx.conf						#主配置文件
/etc/nginx/scgi_params					#ngixn与scg配合使用的文件
/etc/nginx/uwsgi_params					#nginx与uwsgi(python) 配合使用的文件


/usr/sbin/nginx									#二进制文件 nginx命令

/usr/share/nginx/html						#默认的站点目录(网站的根目录)
/var/cache/nginx								#缓存 临时文件
/var/log/nginx									#日志目录


/usr/lib/systemd/system/nginx.service	 	#systemctl 服务管理文件

2.4 简单使用

  • 启动服务
#开启服务并开机自启动
systemctl start nginx
systemctl enable  nginx


#检查端口 默认监听的 80 端口
[root@web01 ~]# ss -lntup |grep nginx 
ps -aux | grep nginx


#检查对应进程
[root@node02 yum.repos.d]# ps -ef | grep nginx
root       1974      1  0 21:27 ?        00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx      1975   1974  0 21:27 ?        00:00:00 nginx: worker process
nginx      1976   1974  0 21:27 ?        00:00:00 nginx: worker process
root       1987   1721  0 21:30 pts/1    00:00:00 grep --color=auto nginx

#检查版本
[root@node02 yum.repos.d]# nginx -v
nginx version: nginx/1.24.0

  • 代码上线

#01 删除默认代码
[root@node02 yum.repos.d]# cd  /usr/share/nginx/html
[root@node02 html]# rm -rf *

#02 下载代码到指定位置
[root@node02 html]# wget  http://192.168.31.46/download/game/xiaoniaofeifei.zip



#03 解压代码并删除压缩包
[root@node02 html]# unzip xiaoniaofeifei.zip 
Archive:  xiaoniaofeifei.zip
  inflating: sound1.mp3              
   creating: img/
  inflating: img/bg1.jpg             
  inflating: img/bg2.jpg             
  inflating: img/number1.png         
  inflating: img/number2.png         
  inflating: img/s1.png              
  inflating: img/s2.png              
  inflating: 21.js                   
  inflating: 2000.png                
  inflating: icon.png                
  inflating: index.html 
  
  
#浏览器访问
http://10.0.0.101/game/

image-20230816120512510

四 nginx 配置文件

4.1 主配置文件 nginx.conf

#主配置文件详解
[root@aliyun ~]#  cat /etc/nginx/nginx.conf

user  nginx;																	#nginx 运行进程的用户
worker_processes  auto;												#worker 进程的数量 处理用户请求(一般时cpu核心总数的2倍)

error_log  /var/log/nginx/error.log notice;		#错误日志error 位置 notice
pid        /var/run/nginx.pid;								#进程pid的位置


events {																			#events 模块/区域
    worker_connections  1024;									#每个worker进程最大的连接数(并发)
}


http {																				#http 模块/区域 
    include       /etc/nginx/mime.types;			#媒体类型(文件类型) include引用或者包含其它地方的配置 精简nginx主配置文件
    default_type  application/octet-stream;		#默认的文件类型(媒体类型)

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '		#指定访问日志的格式 
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;	#访问日志 access_log 指定日志的位置和格式mail 

    sendfile        on;												#开启高效的传输模式
    #tcp_nopush     on;
    keepalive_timeout  65;										#keepalive 长连接超时时间(s)

    #gzip  on;																#是否开启gzip压缩 静态文本内容(节省带宽资源)

    include /etc/nginx/conf.d/*.conf;					#引用conf.d/*.conf 结尾的文件
}

4.2 server 配置文件

#01 配置详解
[root@web01 nginx]$ cat /etc/nginx/conf.d/default.conf 
server {											#server 区域
	listen       80;						#监听端口
	server_name  localhost;   	#域名 www.zhangyuzhou.cn localhost 本地默认

	access_log  /var/log/nginx/host.access.log  main;   #给某一个server或者网站 配置日志 

	location / {													#用来匹配uri  访问文件在系统那个文件    location/ 默认值 
		root   /usr/share/nginx/html;   		#root指定网站站点目录(根目录)
		index  index.html index.htm;				#index 指定网站的首页文件
	}
	error_page   500 502 503 504  /50x.html;    #错误页面 
	location = /50x.html {
		root   /usr/share/nginx/html;
	}
}

  • 主配置文件图示

image-20230816122040244

  • server图示

image-20230816122101112

五. nginx 虚拟主机 server

5.1 定义

虚拟主机方式
基于域名的虚拟主机 不同的域名访问不同的站点
基于IP的虚拟主机 不同的ip地址可以访问不同的站点
基于端口的虚拟主机 不同的端口可以访问不同的站点 用于隐藏重要路径或业务
#01 虚拟主机
虚拟主机:nginx配置中多个server{}区域,每个server{}对应不同的业务{站点} 

5.2 基于域名虚拟主机

  • 需求

image-20230816142545785

  • 开始配置
#要求 基于域名配置主机 要求访问不同域名返回对应的值
/code/www   www.zhangyuzhou.com       返回内容  My domain name is www.zhangyuzhou.com
/code/game  game.zhangyuzhou.com	    返回内容  My domain name is game.zhangyuzhou.com
/code/live  live.zhangyuzhou.com      返回内容  My domain name is live.zhangyuzhou.com



#01 备份原来的配置文件
[root@node02 conf.d]# mv default.conf default.conf.bak

#02 书写nginx 配置文件 配置server 
[root@kq_mysql ~]# cd /etc/nginx/conf.d/
[root@kq_mysql conf.d]# cat www.conf
server {
	  listen   80;
	  server_name www.zhangyuzhou.com;

	  location / {
	   root /code/www;
	   index  index.html index.htm;
	 }
}

[root@kq_mysql conf.d]# cat game.conf
server {
	  listen   80;
	  server_name game.zhangyuzhou.com;

	  location / {
	   root /code/game;
	   index  index.html index.html;
	 }
}

[root@kq_mysql conf.d]# cat live.conf
server {
	  listen   80;
	  server_name live.zhangyuzhou.com;

	  location / {
	   root /code/live;
	   index  index.html index.html;
	 }
}


#02 创建站点数据目录
mkdir -p /code/{game,www,live}
echo 'My domain name is www.zhangyuzhou.com' >/code/www/index.html
echo 'My domain name is game.zhangyuzhou.com' >/code/game/index.html
echo 'My domain name is live.zhangyuzhou.com' >/code/live/index.html


#03 检查语法并重载服务
[root@kq_mysql conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

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

#04 修改本地hosts文件 增加dns解析
vim /etc/hosts
10.0.0.101  www.zhangyuzhou.com  game.zhangyuzhou.com live.zhangyuzhou.com

echo "10.0.0.101  www.zhangyuzhou.com  game.zhangyuzhou.com live.zhangyuzhou.com" >>/etc/hosts


#05 本机测试
curl www.zhangyuzhou.com
curl game.zhangyuzhou.com
curl live.zhangyuzhou.com

[root@kq_mysql conf.d]# curl www.zhangyuzhou.com
My domain name is www.zhangyuzhou.com
[root@kq_mysql conf.d]# curl game.zhangyuzhou.com
My domain name is game.zhangyuzhou.com
[root@kq_mysql conf.d]# curl live.zhangyuzhou.com
My domain name is live.zhangyuzhou.com

  • web页面访问 需要增加windeows hosts解析
#01 windows 路径
C:\Windows\System32\drivers\etc\hosts

添加下面内容

10.0.0.101  www.zhangyuzhou.com  game.zhangyuzhou.com live.zhangyuzhou.com


#02 页面访问即可
www.zhangyuzhou.com
game.zhangyuzhou.com
live.zhangyuzhou.com


5.3 基于ip虚拟主机

image-20230817135109970

  • 添加IP
#02 增加 ip addr 
1) 增加临时IP
[root@node02 conf.d]# ip addr add 10.0.0.112/24 dev ens32 label ens32:0
[root@node02 conf.d]# ip addr add 10.0.0.122/24 dev ens32 label ens32:1

2)删除IP
ip addr del  10.0.0.112/24 dev ens32 label ens32:0
ip addr del  10.0.0.122/24 dev ens32 label ens32:1

  • 开始配置
#01 要求 基于ip 配置主机 要求访问不同ip 返回对应的值
/code/www   10.0.0.102      返回内容  My domain name is www.zhangyuzhou.com
/code/game  10.0.0.112	    返回内容  My domain name is game.zhangyuzhou.com
/code/live  10.0.0.122      返回内容  My domain name is live.zhangyuzhou.com


#02 书写nginx 配置文件 配置server 
[root@kq_mysql ~]# cd /etc/nginx/conf.d/
[root@node02 conf.d]# cat *.conf
server {
	listen 80;
	server_name 10.0.0.102;
	
	location / {
	root /code/www;
	index index.html index.htm;
}
}
server {
	listen 80;
	server_name 10.0.0.112;
	
	location / {
	root /code/game;
	index index.html index.htm;
}
}
server {
	listen 80;
	server_name 10.0.0.122;
	
	location / {
	root /code/live;
	index index.html index.htm;
}
}

#03 检查语法并重载服务
[root@kq_mysql conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@kq_mysql conf.d]# nginx -s reload

#04 页面访问
curl 10.0.0.101
curl 10.0.0.121
curl 10.0.0.131


  • Web 页面访问即可

5.3 基于端口虚拟主机

#01 要求 基于端口 配置主机 要求访问不同端口 返回对应的值
/code/www   80      返回内容  My domain name is 80
/code/game  81	    返回内容  My domain name is 81
/code/live  82      返回内容  My domain name is 82

#02 
[root@kq_mysql conf.d]# cat www.conf
server {
	  listen   80;
	  server_name 10.0.0.101;

	  location / {
	   root /code/www;
	   index  index.html index.html;
	 }
}

[root@kq_mysql conf.d]# cat game.conf
server {
	  listen   81;
	  server_name 10.0.0.101;

	  location / {
	   root /code/game;
	   index  index.html index.html;
	 }
}

[root@kq_mysql conf.d]# cat live.conf
server {
	  listen   82;
	  server_name 10.0.0.101;

	  location / {
	   root /code/live;
	   index  index.html index.html;
	 }
}


#03 检查语法并重载服务
[root@kq_mysql conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@kq_mysql conf.d]# nginx -s reload

#04 访问测试
curl 10.0.0.101
curl 10.0.0.101:81
curl 10.0.0.101:82

  • web 页面直接访问即可

六. nginx日志详解

6.1 定义

#01 默认位置
访问日志: /var/log/nginx/access.log
错误日志: /var/log/nginx/error.log

#02 定义
访问日志的格式: log_format 设置 nginx访问日志的格式
设置(开启)访问日志 access_log 


6.2 log_format日志格式

#01 位置
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

#02 格式说明
log_format 格式 :
	$remote_addr  		客户端ip 地址 
	$remote_user  		远程的用户(一般是空的)
	$time_local	  		时间  11/May/2021:10:23:35 +0800
	$request	  		请求报文的起始行 + uri+ 协议  
	$status 	  		响应报文的状态码 
	$body_bytes_sent	http 响应报文的主体大小(服务器给你发送文件的大小 单位字节)
	$http_referer		从哪里跳转到你的网站 (分析用户的来源 可以精确的投放广告 :比如通过百度搜索 访问的 或者其它渠道)
	$http_user_agent	用户的代理 (浏览器 类型)
	$http_x_forwarded_for  记录用户ip 真实地址
	

#03 例如
10.0.0.7 - - [11/May/2021:10:29:19 +0800] "GET / HTTP/1.1" 200 16 "-" "curl/7.29.0" "-"

6.3 访问日志 access_log

  • 语法说明
Syntax: access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]]; access_log off;
Default: access_log logs/access.log combined;
Context: http, server, location, if in location, limit_except
#01 配置参数
access_log配置
格式:
	buffer=size gzip=lecel flush=time if=condition;
	#access_log off;
	access_log /var/log/nginx/www_access.log main ;
	

解释下:
			path 						#是路径
			format 					#日志格式
			gzip						#是否压缩 注压缩后日志最好命名为access.log.gz
			fush 						#保存在缓存区中的最长时间 定时更新到磁盘 单位s 秒
			buffer					#设置内存缓存区大小
			access_log off; #关闭日志

  • 简单使用 配置访问日志
#案例01 要求先放进缓存区 3秒后写入磁盘 日志位置 /var/log/nginx/www_access.log
#01 书写配置文件 
[root@kq_mysql conf.d]# cat www.conf
server {
	  listen   80;
	  server_name 10.0.0.101;
    access_log /var/log/nginx/www_access.log main
	  buffer=128 flush=3;
	  location / {
	   root /code/www;
	   index  index.html index.html;
	 }
}

#02 重载服务并运行测试
nginx -t
nginx -s reload
curl 10.0.0.101
[root@kq_mysql conf.d]# cat /var/log/nginx/www_access.log
10.0.0.101 - - [16/Aug/2023:15:47:42 +0800] "GET / HTTP/1.1" 200 38 "-" "curl/7.29.0" "-"
10.0.0.101 - - [16/Aug/2023:15:47:43 +0800] "GET / HTTP/1.1" 200 38 "-" "curl/7.29.0" "-"
10.0.0.101 - - [16/Aug/2023:15:47:44 +0800] "GET / HTTP/1.1" 200 38 "-" "curl/7.29.0" "-"
10.0.0.101 - - [16/Aug/2023:15:47:44 +0800] "GET / HTTP/1.1" 200 38 "-" "curl/7.29.0" "-"



----

#案例02 要求压缩 日志先写入到缓存 每隔3s写入到磁盘
#01 书写配置文件
[root@kq_mysql conf.d]# cat www.conf
server {
	  listen   80;
	  server_name 10.0.0.101;
          access_log /var/log/nginx/www_access.log.gz main
	  gzip buffer=128 flush=3;
	  location / {
	   root /code/www;
	   index  index.html index.html;
	 }
}

#02 检查并重启
[root@kq_mysql conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@kq_mysql conf.d]# nginx -s reload
[root@kq_mysql conf.d]# curl 10.0.0.101

#03 检查是否有压缩日志文件
[root@kq_mysql conf.d]# ll /var/log/nginx/
总用量 16
-rw-r--r-- 1 root root 552 8月  16 15:16 access.log
-rw-r--r-- 1 root root 533 8月  16 15:51 error.log
-rw-r--r-- 1 root root 460 8月  16 15:47 www_access.log
-rw-r--r-- 1 root root 574 8月  16 15:52 www_access.log.gz

#04 解压检查日志
gunzip /var/log/nginx/www_access.log.gz
cat /var/log/nginx/www_access.log.gz


6.4 错误日志格式

  • 语法
error_log 错误日志
syntax error_log file [level];
Default: error_log logs/error.log error;
Context: main , http , mail , stream , server ,
location
  • 简单使用
#01 配置错误日志 级别为 error
[root@kq_mysql nginx]# cat /etc/nginx/conf.d/www.conf
server {
	  listen   80;
	  server_name 10.0.0.101;
    access_log /var/log/nginx/www_access.log main;
	  location / {
	   root /code/www;
	   index  index.html index.html;
	 }
	error_log    /var/log/nginx/error_www.com.log   error;
}

#02 检查语法并重载
[root@kq_mysql nginx]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@kq_mysql nginx]# nginx -s reload

#03 估计写错 检查是否有error日志
[root@kq_mysql nginx]# curl 10.0.0.101/1123
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@kq_mysql nginx]# curl 10.0.0.101/1123333

#04 错误日志内容
[root@kq_mysql nginx]# cat error_www.com.log
2023/08/16 16:04:33 [error] 23963#23963: *27 open() "/code/www/1123" failed (2: No such file or directory), client: 10.0.0.101, server: 10.0.0.101, request: "GET /1123 HTTP/1.1", host: "10.0.0.101"
2023/08/16 16:04:36 [error] 23962#23962: *28 open() "/code/www/1123333" failed (2: No such file or directory), client: 10.0.0.101, server: 10.0.0.101, request: "GET /1123333 HTTP/1.1", host: "10.0.0.101"
2023/08/16 16:04:37 [error] 23962#23962: *29 open() "/code/www/1123333" failed (2: No such file or directory), client: 10.0.0.101, server: 10.0.0.101, request: "GET /1123333 HTTP/1.1", host: "10.0.0.101"


6.5 日志切割

#日志切割: 定期把切割成一个新的文件(加上日期). 避免日志过大
#如何实现:
##logrotate 命令 + /etc/logroate.d/配置文件
logroate -f /etc/logroate.d/nginx



[root@web01 nginx]$ cat /etc/logrotate.d/nginx
/var/log/nginx/*.log {  # 指定你要切割的文件
     dily				  	# 每天
     mssingok				# 如果日志不存在 则跳过 不显示错误信息
     rtate 52				# 最多保留多少个切割后的日志
     cmpress				# 日志是否压缩
     dlaycompress			# 延迟一个周期 然后再进行压缩
     ntifempty				# 如果日志是空的 则跳过
     ceate 640 nginx adm	# 日志的权限 所有者和所有组
     saredscripts
     pstrotate				# 日志轮询 (切割之后) 执行里面的命令
            if [ -f /var/run/nginx.pid ]; then
                    kill -USR1 `cat /var/run/nginx.pid`
            fi
        endscript
}

# 定期切割原理
系统定时任务 会每天都执行
[root@web01 nginx]$ cat  /etc/cron.daily/logrotate 
#!/bin/sh

/usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0


七. nginx处理请求流程

#01 流程如下
1. 用户输入url域名
2. DNS解析:查找域名对应的ip地址(获得域名对应的ip地址)
3. tcp3次握手:用户通过ip地址与对应的服务器建立连接(与服务器连接)
4. http请求报文(豹纹):建立tcp连接后,用户向服务器索要指定的内容(页面,
   图片,视频....) (向服务索要内容)
5. 服务器通过查找 (nginx如何处理请求)
6. http响应豹纹: 找到后把用户要的内容,返还给用户(服务型响应用户)
7. tcp4次挥手: 用户与服务器断开连接


#匹配相关 
nginx 处理请求流程	(使用域名)
	1 根据http请求报文 匹配到http 模块
	2 根据host 匹配对应的server 
	3 根据uri 匹配location  没有对应的location 就使用默认的
	最后跟进用户请求的uri 找出站点目录下面(root ) 目录和文件

八. nginx常用模块

8.1 autoindex 目录索引模块

  • 语法要求

  • autoindex_module

autoindex 是否开启目录索引功能

autoindex_exact_size 是否以人类可读形式显示大小(off), on(精确
显示)

使用场景:用户访问nginx的时候,可以像使用ftp工具一样,下载网站站点下面的文件

  • 简单使用
#01 配置server区 提供下载
cat ftp.conf
server {
				listen 80;
				server_name ftp.zhangyuzhou.com;
				charset utf-8;
				root /code;
				
			location /download {
				autoindex on;
			  autoindex_exact_size off;
	}
}


#02 注意需要做hosts解析
echo "10.0.0.101 ftp.zhangyuzhou.com" >>/etc/hosts

#03 传数据到下载的站点目录
mkdir -p /code/download/
echo '123' >>/code/download/test.txt

#04 检查重载并下载
nginx -t
nginx -s reload

#04 页面访问
ftp.zhangyuzhou.com/

8.2 nginx状态模块

  • ngx_http_stub_status_module 显示nginx状态
    • stub_status

stub_status nginx状态模块使用

格式 stub_status

context server,location

  • 简单使用
#01 添加状态模块
[root@web01 nginx]# cat /etc/nginx/conf.d/www.conf 
server {
  listen   80;
  server_name www.zhangyuzhou.com;  
  access_log /var/log/nginx/www_access.log main ;
    location  / {
    root /code/www ;
    index  index.html index.html;
}

  location  /favicon.ico {
  access_log off;
  return 200 ;
}

 location /status  {	     #添加location 站点
  stub_status;             #添加stub_status
  } 
}

#02 检查并重启
ngxin -t 
nginx -s reload


#03 测试 curlwww.zhangyuzhou.com
[root@kq_mysql conf.d]#  curl www.zhangyuzhou.com/status
Active connections: 1
server accepts handled requests
 30 30 30
Reading: 0 Writing: 1 Waiting: 0



#04 stub_status 状态
Active connections: 3   #当前活动连接(已经连接的连接)								
server accepts			 		#已经接受的http请求(总数)	一般是和handled数量一致
	handled      		 			#已经处理的htp请求(总数)			
	requests    		 			#—共向我发送了多少请求(总数)			
	Reading: 0   		 			#当前正在读取用户请求头的数量(实时)			
	writing:1   		 			#当前正在发送响应报文的数量
	waiting 2    		 			#当前排队的数量
	
	

8.3 访问限制模块

ngx_http_access_module 访问限制模块

  • allow 准许 某个ip或网段访问

  • deny 拒绝

  • 使用allow和deny 完成白名单和黑名单功能

  • 白名单: allow,deny常用,用来限制核心目录,文件,禁止外界访问.

  • 黑名单:deny, 屏蔽ip地址.

  • 简单使用

#01 白名单 在名单中的可以访问
##先allow
##最后deny all

#02 书写配置
location /status {
    stub_status;
    access_log off;
    allow 172.16.1.0/24;
    allow 10.0.0.7;
    allow 127.0.0.1;
    deny all;
}

解释下:
		  deny all 除了已经授权允许的 其它的全部拒绝


#03 测试

8.4 auth_basic_user用户授权模块

  • ngx_http_auth_basic_module
  • 限制用户访问,访问的时候输入用户名和密码
auth_basic 显示登入提示
语法 auth_basic "提示信息" off
默认 auth_basic off;
context http , server , location , limit_except
auth_basic_user_file *file*
语法 auth_basic_user_file conf/htpasswd
默认
context http, server, location, limit_except
# 应用案例
#让用户访问 www.zhangyuzhou.com/status 需要输入用户名和密码

##创建nginx auth_basic_user_file 需要的密码文件

zhangyz 123456 conf.d/status.pass


# 实施步骤
# htpasswd  -b -c
-b  使用批处理方式,直接从命令行获取密码,不提示用户输入 
-c   创建密码文件,如果文件存在,那么内容被清空重写


创建密码文件
yum install -y httpd-tools
htpasswd -bc status.pass zhangyz 123456

# 修改密码文件权限 
chmod 600 status.pass
chown nginx.nginx status.pass

#修改配置文件
server	}
	...
	location /status  {
		stub_status;
		auth_basic "Input user password:";				# 给status模块 添加用户访问限制提示信息  "Input password"
	auth_basic_user_file conf.d/status.pass;  # 指定用户和密码文件
   ....

# 测试 
curl -u zhangyz:123456 www.zhangyuzhou.com/status 
	

  • 访问网站 测试

image-20230816170536685

  • 输入密码

image-20230816170636078

九.location 功能

  • 匹配用户请求中的uri.
location
语法 Syntax: location [ = |~| ~*| ^~] uri { ... }
location @name
上下文 server , location

特殊字符
location
= 精确匹配uri 优先级别 最高
^~ 匹配uri,不使用正侧表达式 高优先级
~ 区分大小写的正则匹配 优先级和~一致 谁在前面先匹配谁
~* 不区分大小写的正则匹配 (例如 location ~
.(jpg|png|gif)$ 匹配以.jpg或者.pnp结尾的所有内容
/ 通用匹配,默认:其它location匹配失败了 则会匹配这个 优先级最低

  正侧:用符号匹配有规律的内容 

  注意:location 不支持!= !~ !~*写法 这些需要在if中才能使用 
书写测试文件 location.conf
[root@centos7 conf.d]# cat location.conf
server {
 listen 80;
 server_name 192.168.5.14;
#	location / {
#	default_type text/html;
#	return 200 " B / " ;
#}

 	location = / {
   	default_type text/html;
   	return 200 " A = " ;

 }

 	location ^~ / {
   	default_type text/html;
   	return 200 " C  ";

 }


 	location ~ / {
  	default_type text/html;
  	return 200 " D ~ " ;

 }


 	location ~* / {
   	default_type text/html;
   	return 200 " E ~*" ;

 }

}


测试:curl -H Host:location.com 10.0.0.7 



10 LNMP部署系列

10.1 通用网站架构

1) 静态vs 动态

  • 静态资源(请求_: nginx自己处理的内容, html,js,css,图片,视频,音频.......
  • 动态资源(请求): 交互内容(评论,发布文章,订单,金钱) url连接中 包含
    特殊符号 & 符号 或 ? 符号
    • 动态请求需要开发语言处理: php,java,python,golang,......
静态 动态
处理 nginx/apache/tengine nginx+php/java/python/golang
数据存放 站点目录 站点目录+数据库+存储
url .html .css .js .png
.mp4 .....
含有 & ? 特殊符号
效率 效率高 速度快 效率低,处理缓慢,
是否容易被搜索引擎收入 容易被收入 不容易被收入.(伪静态:把动态url
伪装为静态url)

2) 常用架构

架构
LAMP LInux Apache MySQL(MariaDB) PHP (Fastcgi)
LNMP/LEMP LInux Nginx MySQL(MariaDB) PHP(Fastcgi)
LNMT Linux Nginx MySQL Tomcat/Jboss/Resin/(java)
Weblogic(配合Oracle数据苦)
LNMP Linux Nginx MySQL Python (Uwsgi)
LNM??? Linux Nginx MySQL 自己开发

10.2 LNMP原理

  1. 用户发出请求后,请求到达nginx
  2. 如果是静态请求,nginx自己处理
  3. 如果是动态请求nginx 根据 请求类型(php) 通过fastcgi_pass 动态请求
    交给 php-fpm(fastcgi)
  4. php-fpm收到请求后,传递给php解释器(与数据库交互)
  5. 解释后把结果传递给用户(解释器-->php-fpm--->nginx--->用户)
  6. 完成动态请求过程
  • php-fpm.conf 配置控制php-fpm进程
    php.ini 控制解释器

10.3 lnmp 环境准备

服务器 服务 网站 ip
Node01 nginx php mariadb shop,wordpess 10.0.0.101
##要求 部署电商和博客
使用虚拟用户 www
shop.zyz.com   --->> /code/shop
wordpess.zyz.com   --->> /code/work

#01 创建虚拟用户
useradd -s /sbin/nologin -M -u 1111 www
[root@centos7 ~]# id www
uid=1111(www) gid=1111(www) 组=1111(www)

#02 创建站点目录
mkdir -p /code/{shop,wordpess}
chown www.www -R /code

#03 添加本地hosts解析
echo '10.0.0.101 shop.zyz.com work.zyz.com ' >> /etc/hosts

#04 关闭防火墙
systemctl stop firewalld.service


1)数据库部署

#01 安装数据库
yum install -y mariadb mariadb-server

#02 启动数据库 并检查
systemctl start mariadb
ss -natl | grep 3306
LISTEN     0      50           *:3306                     *:*

#03 设置密码
[root@centos7 ~]# mysqladmin -u root password '123456'
[root@centos7 ~]# mysql -uroot -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3
Server version: 5.5.68-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> exit
Bye


#03 创建用户
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'  IDENTIFIED BY '123456'  WITH GRANT OPTION;

grant all on *.*   to  'all'@'%' identified by '123456';
flush privileges;
select user,host from mysql.user; 

#04 创建数据库
 create database wordpress ;
 create database shop ;

数据库地址 192.168.5.14
账户:all
密码:123456
库名称:wordpress
库名称:shop



----分隔符----

#04 数据库指令
	help show  		 查询帮助
	show databases ; 查看所有数据库  (show 例如:ll)		
	show tables ;	 查看表格
	use 		     进入目录  (use 例如:cd)
	select user,host from mysql.user;  查看当前数据库用户信息  select (字段 列) from 数据库,表
	create database wordpress ;  创建数据库
	drop user ''@'root' ;		删除用户


2)php部署


#01 卸载原来的php
[root@centos7 ~]# yum remove php-mysql-5.4 php php-fpm php-common

#02 配置php 源
[root@centos7 ~]# cat /etc/yum.repos.d/php.repo
[webtatic-php]
name = php Repository
baseurl = http://us-east.repo.webtatic.com/yum/el7/x86_64/
gpgcheck = 0

#03 下载php
yum -y install php71w php71w-cli php71w-common php71w-devel php71w-embedded php71w-gd php71w-mcrypt php71w-mbstring php71w-pdo php71w-xml php71w-fpm php71w-mysqlnd php71w-opcache 
yum install -y php71w-pecl-memcached php71w-pecl-redis php71w-pecl-mongodb

[root@centos7 ~]# rpm -qa | egrep 'php|nginx'
php71w-common-7.1.33-1.w7.x86_64
php71w-mysqlnd-7.1.33-1.w7.x86_64
php71w-mbstring-7.1.33-1.w7.x86_64
php71w-pecl-redis-3.1.6-1.w7.x86_64
nginx-filesystem-1.20.1-10.el7.noarch
php71w-cli-7.1.33-1.w7.x86_64
php71w-devel-7.1.33-1.w7.x86_64
mod_php71w-7.1.33-1.w7.x86_64
php71w-pdo-7.1.33-1.w7.x86_64
php71w-gd-7.1.33-1.w7.x86_64
php71w-mcrypt-7.1.33-1.w7.x86_64
php71w-fpm-7.1.33-1.w7.x86_64
php71w-process-7.1.33-1.w7.x86_64
php71w-pecl-igbinary-2.0.5-1.w7.x86_64
php71w-pecl-memcached-3.0.4-1.w7.x86_64
nginx-1.20.1-10.el7.x86_64
php71w-embedded-7.1.33-1.w7.x86_64
php71w-xml-7.1.33-1.w7.x86_64
php71w-opcache-7.1.33-1.w7.x86_64
php71w-pear-1.10.4-1.w7.noarch
php71w-pecl-mongodb-1.5.3-1.w7.x86_64


#04 修改php默认启动用户
[root@centos7 ~]# sed -i 's#apache;#www;#g' /etc/nginx/nginx.conf
[root@centos7 ~]#  egrep '^(user|group)' /etc/php-fpm.d/www.conf
user = apache
group = apache

#04 启动服务
systemctl start  php-fpm.service 
systemctl enable   php-fpm.service 

#05 检查进程
[root@centos7 ~]# ps -ef | grep php
root     17521     1  1 16:14 ?        00:00:00 php-fpm: master process (/etc/php-fpm.conf)
apache   17522 17521  0 16:14 ?        00:00:00 php-fpm: pool www
apache   17523 17521  0 16:14 ?        00:00:00 php-fpm: pool www
apache   17524 17521  0 16:14 ?        00:00:00 php-fpm: pool www
apache   17525 17521  0 16:14 ?        00:00:00 php-fpm: pool www
apache   17526 17521  0 16:14 ?        00:00:00 php-fpm: pool www
root     17594  2297  0 16:14 pts/1    00:00:00 grep --color=auto php

3)nginx 部署

  • wordpess

#01 下载nginx 并替换默认启动用户
[root@centos7 conf.d]# yum insatll -y nginx
[root@centos7 conf.d]# sed -i 's#user nginx;#user www;#g' /etc/nginx/nginx.conf
[root@centos7 conf.d]# egrep '^(user)' /etc/nginx/nginx.conf
user www;


#01 书写配置文件
[root@centos7 conf.d]# cat wordpess.conf
server {
	listen 80;
	server_name wordpess.zyz.com;
	access_log /var/log/nginx/blog_access.log main;
	error_log /var/log/nginx/blog_error.log notice;
	root /code/wordpess;
	location / {
	index index.html index.php;
	}
	location ~ \.php$ {
	fastcgi_pass 127.0.0.1:9000;
	fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
	include  fastcgi_params ;
	}	
}


#03 上传代码
cd /code/wordpess
wget http://192.168.1.159/download/game/%E5%8D%9A%E5%AE%A2.tar.gz
tar xf 博客.tar.gz
mv wordpress/* ./
rm -rf wordpress

#04 启动nginx 并检查
systemctl start nginx
 
 

  • 页面访问

image-20230818163058016

  • 站点信息

image-20230818163555077

  • shop

#01 书写配置文件
[root@web-101 conf.d]$ cat shop.zyz.com.conf 
server {
	listen 80;
	server_name shop.zyz.com;
	access_log /var/log/nginx/shop_access.log main;
	error_log /var/log/nginx/shop_error.log notice;
	root /code/phpshe;
	location / {
	index index.html index.php;
	}
	location ~ \.php$ {
	fastcgi_pass 127.0.0.1:9000;
	fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
	include  fastcgi_params ;
	}	
}

nginx -t
nginx -s reload

#02 代码上线 
cd /code/shop
wget http://192.168.1.159/download/game/dianshang.zip
rm -f dianshang.zipmv
dianshang/* ./
chown www.www -R /code


#03 测试


[root@centos7 shop]# cat config.php
<?php
$pe['db_host'] = '192.168.5.14'; //数据库主机地址
$pe['db_name'] = 'shop'; //数据库名称
$pe['db_user'] = 'all'; //数据库用户名
$pe['db_pw'] = '123456'; //数据库密码
$pe['db_coding'] = 'utf8';
$pe['url_model'] = 'pathinfo_safe'; //url模式,可选项(pathinfo/pathinfo_safe/php)
define('dbpre','pe_'); //数据库表前缀




# 修改权限 
[root@centos7 shop]# mkdir -p /var/lib/php/session
[root@centos7 shop]# chown -R www.www /var/lib/php/session

posted @   宁采臣open  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示