Blocking direct access to the Nginx server by IP is necessary to protect the system from direct attacks and increase security by directing users to use the official domain name.
Step by step: Configure block direct IP access to your Nginx web server
For example, if you have a website called itsmeit.co and its IP address is 134.24.149.46, when users enter 134.24.149.46 directly into their browser, they can still be redirected to your website. However, this method is less secure and could make your site susceptible to DDoS attacks. To enhance security and prevent direct access to your Nginx server from specific IP addresses, you can follow the steps below to block IP address in Nginx.
Step 1: Create a new Nginx configuration file
Login to the server using SSH and create a separate configuration file, for example, block_direct_access_ip.conf.
sudo nano /etc/nginx/sites-available/block_direct_access_ip.conf
And add this content file:
server { listen 80 default_server; listen [::]:80; server_name _; return 444; } server { listen 443 ssl http2 default_server; listen [::]:443; server_name _; ssl_certificate /etc/nginx/ssl/public.crt; ssl_certificate_key /etc/nginx/ssl/private.key; return 444; }
Step 2: Generate SSL certificate for HTTPS authentication
The above configuration will block direct access to nginx server by IP address including IPV4 and IPV6 as well as HTTP and HTTPS. However for it to work you need to create the file public.crt
and private.key
, keep running the command to create crt
and key
:
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/private.key -out /etc/nginx/ssl/public.crt
Then open the file /etc/nginx/nginx.conf, add in http {} the line include /etc/nginx/sites-available/*.conf;
Finally, restart Nginx for the changes to take effect. And you can check by entering your IP address directly into the browser.
sudo service nginx restart
By following the above steps, you have successfully blocked any direct access requests from your IP address to your Nginx server. This significantly enhances security by blocking IP addresses in Nginx and allowing access only through the official domain name.
– Advertising –