首页 > 系统相关 >nginx高级篇之基于IP的访问限制

nginx高级篇之基于IP的访问限制

时间:2024-04-26 11:12:18浏览次数:19  
标签:www http 请求 nginx IP 访问 test root

一、基于IP的访问限制

官网

http://nginx.org/en/docs/http/ngx_http_access_module.html

1.配置语法

句法:    allow address | CIDR | unix: | all;
默认:    —
语境:    http, server, location,limit_except
允许访问指定的网络或地址。如果指定了特殊值unix:(1.5.1),则允许访问所有 UNIX 域套接字。

句法:    deny address | CIDR | unix: | all;
默认:    —
语境:    http, server, location,limit_except
拒绝对指定网络或地址的访问。如果指定了特殊值unix:(1.5.1),则拒绝所有 UNIX 域套接字的访问。



allow 和 deny有自上而下的加载顺序

2.只允许访问10.0.0.0/24网段

[root@test-88 /etc/nginx/conf.d]#vim allow_deny.conf
[root@test-88 /etc/nginx/conf.d]#cat allow_deny.conf 
server{
    listen 12121;
    server_name _;
    location / {
      root /www/allow_deny/;
      allow 10.0.0.0/24;
      deny all;
      index index.html;
} 
}
[root@test-88 /etc/nginx/conf.d]#



[root@test-88 /etc/nginx/conf.d]#mkdir -p /www/allow_deny
[root@test-88 /etc/nginx/conf.d]#echo 'hello,welcome allow_deny test' >> /www/allow_deny/index.html
[root@test-88 /etc/nginx/conf.d]#systemctl reload nginx



[root@master-61 ~]#curl 10.0.0.88:12121
hello,welcome allow_deny test

[root@master-61 ~]#curl 172.16.1.88:12121
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.24.0</center>
</body>
</html>
[root@master-61 ~]#

3.拒绝windows访问www域名

