欢迎来到站长天空!

其它服务器

当前位置: 主页 > 服务器 > 其它服务器

nginx中封禁ip和允许内网ip访问的实现示例

时间:2025-12-20 07:30:05|栏目:其它服务器|点击:

目录
  • 一、语法
  • 二、封禁ip
  • 三、仅内网IP访问

Nginx不仅仅只是一款反向代理和负载均衡服务器,它还能提供很多强大的功能,例如:限流、缓存、黑白名单和灰度发布等等,我们先来了解一下nginx如何封禁ip和允许内网ip访问。

一、语法

Nginx的ngx_http_access_module 模块可以封配置内的ip或者ip段

deny IP; 
deny subnet; 
allow IP; 
allow subnet; 
# block all ips 
deny    all; 
# allow all ips 
allow    all;

二、封禁ip

假定nginx的目录在/usr/local/nginx/
首先要建一个封ip的配置文件blockips.conf,然后在文件中输入要封的ip 

deny 192.168.4.3; 
deny 31.42.145.0/24; 
deny 51.12.35.0/24;

然后保存此文件

并且打开nginx.conf文件,在http配置节内添加下面一行配置:

http {
    # 其他配置
 
    include blockips.conf;
}

测试现在的nginx配置文件是否是合法

/usr/local/nginx/sbin/nginx -t

如果配置没有问题,就会输出

the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok 
configuration file /usr/local/nginx/conf/nginx.conf test is successful

如果配置有问题就需要检查下哪儿有语法问题
如果没有问题,需要执行下面命令,让nginx重新载入配置文件 

/usr/local/nginx/sbin/nginx -s reload

三、仅内网IP访问

配置如下

下面配置中禁止了192.168.1.1,允许其他内网网段,然后deny all禁止其他所有ip。

location / { 
  # block one workstation 
  deny    192.168.1.1; 
  # allow anyone in 192.168.1.0/24 
  allow   192.168.1.0/24; 
  # drop rest of the world 
  deny    all; 
}

上一篇:Docker容器镜像加载及底层基本原理深入解析

栏    目:其它服务器

下一篇:Nginx中使用Lua脚本与图片的缩略图处理的实现

本文标题:nginx中封禁ip和允许内网ip访问的实现示例

本文地址:https://zz.feitang.co/server/32156.html

广告投放 | 联系我们 | 版权申明

申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:257218569 | 邮箱:257218569@qq.com

Copyright © 2018-2025 站长天空 版权所有 Powered by EyouCms冀ICP备14023439号