centos

centos nginx如何禁止访问

小樊
45
2025-07-30 20:53:20
栏目: 智能运维

在CentOS系统中,使用Nginx禁止访问可以通过以下几种方法实现:

方法一:使用防火墙规则

  1. 安装并启用防火墙(如果尚未安装):

    sudo yum install firewalld
    sudo systemctl start firewalld
    sudo systemctl enable firewalld
    
  2. 添加防火墙规则以阻止特定IP或端口

    • 阻止特定IP访问:
      sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" reject'
      sudo firewall-cmd --reload
      
    • 阻止特定端口(例如80端口):
      sudo firewall-cmd --permanent --remove-port=80/tcp
      sudo firewall-cmd --reload
      

方法二:配置Nginx服务器块

  1. 编辑Nginx配置文件

    sudo vi /etc/nginx/nginx.conf
    
  2. server块中添加拒绝访问的规则

    server {
        listen 80;
        server_name example.com;
    
        location / {
            deny all;
        }
    
        location /blocked {
            return 403 "Forbidden";
        }
    }
    
  3. 重新加载Nginx配置

    sudo systemctl reload nginx
    

方法三:使用.htaccess文件(适用于Apache,但可以通过Nginx的try_files指令模拟)

虽然Nginx不使用.htaccess文件,但可以通过try_files指令实现类似效果:

server {
    listen 80;
    server_name example.com;

    location / {
        try_files $uri $uri/ =404;
    }

    location /blocked {
        return 403 "Forbidden";
    }
}

方法四:使用IP黑名单模块

如果你需要更复杂的IP黑名单管理,可以考虑使用Nginx的ngx_http_access_module模块。

  1. 安装模块(如果尚未安装):

    sudo yum install nginx-mod-http-access-log-module
    
  2. 配置Nginx

    server {
        listen 80;
        server_name example.com;
    
        location / {
            allow 192.168.1.1;  # 允许的IP
            deny all;           # 拒绝所有其他IP
        }
    }
    
  3. 重新加载Nginx配置

    sudo systemctl reload nginx
    

通过以上方法,你可以根据具体需求选择合适的方式来禁止访问Nginx服务器。

0
看了该问题的人还看了