Nginx禁用IP和IP段

前言:因最近项目需要,现在个别IP可以访问服务器,例如75前端服务器访问两台后端服务器+文件服务器,两台后端服务器访问两台数据库服务器,任何IP可以访问前端等。

Nginx除了反向代理和负载均衡,还可以限流、缓存、黑白名单、灰度发布、禁用IP等

下面重点讲述下Nginx禁用IP和IP段

1. 禁用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;

如果规则之间有冲突,会以最前面匹配的规则为准。

2. 配置禁用ip和ip段具体做法

一般nginx的目录在/usr/local/nginx/,先建一个封ip的配置文件blockips.conf,然后vi blockips.conf编辑此文件,在文件中输入要封的ip。

deny 10.128.231.XX;

deny 10.128.231.XX;

然后打开nginx.conf文件,在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

3.针对某个网站单独设置

当Nginx代理了很多网站时,有的我们想让所有人访问,有的想让部分人访问,那么上面的设置就不能满足我们的需求了,我们可以来到每个网站的代理配置文件,针对当前网站单独设置

比如,现在我们网站的代理配置是这样的:

server {

listen 80;

server_name wx-service;

location / {

root /usr/share/nginx/html/test;

index index.html index.htm;

}

}

当我们想只对这个网站进行禁止或允许的配置时,我们可以在server{}段中添加一行配置

server {

listen 80;

server_name wx-service;

allow 10.128.231.XX;

deny all;

location / {

root /usr/share/nginx/html/test;

index index.html index.htm;

}

}

4. 格式化nginx的403页面

首先执行下面的命令:

cd /usr/local/nginx/html

vi error403.html

然后输入403的文件内容,例如:

<html>

<head><title>Error 403 - IP Address Blocked</title></head>

<body>

Your IP Address is blocked.

</body>

</html>

参考:https://www.cnblogs.com/binghe001/p/13293032.html#:~:text=%E7%A6%81%E7%94%A8IP%E5%92%8CIP%E6%AE%B5%20Nginx%E7%9A%84ngx_http_access_module%20%E6%A8%A1%E5%9D%97%E5%8F%AF%E4%BB%A5%E5%B0%81%E9%85%8D%E7%BD%AE%E5%86%85%E7%9A%84ip%E6%88%96%E8%80%85ip%E6%AE%B5%EF%BC%8C%E8%AF%AD%E6%B3%95%E5%A6%82%E4%B8%8B%EF%BC%9A%20deny%20IP%3B%20deny%20subnet%3B,allow%20IP%3B%20allow%20subnet%3B%20%23%20block%20all%20ips

相关推荐
jc06201 小时前
4.5-中间件之Nginx
运维·服务器·nginx
青鱼入云7 小时前
对比nginx、kong、apisix、zuul、gateway网关
nginx·gateway·kong
程序员勾践1 天前
安装nginx
linux·nginx·centos
fxshy1 天前
CentOS 7上安装并配置Nginx监听81端口的完整指南
linux·nginx·centos
比特森林探险记2 天前
Nginx+Lua动态加载黑名单
nginx·junit·lua
惘嘫、冋渞3 天前
CentOS 7 下 Nginx 编译后热重启方案
chrome·nginx·centos
码农-小林3 天前
使用leaflet库加载服务器离线地图瓦片(这边以本地nginx服务器为例)
运维·服务器·nginx
阑梦清川3 天前
docker入门教程--部署nginx和tomcat
nginx·docker·tomcat
fruge4 天前
Ubuntu服务器已下载Nginx安装包的安装指南
服务器·nginx·ubuntu
siriuuus4 天前
Linux Tomcat 简单使用及 Nginx 反向代理
linux·nginx·tomcat