仅允许通过NGINX中的IP白名单访问某些位置

Mit*_*one 4 subdomain wordpress nginx multisite

我正在使用Sucuri扫描仪通知我登录尝试失败,我目前每天收到大约50封以上的电子邮件.我已经尝试了几种不同的方法来阻止访问wp-login.phpwp-admin而没有任何运气,因为我认为这些规则可能不适用于子域(或者通常只是吮吸).

server {
    # Primary domain, secondary domain and subdomains are explicitly 
    # declared so that I can generate certs using CertBot
    server_name primarydomain.com
                secondarydomain.com
                subdomain1.primarydomain.com
                subdomain2.primarydomain.com
                subdomain3.primarydomain.com;

    client_max_body_size 20M;
    root /home/username/www/primarydomain.com/public_html;
    index index.php;
    error_log /home/username/www/primarydomain.com/logs/error.log error;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi.conf;
    }

    # This doesn't seem to block access
    location /wp-login.php {
        allow XXX.XXX.XXX.XXX;    # this is my ipaddress
        deny all;
    }

    # This doesn't seem to block access    
    location /wp-admin/ {
        deny all;
        allow XXX.XXX.XXX.XXX;    # this is my ipaddress
    }

    # This doesn't seem to block access
    location ~ ^/(wp-admin|wp-login\.php) {
        deny all;
        allow XXX.XXX.XXX.XXX;    # this is my ipaddress
    }
}
Run Code Online (Sandbox Code Playgroud)

ffe*_*ast 7

这不是工作,因为regexps具有较高的比前缀优先nginx

https://nginx.ru/en/docs/http/ngx_http_core_module.html#location

为了找到与给定请求匹配的位置,nginx首先检查使用前缀字符串(前缀位置)定义的位置.其中,选择并记住具有最长匹配前缀的位置.

这就是重点:

然后按照它们在配置文件中的出现顺序检查正则表达式.正则表达式的搜索在第一次匹配时终止,并使用相应的配置.如果未找到与正则表达式的匹配,则使用先前记住的前缀位置的配置

所以这个表达式将处理所有请求

location ~ \.php$
Run Code Online (Sandbox Code Playgroud)

其中一个解决方案可能是将您的prefix位置转换为regexp并在配置文件中向上移动它们

或者使用=修饰符作为您要限制访问的网址

此外,使用"="修饰符可以定义URI和位置的精确匹配.如果找到完全匹配,则搜索终止

来自文档的更多示例:

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}
Run Code Online (Sandbox Code Playgroud)

"/"请求将匹配配置A,"/ index.html"请求将匹配配置B,"/ document/document.html"请求将匹配配置C,"/ images/gif"请求将匹配配置D和"/documents/1.jpg"请求将匹配配置E.