[root@web-9 /etc/nginx/conf.d]#cat www.yuchaoit.conf 
server {
    listen       80;
    server_name  www.yuchaoit.cn;
    charset utf-8;
    access_log /var/log/nginx/www.yuchaoit.log;
    error_log  /var/log/nginx/error.www.yuchaoit.log;
    error_page 404 /404.html;
    location / {
        root   /usr/share/nginx/html/game;
        index  index.html index.htm;
        deny 10.0.0.1;
        allow all;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

3.只允许windows访问,其他人拒绝

注意allow和deny的加载顺序是,自上而下加载;

[root@web-9 /etc/nginx/conf.d]#cat www.yuchaoit.conf 
server {
    listen       80;
    server_name  www.yuchaoit.cn;
    charset utf-8;
    access_log /var/log/nginx/www.yuchaoit.log;
    error_log  /var/log/nginx/error.www.yuchaoit.log;
    error_page 404 /404.html;
    location / {
        root   /usr/share/nginx/html/game;
        index  index.html index.htm;
        allow 10.0.0.1;
        deny all;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

二、基于用户认证的访问限制

有时候,我们一些站点内容想要进行授权查看,只能输入账号密码之后才能访问,例如一些重要的内网平台,CRM,CMDB,企业内部WIKI等等。

1.语法

https://nginx.org/en/docs/http/ngx_http_auth_basic_module.html

句法:    auth_basic string | off;
默认:    
auth_basic 关闭;
语境:    http, server, location,limit_except
启用使用“HTTP 基本身份验证”协议验证用户名和密码。
指定的参数用作realm. 参数值可以包含变量(1.3.10、1.2.7)。
特殊值off取消了auth_basic从先前配置级别继承的指令的效果。

句法:    auth_basic_user_file file;
默认:    —
语境:    http, server, location,limit_except

2.创建密码文件

htpasswd是Apache密码生成工具,Nginx支持auth_basic认证,因此我门可以将生成的密码用于Nginx中,输入一行命令即可安装:

yum -y install httpd-tools 

参数
-c 创建passwdfile.如果passwdfile 已经存在,那么它会重新写入并删去原有内容.
-b 命令行中一并输入用户名和密码而不是根据提示输入密码,可以看见明文,不需要交互

#创建认证文件,htpasswd -bc .access username password 

#在当前目录生成.access文件,用户名username,密码:password,默认采用MD5加密方式。

3.nginx调用密码文件

调用参数设置
# 开启功能模块,开启on关闭为off
auth_basic on;
# 指定密码配置文件
auth_basic_user_file /etc/nginx/auth_passwd;

实践

1.先安装工具
[root@test-88 ~]#yum install httpd-tools -y

2.免交互创建密码文件
[root@test-88 ~]#htpasswd -bc /etc/nginx/auth_passwd ycy001 ycy123123
Adding password for user ycy001


3.密码文件调用
[root@test-88 ~]#vim /etc/nginx/conf.d/allow_deny.conf 
[root@test-88 ~]#cat /etc/nginx/conf.d/allow_deny.conf 
server{
    listen 12121;
    server_name _;
    location / {
      root /www/allow_deny/;
      allow 10.0.0.0/24;
      deny all;
      index index.html;
      auth_basic on;
      auth_basic_user_file /etc/nginx/auth_passwd;
} 
}

4.重启nginx
[root@test-88 ~]#systemctl reload nginx


测试

三、nginx请求限制

1.官网模块

https://nginx.org/en/docs/http/ngx_http_limit_req_module.html

2.配置语法

限速规则语法
NGINX中文文档:https://docshome.gitbook.io/nginx-docs/he-xin-gong-neng/http/ngx_http_limit_req_module

CSDN:https://blog.csdn.net/qq_38408785/article/details/103403971

ngx_http_limit_req_module 模块(0.7.21)用于限制每个已定义 key 的请求处理速率,特别是来自单个 IP 地址请求的处理速率。限制机制采用了 leaky bucket (漏桶算法)方法完成。

3.参数示例

# 1.定义一个限速规则
# 定义限速区域,保持在10兆字节的区域one,该区域的平均处理请求每秒不能超过1个。
# $binary_remote_addr 变量的大小始终为 4 个字节,在64位机器上始终占用64字节
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_req_zone $binary_remote_addr zone=two:10m rate=1r/s;

参数解释
limit_req_zone        # 引用限速模块
binary_remote_addr    # 判定条件,远程的客户端IP
zone        # 定义限速区域名称,内存大小
rate        # 限速规则,1秒只能1个请求


# 2.引用限速规则
limit_req zone=two  burst=5;  
limit_req # 引用哪一个限速区域

burst=5 # 令牌桶、平均每秒不超过 1 个请求,并且突发不超过5个请求。
nodelay  # 如果不希望排队堆积的请求过多,可以用这个参数。

4.实际用法

  • 限速规则是1秒一个请求
  • 提供3个vip特殊名额
[root@test-88 ~]#vim /etc/nginx/conf
[root@test-88 ~]#cat /etc/nginx/conf.d/allow_deny.conf 
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server{
    listen 12121;
    server_name _;
    access_log /var/log/nginx/limit_access.log;

    limit_req zone=one burst=3 nodelay;
    location / {
      root /www/allow_deny/;
      allow 10.0.0.0/24;
      deny all;
      index index.html;
} 
}


测试数据

四、nginx内置变量

官网
https://nginx.org/en/docs/varindex.html

学这些内置nginx变量,目的是为了在配置文件中使用,如

  • 日志功能会用
  • url跳转时用
$args                    #请求中的参数值
$query_string            #同 $args
$arg_NAME                #GET请求中NAME的值
$is_args                 #如果请求中有参数,值为"?",否则为空字符串
$uri                     #请求中的当前URI(不带请求参数,参数位于$args),可以不同于浏览器传递的$request_uri的值,它可以通过内部重定向,或者使用index指令进行修改,$uri不包含主机名,如"/foo/bar.html"。
$document_uri            #同 $uri
$document_root           #当前请求的文档根目录或别名
$host                    #优先级:HTTP请求行的主机名>"HOST"请求头字段>符合请求的服务器名
$hostname                #主机名
$https                   #如果开启了SSL安全模式,值为"on",否则为空字符串。
$binary_remote_addr      #客户端地址的二进制形式,固定长度为4个字节
$body_bytes_sent         #传输给客户端的字节数,响应头不计算在内;这个变量和Apache的mod_log_config模块中的"%B"参数保持兼容
$bytes_sent              #传输给客户端的字节数
$connection              #TCP连接的序列号
$connection_requests     #TCP连接当前的请求数量
$content_length          #"Content-Length" 请求头字段
$content_type            #"Content-Type" 请求头字段
$cookie_name             #cookie名称
$limit_rate              #用于设置响应的速度限制
$msec                    #当前的Unix时间戳
$nginx_version           #nginx版本
$pid                     #工作进程的PID
$pipe                    #如果请求来自管道通信,值为"p",否则为"."
$proxy_protocol_addr     #获取代理访问服务器的客户端地址,如果是直接访问,该值为空字符串
$realpath_root           #当前请求的文档根目录或别名的真实路径,会将所有符号连接转换为真实路径
$remote_addr             #客户端地址
$remote_port             #客户端端口
$remote_user             #用于HTTP基础认证服务的用户名
$request                 #代表客户端的请求地址
$request_body            #客户端的请求主体:此变量可在location中使用,将请求主体通过proxy_pass,fastcgi_pass,uwsgi_pass和scgi_pass传递给下一级的代理服务器
$request_body_file       #将客户端请求主体保存在临时文件中。文件处理结束后,此文件需删除。如果需要之一开启此功能,需要设置client_body_in_file_only。如果将次文件传递给后端的代理服务器,需要禁用request body,即设置proxy_pass_request_body off,fastcgi_pass_request_body off,uwsgi_pass_request_body off,or scgi_pass_request_body off
$request_completion      #如果请求成功,值为"OK",如果请求未完成或者请求不是一个范围请求的最后一部分,则为空
$request_filename        #当前连接请求的文件路径,由root或alias指令与URI请求生成
$request_length          #请求的长度 (包括请求的地址,http请求头和请求主体)
$request_method          #HTTP请求方法,通常为"GET"或"POST"
$request_time            #处理客户端请求使用的时间; 从读取客户端的第一个字节开始计时
$request_uri             #这个变量等于包含一些客户端请求参数的原始URI,它无法修改,请查看$uri更改或重写URI,不包含主机名,例如:"/cnphp/test.php?arg=freemouse"
$scheme                  #请求使用的Web协议,"http" 或 "https"
$server_addr             #服务器端地址,需要注意的是:为了避免访问linux系统内核,应将ip地址提前设置在配置文件中
$server_name             #服务器名
$server_port             #服务器端口
$server_protocol         #服务器的HTTP版本,通常为 "HTTP/1.0" 或 "HTTP/1.1"
$status                  #HTTP响应代码
$time_iso8601            #服务器时间的ISO 8610格式
$time_local              #服务器时间(LOG Format 格式)
$cookie_NAME             #客户端请求Header头中的cookie变量,前缀"$cookie_"加上cookie名称的变量,该变量的值即为cookie名称的值
$http_NAME               #匹配任意请求头字段;变量名中的后半部分NAME可以替换成任意请求头字段,如在配置文件中需要获取http请求头:"Accept-Language",$http_accept_language即可
$http_cookie
$http_post
$http_referer
$http_user_agent
$http_x_forwarded_for
$sent_http_NAME          #可以设置任意http响应头字段;变量名中的后半部分NAME可以替换成任意响应头字段,如需要设置响应头Content-length,$sent_http_content_length即可
$sent_http_cache_control
$sent_http_connection
$sent_http_content_type
$sent_http_keep_alive
$sent_http_last_modified
$sent_http_location
$sent_http_transfer_encoding

五、nginx添加第三方模块

1.理念

nginx除了支持内置模块,还支持第三方模块,但是第三方模块需要重新编译进nginx。
(重新生成nginx二进制命令)

1.如你的nginx默认不支持https
2.给你的nginx添加echo模块,用于打印nginx的变量。

2.编译添加echo模块

echo-nginx-module 模块可以在Nginx中用来输出一些信息,可以用来实现简单接口或者排错。

由于网络问题,建议该模块可以手动下载,编译安装

模块网址 https://github.com/openresty/echo-nginx-module

1.准备好nginx编译环境
[root@test-89 ~]#yum install pcre pcre-devel openssl openssl-devel  zli b zlib-devel gzip  gcc gcc-c++ make wget httpd-tools vim -y

2.设置www账号
[root@test-89 ~]#groupadd www -g 666
[root@test-89 ~]#useradd www -u 666 -g 666 -M -s /sbin/nologin
[root@test-89 ~]#id www
uid=666(www) gid=666(www) groups=666(www)
# 新建文件夹
[root@test-89 ~]#mkdir -p /nginx_addecho

3.下载echo模块
[root@test-89 /nginx_addecho]#yum install git -y
[root@test-89 /nginx_addecho]#git clone https://github.com/openresty/echo-nginx-module.git

[root@test-89 /nginx_addecho]#cp -r ./* /opt
[root@test-89 /nginx_addecho]#cd /opt
[root@test-89 /opt]#ls
echo-nginx-module
[root@test-89 /opt]#mkdir /opt/nginx-1-19-0

4.下载解压nginx
[root@test-89 /opt]#wget http://nginx.org/download/nginx-1.19.0.tar.gz
[root@test-89 /opt]#tar -zxf nginx-1.19.0.tar.gz 
[root@test-89 /opt]#ls
echo-nginx-module  nginx-1.19.0  nginx-1.19.0.tar.gz
5.编译nginx
[root@test-89 /opt]#cd nginx-1.19.0/
[root@test-89 /opt/nginx-1.19.0]#ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
[root@test-89 /opt/nginx-1.19.0]#./configure \
--user=www \
--group=www \
--prefix=/opt/nginx-1-19-0 \
--with-http_stub_status_module \
--with-http_ssl_module \
--with-pcre \
--add-module=/opt/echo-nginx-module


5.编译且安装
[root@test-89 /opt/nginx-1.19.0]#make && make install


6.新建软链接
[root@test-89 /opt]#ln -s /opt/nginx-1-19-0/sbin/nginx /usr/sbin/

7.查看模块
[root@test-89 /opt]#nginx -V
nginx version: nginx/1.19.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --user=www --group=www --prefix=/opt/nginx-1-19-0 --with-http_stub_status_module --with-http_ssl_module --with-pcre --add-module=/opt/echo-nginx-module

3.创建新配置文件,验证echo模块

server{
  listen 12321;
  server_name _;
    location / {
       echo "nginx echo welcome you!";
       echo $uri;
       echo $document_uri;
       echo $remote_addr;
       echo $remote_port;
       echo $http_user_agent;
    }
}

[root@test-89 /opt]#nginx -t
nginx: the configuration file /opt/nginx-1-19-0/conf/nginx.conf syntax is ok
nginx: configuration file /opt/nginx-1-19-0/conf/nginx.conf test is successful

      

4.客户端访问

[root@test-89 /opt]#nginx
[root@test-89 /opt]#ps -ef |grep nginx
root       4987      1  0 01:31 ?        00:00:00 nginx: master process nginx
www        4988   4987  0 01:31 ?        00:00:00 nginx: worker process
root       4990   1468  0 01:31 pts/0    00:00:00 grep --color=auto nginx


[root@test-88 ~]#curl 10.0.0.89:12321
nginx echo welcome you!
/
/
10.0.0.88
33226
curl/7.29.0

标签:www,http,请求,nginx,IP,访问,test,root
From: https://www.cnblogs.com/yechangyao/p/18159571

相关文章

  • linux配置网络环境(固定ip)
    通过cd/etc/sysconfig/network-scripts/查看网络配置输入viifcfg-ens33(主机的网卡文件夹)https://blog.csdn.net/hold_on_qlc/article/details/130440562 然后查看https://blog.csdn.net/2201_75288693/article/details/133097221修改网卡模式为 BOOTPROTO=static修改启......
  • 支付宝JavaScript跳转领取红包
    代码如下<!DOCTYPEhtml><html><head> <title>赚钱红包</title> <metacharset="utf-8"> <metaname="wechat-enable-text-zoom-em"content="true"> <metahttp-equiv="Content-Type"......
  • GatewayWorker 配置 WSS 利用 nginx 代理 wss
    首先,本地开发的测试一般都能通信成功而且,如果客户端为【http】网络协议的网站,那么js代码基本就是类似——varws=newWebSocket("ws://47.104.110.54:8283");的连接方式出错率是很低的,基本不做赘述最大的难点,个人认为是WSS服务配置…【操作环境】系统:......
  • pyclipper的多边形操作(转载)
    等距离缩放多边形:参考博客:https://blog.csdn.net/jizhidexiaoming/article/details/134435885 文本检测DBnet中对标签的预处理里面需要用到这个操作:将文本标注框等距离缩放用于生成标签二值图像和阈值图像,如下所示: 备注:上图出自Dbnet论文原来python有个库pyclipper自带这......
  • NFT tokenURI使用去中心化IPFS链接
    前言tokenURI指向存放NFTMetadata信息的json文件所在的URLjson文件最好用去中心化方式存储,例如IPFS 使用IPFS存储文件自己搭建IPFS需要下载客户端和保持节点运行较麻烦,我们可采用第三方服务商提供的服务例如Pinata、4everland等,我们以4everland(4everland.org)......
  • Nginx 配置文件 nginx.conf
    #帮助限制Nginx进程的权限,从而减少系统遭受恶意攻击的风险#通常,出于安全考虑,推荐不使用root用户运行网络服务#user<username>[groupname];#设置Nginx将启动的工作进程数目(默认为1)#worker_processes7;#可以填数字#worker_processesauto;#auto代表......
  • system-v IPC共享内存通信
    目录systemvIPC简介共享内存需要用到的函数接口shmget函数--获取对象IDshmat函数--获得映射空间shmctl函数--释放资源共享内存实现思路注意systemvIPC简介消息队列、共享内存和信号量统称为systemvIPC(进程间通信机制),V是罗马数字5,是UNIX的AT&T分支的其中一个版本,一般称它......
  • 2023最新!nginx安装配置保姆级教程
    2023最新!nginx安装配置保姆级教程这篇文章了参考了这位的教程:https://blog.csdn.net/qq_36838700/article/details/129971765导航目录2023最新!nginx安装配置保姆级教程一、nginx下载二、编译安装nginx安装pcre安装openssl、zlib、gcc依赖安装nginx二、拓展一、nginx下载......
  • github只下载某个文件或文件夹(使用GitZip插件)
    安装GitZip插件(此安装过程需要梯子(不懂“梯子”,百度一下就明白))1.打开插件管理页面方法一:打开Chrome浏览器(Edge浏览器同理),在Chrom地址栏输入chrome://extensions/,或edge地址栏edge://extensions/进入插件管理页面。方法二:直接Chrome浏览器找管理页面(Edge浏览器同理)......
  • 论文笔记-Non-intrusive classification of gas-liquid flow regimes in an S-shaped
    目标:使用深度神经网络对S形立管中的流态进行分类该分类器与四种传统的机器学习分类器进行了比较:即AdaBoost分类器、bagging分类器、额外树分类器和决策树分类器小波分析在流态分类中的应用可以有效地提取多相流行为的特征。使用信号处理方法进行流态分类,包括峰值点计数、......