nginx

关注公众号 jb51net

关闭
首页 > 网站技巧 > 服务器 > nginx > nginx拦截指定ip

nginx 拦截指定ip访问指定url的实现示例

作者:筏镜

本文主要介绍了nginx 拦截指定ip访问指定url的实现示例,使用$http_x_forwarded_for变量来获取客户端的真实IP地址,感兴趣的可以了解一下

这里需要注意的是一定要用$http_x_forwarded_for 这个变量

upstream myapp1 {  # 定义一个名为myapp1的服务器组  
        server backend1.example.com weight=5;  # 添加一个服务器,并设置权重为5  
        server backend2.example.com;  # 添加另一个服务器,权重默认为1  
        server backend3.example.com down;  # 将此服务器标记为down,不参与负载均衡  
        server backup1.example.com backup;  # 将此服务器作为备份服务器  
    }  

 location ^~ /api/ {
        #10\.182\.(?!25\.|26\.)[0-9.]+
       if ($http_x_forwarded_for ~ "^10\.182\.(25\.|26\.)[0-9.]+") {
          # 如果是,返回403禁止访问
          return 403;
      }
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_pass myapp1;
    }

禁止指定网站来访:

if ($http_referer ~* "要拦截的域名") {
    return 301 要跳转的域名;
}

限制指定目录扩展名后缀

location ~ ^/images/.*\.(php|php5|sh|pl|py)$
{
deny all;
}

location ~ ^/static/.*\.(php|php5|sh|pl|py)$
{
deny all;
}

禁止直接访问txt和doc文件

location ~* \.(txt|doc)$ {
if (-f $request_filename) {
root /data/www/www;
rewrite ^(.*) https://www.itbulu.com/ break;  #可以重定向到某个URL;
}
}
location ~* \.(txt|doc)$ {
root /data/www/www;
deny all;
}

禁止访问文件和目录

#禁止访问的文件或目录 
location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md) { 
return 404; 
}

排除某个目录不受限制

location ~ \.well-known{ 
allow all; 
}

禁止访问单个目录的命令

 location ~ ^/(static)/ {
deny all;
}

location ~ ^/static {
deny all;
}

禁止访问多个目录的配置

location ~ ^/(static|js) {
deny all;
}

禁止目录让外界访问

location ~ ^/mysql_loging/ {
allow 192.168.1.4;
deny all;
}

location ~ .*\.(php|php5)?$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

说明:该配置只允许192.168.1.4IP访问mysql_loging目录

限制IP和IP段

location / {
deny 192.168.0.4;
allow 192.168.1.0/16;
allow 10.0.0.0/24;
deny all;
}

说明:此限制是对某些IP做整个网站的限制访问。

非指定域名访问跳转

if ($host !~ ^www/.itbulu/.com$) {
rewrite ^(.*) http://www.baidu.com$1 permanent;
}

到此这篇关于nginx 拦截指定ip访问指定url的实现示例的文章就介绍到这了,更多相关nginx拦截指定ip内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文