如何設定 nginx 阻擋特定 ip / 網段存取,首先找到對應的 nginx configuration,

通常會在 /etc/nginx/sites-enabled/*.conf 或是預設的 /etc/nginx/nginx.conf

接著找到 server / location 區塊,加上 deny 語法

server {
    listen 443 ssl http2;
    server_name blog.camel2243.com
    # 阻擋特定 ip
    deny x.x.x.x
    ...
}

# 或者在指定的 location 區塊中
location / {
    # 阻擋 220.133.87.0 ~ 220.133.87.255 的所有 ip 
    deny 220.133.87.0/24;
    index index.php index.html index.htm;
    try_files $uri $uri/ /index.php?$args;
}

# 進階一點搭配 allow 的用法
server {
    listen 443 ssl http2;
    server_name blog.camel2243.com
    # 阻擋除了 ip 為 220.133.87.235 以外的 220.133.87.0 ~ 220.133.87.255 網段
    allow 220.133.87.235;
    deny 220.133.87.0/24;
    ...
}

1 Comment

Leave a Reply