How to prevent DDoS Attack on Nginx by Hardening ⋆ ALexHost SRL

Test your skills on our all Hosting services and get 15% off!

Use code at checkout:

Skills
16.02.2024

How to prevent DDoS Attack on Nginx by Hardening

How to prevent ddos attack on Nginx

How to prevent ddos attack on nginx, learn how to block certain DDoS Attacks with Nginx Web server with this nginx ddos protection configuration, this will help your server to prevent and block certain common DDoS Attacks, with Nginx configuration and hardening you can block some attacks in your server.

Alexhost offers free Anti-DDoS Protection against some certain attacks, you can use our VPS Servers or Dedicated Servers, we offer free Anti-DDoS Protection, however the capacity of mitigations, methods, filtering will be different based in the location you choose.

Requirements:
Nginx (you need to have Nginx installed in your current server)
Some Knowledge (is required to know how to use basic commands of Linux and how to access some Nginx files, know-how is expected)
VPS server or Dedicated Server (you can use a VM in your localhost)
DDoS Protection (from your Hosting Provider is required to be able to mitigate more complex DDoS Attacks)
Linux (any distribution that Nginx can be installed)
Nginx (you may need to read their Nginx documentation in order to test and check if still reliable)

Limitations: This tutorial is not a “bulletproof” to protect against all DDoS Attacks, this will probably limit the attack by blocking certain types of commons attacks and help your server to be online. There are some limitations against some DDoS Attacks, you will need that your Hosting Provider offers some kind of DDoS Protection in order to block and prevent, this configuration can’t protect against all attacks against your server. This configuration is to prevent and block some attacks, but it won’t block all attacks without DDoS Protection from your Hosting.

Warning:  Alexhost doesn’t recommend you to use this configuration in your production server, we recommend to test it before doing anything. Alexhost isn’t responsible for any kind of issue this might create or not. Pratice a good server security, before implement anything backup everything in case you need to restore. Please read the Nginx Documentation for DDoS Protection to understand how it works.

Prevent DDoS Attacks by hardening Nginx

Configuring Nginx for DDoS protection and hardening against common attack layers involves implementing various strategies to mitigate and prevent attacks. Here’s a guide on how to configure Nginx to enhance security and learn How to prevent ddos attack on nginx by hardening your web server:

  1. Update Nginx: Ensure you are using the latest stable version of Nginx to benefit from the latest security patches and improvements.
  2. Limit Connections: Use the limit_conn module to restrict the number of connections from a single IP address. This helps prevent DDoS attacks from overwhelming your server with too many simultaneous connections.
http { limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=1r/s; server { limit_req zone=req_limit_per_ip burst=5; # Other server configurations... } }

Whitelist/Blacklist IPs: Use the allow and deny directives to whitelist trusted IP addresses and block malicious ones.
nginx

http { # Whitelist trusted IP addresses allow 192.168.1.0/24; deny all; # Other server configurations... }

Implement Web Application Firewall (WAF): Utilize third-party modules like ModSecurity with Nginx to detect and block malicious HTTP traffic.

Enable HTTPS: Encrypt communication between clients and the server using HTTPS to prevent data interception and man-in-the-middle attacks.

Disable Unused Modules: Disable unnecessary Nginx modules to reduce the attack surface and improve performance.
nginx

./configure --without-http_autoindex_module --without-http_ssi_module
  1. Tuning Nginx Configuration: Optimize Nginx configuration parameters such as worker processes, worker connections, and timeouts based on your server’s hardware capabilities and expected traffic.
  2. Monitoring and Logging: Regularly monitor server logs for suspicious activity and set up alerting systems to notify administrators of potential attacks.
  3. Implementing DDOS Protection Services: Consider using specialized DDoS protection services or appliances in front of Nginx, such as Cloudflare, AWS Shield, or Akamai.
  4. Regular Backups: Ensure regular backups of critical data to minimize the impact of successful attacks.

Remember that security is an ongoing process, and it’s crucial to stay updated with the latest security practices and threats to effectively protect your server against potential attacks.

Nginx ddos protection configuration:

#Define a zone to track connections from each IP

http {     limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;     # Define a zone to track requests from each IP     limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=10r/s;     server {         listen 80;         server_name example.com;         # Rate limit requests         limit_req zone=req_limit_per_ip burst=20;         # Limit maximum number of connections from a single IP         limit_conn conn_limit_per_ip 20;         # Deny requests with large request bodies to mitigate against some types of attacks         client_body_buffer_size 1k;         client_header_buffer_size 1k;         client_max_body_size 1k;         large_client_header_buffers 2 1k;         # Enable Gzip compression to save bandwidth         gzip on;         gzip_comp_level 5;         gzip_min_length 256;         gzip_proxied any;         gzip_vary on;         # Add security headers to enhance security         add_header X-Content-Type-Options "nosniff";         add_header X-XSS-Protection "1; mode=block";         add_header X-Frame-Options "SAMEORIGIN";         add_header Referrer-Policy "same-origin";         add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;         # Block common vulnerable User-Agents         if ($http_user_agent ~* (wget|curl) ) {             return 403;         }         # Block access to hidden files         location ~ /\. {             deny all;         }         # Block access to certain file types         location ~* \.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$|^#.*#$|\.php_ {             deny all;             return 403;         }         # Whitelist your IP for administrative access         location /admin {             allow your_admin_ip;             deny all;         }         # Deny access to certain directories         location ~ /(system|vendor) {             deny all;             return 403;         }         # Proxy pass requests to your application server         location / {             proxy_pass http://your_backend_server;             proxy_set_header Host $host;             proxy_set_header X-Real-IP $remote_addr;             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;             proxy_set_header X-Forwarded-Proto $scheme;         }     } }

 

This configuration does the following:

  1. Rate Limiting: Limits the number of requests from each IP address to 10 requests per second with a burst of 20 requests.
  2. Connection Limiting: Limits the maximum number of connections from each IP address to 20.
  3. Request Body Size Limiting: Limits the size of request bodies to mitigate against attacks that send large request bodies.
  4. Gzip Compression: Enables gzip compression to save bandwidth.
  5. Security Headers: Adds security headers to enhance security.
  6. Blocking Vulnerable User-Agents: Blocks requests from common vulnerable User-Agents.
  7. Blocking Hidden Files: Blocks access to hidden files and directories.
  8. Whitelisting Admin Access: Allows access to the admin area only from your IP address.
  9. Denying Access to Certain Directories: Blocks access to sensitive directories like system and vendor.
  10. Proxy Pass: Forwards requests to your application server.

Ensure to customize the configuration according to your specific requirements, such as domain names, backend server addresses, and administrative IP addresses. Additionally, regularly monitor your server logs and adjust configurations as necessary to adapt to evolving threats.

The configuration provided is meant to be added to the nginx.conf file or included from separate configuration files. Here’s a step-by-step guide on where to add the configuration:

  1. Locate the nginx.conf file: Depending on your Nginx installation, the nginx.conf file might be located in different directories. Common locations include /etc/nginx/nginx.conf, /usr/local/nginx/conf/nginx.conf, or /etc/nginx/sites-available/default.
  2. Open the nginx.conf file: You can open the file using a text editor or a command-line text editor like nano, vim, or emacs.
  3. Add the configuration within the http block: Inside the http block, which defines the HTTP server settings, you’ll add the provided configuration. Typically, you’ll find the http block near the top of the nginx.conf file.
  4. Paste the provided configuration: Paste the entire configuration provided earlier inside the http block. Ensure that you replace placeholder values like example.com, your_admin_ip, and your_backend_server with your actual values.
  5. Save and exit the file: After adding the configuration, save the nginx.conf file and exit the text editor.
  6. Test the Nginx configuration: Before restarting Nginx, it’s a good practice to test the configuration for syntax errors.
  7. You can do this by running the following command:
    nginx -t

If there are no syntax errors, you’ll see a message indicating that the configuration file test is successful.

Restart Nginx: Finally, restart Nginx to apply the changes. You can do this with the following command:

sudo service nginx restart

  1. If you’re not using a system with systemd, you might use different commands to restart Nginx.

By following these steps, you’ll add the provided configuration to your Nginx server, enhancing its security with DDoS protection and other security measures, this tutorial will help you how to prevent ddos attack on nginx by configurating Nginx.

Test your skills on our all Hosting services and get 15% off!

Use code at checkout:

Skills