Rectangle 27 0

wordpress Apache 2.4 Require ip not working?


# Protect WordPress
ErrorDocument 401 default
ErrorDocument 403 default

SetEnvIF X-Forwarded-For "50.153.218.4" AllowIP

<Files wp-login.php>
    <RequireAny>
         Require env AllowIP
    </RequireAny>
</Files>
ErrorDocument 401 default
ErrorDocument 403 default

SetEnvIF X-Forwarded-For "50.153.218.4" AllowIP

# Disallow access for everyone except these IPs
<RequireAny>
    Require env AllowIP
</RequireAny>

# Allow plugin access to admin-ajax.php around password protection
<Files admin-ajax.php>
    <RequireAll>
        Require all granted
    </RequireAll>
</Files>
add_action('init', function() {
    $allowed_ips = array('50.153.218.4');
    if(is_admin() || $GLOBALS['pagenow'] == 'wp-login.php') {
        if( !DOING_AJAX && !in_array($_SERVER['REMOTE_ADDR'], $allowed_ips) ) {
            wp_die('', 'Forbidden' array(
                'response' => 403
            ));
        }
    }
});

@zen It must be the reverse proxy. A reverse proxy sits between the webserver and the user. All of your requests are actually coming from the proxy so the IP address you see is the proxy's. A CDN would not cause this sort of issue. It's strange that before the upgrade this wasn't an issue. It might having something to do with configuring apache to account for the reverse proxy. If you're interested I would ask on ServerFault.

Alternatively, in your theme or in a plugin you can implement this same sort of authentication logic:

I am using Cloudflare for CDN and nginx reverse proxy for speed improvements so one of those must be causing it. Although I had both before I upgraded to new apache and it seemed to work then. I did indeed confirm that REMOTE_ADDR and HTTP_X_FORWARDED_FOR do not match. Would you know off the top of your head which one is the cause? I'd rather do it through apache than PHP since it will probably be safer and faster. I've tried a few WordPress security plugins but they all eventually fail or still add too much load to the server in case of brute force attacks.

I can offer you some workarounds though. The easiest solution may be to use one of several WordPress security plugins that allow you to restrict access to the backend by IP address.

If that is not the issue so you might have better luck finding an answer at ServerFault.

The only reason I can think that apache might not be reading the user's IP correctly is if you're behind a proxy or load balancer. If that is the case you would use X-Forwarded-For instead of ip. In PHP, you can confirm if you're behind a proxy by comparing $_SERVER['REMOTE_ADDR'] and $_SERVER['HTTP_X_FORWARDED_FOR'].

Update: From the comments it looks like there is a proxy involved. This should work:

You should also be able to use a similar method using the "Allow, Deny" syntax.

and

thanks for the edit. I will mark this the correct answer since that is a good solution for now.

Note