文章目录
Nginx进阶功能
一、Nginx处理http请求的流程
- 用户在浏览器输入域名,经过dns解析得到真实IP
- 用户客户端发起tcp连接
- 发送http请求报文,url信息
- Nginx根据监听端口接收请求
- 根据域名信息匹配配置文件
- 根据root指定路径查找代码
- 在代码路径下查找默认的首页文件
- 根据location匹配响应的URI,按照相应规则功能处理请求。
#Nginx不支持中文解决办法
编辑nginx主配置文件
vim /usr/local/nginx/conf/nginx.conf
charset utf-8;
#通过本地域名解析访问hosts文件
C:\Windows\System32\drivers\etc\hosts
10.0.0.11 www.test.com www.game.com
随后可实现域名访问
二、Nginx的进阶功能
1.Nginx的访问控制模块
- 作用:根据访问者的来源IP,限制访问
- 应用场景:一个网站的某些页面不希望别人访问,只允许特定IP访问
location的语法格式
location匹配uri路径 {
规则;
}
模块地址:https://nginx.org/en/docs/http/ngx_http_access_module.html
# 例子
location / {
deny 192.168.1.1; 黑名单
allow 192.168.1.0/24; 白名单
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}
# 案例1:location.dms.com/admin 不允许所有人访问
## 准备环境
mkdir /html/location
echo '测试' >/html/location/index.html
mkdir /html/location/admin
echo '123' >/html/location/admin/index.html
server {
listen 80;
server_name location.dms.com;
root /html/location;
index index.html;
location /admin {
deny all;
}
}
# 案例2:location.dms.com/admin 不允许所有人访问,只允许10.0.0.3来源ip访问
mkdir /html/location
echo '测试' >/html/location/index.html
mkdir /html/location/admin
echo '123' >/html/location/admin/index.html
server {
listen 80;
server_name location.dms.com;
root /html/location;
index index.html;
location /admin {
allow 10.0.0.3;
deny all;
}
}
2.Nginx的身份验证功能
- 作用:将一个特定的页面开启身份验证(登录)
- 应用场景:带有管理型的页面,不允许外人访问,内部人员可以访问
# 例子
location / {
auth_basic "closed site"; #定义登录页面提示信息
auth_basic_user_file conf/htpasswd; #定义存储账号密码的文件
}
# 案例:location.dms.com/admin 输入页面认证的账号密码
## 编辑配置文件
location /admin {
auth_basic "请输入用户名和密码";
auth_basic_user_file ./userfile;
}
## 通过htpasswd工具生成密码文件
1)安装工具
yum install httpd-tools -y
htpasswd -c /usr/local/nginx/conf/userfile dms #要和主配置文件在一个目录下
3.Nginx的文件列表功能
应用场景:文件共享,搭建镜像站
应用场景:文件共享,搭建镜像站
模块地址:https://nginx.org/en/docs/http/ngx_http_autoindex_module.html
# 例子:
location / {
autoindex on;
autoindex_exact_size off; #显示单位
autoindex_localtime on; #同步本地时间
autoindex_format json;
location /list {
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}
4.Nginx的状态页面
作用:用于实时展示当前Nginx处理任务的状况的
stub_status #开启状态页面
# location.dms.com/status 显示状态信息
location /status {
stub_status;
}
#七项指标
Active connections: 2 #当前正在连接中的数量
server accepts 47 #当前Nginx总接收到的请求数
handled 47 #当前Nginx总处理了的请求数
requests 207 #请求总量
Reading: 0 #当前正在进行数据读取的数量
Writing: 1 #当前正在进行数据写入的数量
Waiting: 1 #当前正处于等待状态的数量
三、location匹配uri的策略
location = /admin/ {
规则
}
=:精准匹配。所匹配路径必须和url中的路径一模一样才能匹配到。优先级最高
~: 模糊匹配。支持正则表达式
~*:支持正则表达式,不区分大小写
^~:优先匹配。前置匹配,优先级更高
~!:取反。
/:前缀匹配。URI路径匹配的开头
优先级:= > ^~ > ~ > /
四、目录别名
alias:命令别名。让命令变成别的命令的功能
DNS-CNAME:域名别名。一个域名变为访问另一个域名。
目录别名:用户访问的URL变为访问其他路径
应用场景:代码路径发生变化保证通过旧的URL依然能访问到新的路径
# 案例:location.dms.
location /test {
alias /html/location/laoliu/;
index index.html;
}
注意:
1.别名之后的路径要使用绝对路径
2.别名之后的路径结尾要加/号