Tuesday 19 January 2016

How to block only 1 IP in NGINX configuration

Hi friends,

Have you ever wondered how to block only 1 IP from accessing your website that runs on a NGINX server? Guess what, I have the right information for you!

So, to begin with, you should know where your configurations files are stored. Most commonly they should be located in /etc/nginx/. For example, my configuration is an ubuntu server with nginx installed, running 1 wordpress website.

My NGINX server uses two conf files:

1. /etc/nginx/nginx.conf
2. /etc/nginx/sites-available/wordpress

The second one can be "default", "yourdomain", "wordpress", etc. This is the file where the NGINX rules for your particular website are configured.

In this particular example, the restriction rules for blocking only 1 IP will be placed in wordpress. What you can do is to open wordpress file with your favorite text editor and edit it. I will show you a way that can be done directly from the terminal console.

1. Type in termiinal:

nano -c /etc/nginx/wordpress

This should open a the text file and now it should be ready for the edits. Then, you need to find this line:

2. Find this lines in your active server block:

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



3. Edit this lines as following:

location / {
                try_files $uri $uri/ /index.php?q=$uri&$args;
                deny   85.159.237.13;
        }


In the deny section you can place the IP that you want to ban from accessing your website. You can add as many IPs as you want. You can place each IP as a new line.


4. If you want to additionally block 1 IP from executing files that end with .php extensions, like xmlrpc.php, you can further edit your server block, like this...

5. Find the following lines:

location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;     
           } 


6. Edit this section by adding the blocked IP, as following:

location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params; 
            deny   85.159.237.13;          
        }  
In the deny section, again - place the IP that you want to ban. Whenever someone or a script tries to access your website or any .php file, the NGINX server with return 403 Forbidden error and thus will prevent your server resources from being abused or will simply block somebody that you don't like to see your website.

That's it!

No comments:

Post a Comment