What is the best way to restrict the access to the admin area by IP in Magento? Bear in mind that admin can work either from /admin
or index.php/admin
5 Answers
You can place the following codes into your .htaccess
file:-
RewriteCond %{REQUEST_URI} ^/(index.php/)?admin/ [NC]
RewriteCond %{REMOTE_ADDR} !^1\.1\.1\.1
RewriteRule ^(.*)$ http://%{HTTP_HOST}/ [R=302,L]
Where 1.1.1.1
is your IP address.
* For the last line, make sure that there's no spacing between http://
and %{HTTP_HOST}/
. StackExchange doesn't allow the code http://%
to be posted so I have to add a spacing in between.
-
1This code redirect from admin pages with slash after admin (admin/) and with something after the slash (admin/abc). But admin page is still loaded on "myeshop.com/admin". Is better to use rule without last slash (RewriteCond %{REQUEST_URI} ^/(index.php/)?admin [NC]) to prevent page loading– MartinMar 21, 2017 at 10:01
Multiples are handled by adding another match line
RewriteCond %{REQUEST_URI} ^/(index.php/)?admin(.*) [NC]
RewriteCond %{REMOTE_ADDR} !^10\.1\.1\.10
RewriteCond %{REMOTE_ADDR} !^10\.2\.1\.10
RewriteRule .* - [F,L]
Basically it translates to if this url regex, and not these addresses, then 403, you're out of here.
-
Just reading the documentation: If you specify
F
thenL
is implied. httpd.apache.org/docs/2.4/rewrite/flags.html. "When using [F], an [L] is implied - that is, the response is returned immediately, and no further rules are evaluated." Feb 22, 2018 at 11:41
In case anyone uses Nginx:
location ~* ^/(index\.php/bcknd|bcknd) {
allow 1.1.1.1;
try_files $uri $uri/ /index.php?$args;
location ~* \.php$ { try_files /dummy @proxy; }
deny all;
}
You can also set up "allow from" rules in the httpd config for the virtual host files. I would also change the admin URL for additional security (ok kind of redundant with the "allow from"s but belt and braces).
Inside the conf file I do something like this:
<Location /index.php/mynewadminname>
Order deny,allow
deny from all
#home
allow from 1.2.3.4
#office
allow from 5.6.7.8
</Location>
<Location /mynewadminname>
Order deny,allow
deny from all
#home
allow from 1.2.3.4
#office
allow from 5.6.7.8
</Location>
Where 1.2.3.4 and 5.6.7.8 are two allowed IP addresses. Might be an alternative.
Allow admin access by ip
RewriteCond %{REMOTE_ADDR} !^10\.125\.192\.50
RewriteCond %{REMOTE_ADDR} !^10\.125\.192\.50
RewriteCond %{REQUEST_URI} admin [NC]
RewriteRule ^(.*)$ / [F,L]