Site icon GetPageSpeed

Whitelist IP addresses for Magento 2 admin protection

Magento Security

Magento Security

Magento 2 is a complex framework that requires serious attention to security.

Out of the box, it generates unique admin URIs, making it hard for attackers to brute force the admin area.

However, it doesn’t mean that you have to stop securing your store furthermore. Developers come and go, but your admin URI is likely to stay unchanged.
Alas, a developer that no longer works for you is a security risk 🙂

You could keep changing admin URI every time you have a developer depart your team, but it’s best to simply manage a set of allowed IP addresses within your NGINX configuration for Magento 2.

How do we achieve this?

Allocate location for Magento 2 admin

The first thing we should do is create a new location that will match the admin URI common prefix, e.g. /admin_.
Depending on how you have set up your admin URI, you may want to use different prefix instead.

location ~ "^/admin_" {

    fastcgi_pass   unix:/var/run/php-fpm/example.com.sock;
    fastcgi_buffers 1024 4k;
    fastcgi_buffer_size 128k;

    fastcgi_param  PHP_FLAG  "session.auto_start=off \n suhosin.session.cryptua=off";
    fastcgi_param  PHP_VALUE "memory_limit=4G \n max_execution_time=600 \n max_input_vars=100000";
    fastcgi_read_timeout 600s;
    fastcgi_connect_timeout 600s;

    fastcgi_param  SCRIPT_FILENAME  $document_root/index.php;
    include        fastcgi_params;
}

Since all requests to the admin area will unconditionally go through PHP-FPM, we have eliminated try_files, and this made things faster in terms of accessing the admin area.
The extra benefit of allocating this block, is, of course, the one we want – being able to apply the additional configuration.

In our example configuration, we specify that admin pages are OK to load for up to 10 minutes, which is typical when you use some bad export plugin or custom code that does not efficiently use things like Magento 2 queues.

Apply IP whitelisting

Now we can simply add allowed IP addresses to the same location, at the top, e.g.:

location ~ "^/admin_" {

    allow 1.2.3.4;
    allow 1.2.3.5;
    allow 1.2.3.6;
    deny all;

    fastcgi_pass   unix:/var/run/php-fpm/example.com.sock;
    fastcgi_buffers 1024 4k;
    fastcgi_buffer_size 128k;

    fastcgi_param  PHP_FLAG  "session.auto_start=off \n suhosin.session.cryptua=off";
    fastcgi_param  PHP_VALUE "memory_limit=4G \n max_execution_time=600 \n max_input_vars=100000";
    fastcgi_read_timeout 600s;
    fastcgi_connect_timeout 600s;

    fastcgi_param  SCRIPT_FILENAME  $document_root/index.php;
    include        fastcgi_params;
}

That’s pretty much it. Only the listed IP addresses will be able to access Magento 2 admin.

Exit mobile version