Nginx is fast and reliable, but default configurations are not secure. If you're running a production website, you need to harden your Nginx server. This guide covers 10 essential security steps.
Step 1: Keep Nginx Updated
Outdated software has known vulnerabilities. Run these commands regularly:
sudo apt update
sudo apt upgrade -y
Check your Nginx version:
nginx -v
Step 2: Hide Nginx Version
Don't reveal your Nginx version to attackers. Add this to /etc/nginx/nginx.conf inside the http block[reference:6]:
server_tokens off;
This prevents version information from appearing in error pages and response headers.
Step 3: Set Up a Firewall
Restrict access to your server. Use UFW to allow only necessary ports[reference:7]:
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
Step 4: Enable HTTPS with SSL/TLS
Encrypt traffic to protect user data. Use Let's Encrypt for free certificates[reference:8]:
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com
Redirect all HTTP traffic to HTTPS to ensure encrypted connections[reference:9].
Step 5: Implement Rate Limiting
Protect against brute-force attacks and DDoS by limiting request rates[reference:10]. Add this to your Nginx configuration:
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;
server {
location / {
limit_req zone=mylimit burst=20 nodelay;
}
}
Step 6: Restrict Access by IP
If you have administrative areas (like phpMyAdmin), restrict access to specific IPs[reference:11]:
location /admin/ {
allow 192.168.1.100;
deny all;
}
Step 7: Disable Unused HTTP Methods
Prevent PUT and DELETE requests that aren't needed:
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 405;
}
Step 8: Set Up Basic Authentication
Add an extra layer of security for sensitive areas[reference:12]. Create a password file:
sudo htpasswd -c /etc/nginx/.htpasswd admin
Then add to your Nginx config:
location /protected/ {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
Step 9: Configure Secure Headers
Add security headers to protect against common attacks:
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
Step 10: Monitor Access and Error Logs
Regularly check logs for suspicious activity[reference:13]:
sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log
Enable logging of failed requests to identify attack patterns.
Quick Security Checklist
| Step | Task | Done? |
|---|---|---|
| 1 | Keep Nginx updated | ☐ |
| 2 | Hide Nginx version | ☐ |
| 3 | Set up firewall | ☐ |
| 4 | Enable HTTPS | ☐ |
| 5 | Implement rate limiting | ☐ |
| 6 | Restrict sensitive areas by IP | ☐ |
| 7 | Disable unused HTTP methods | ☐ |
| 8 | Set up basic authentication | ☐ |
| 9 | Configure security headers | ☐ |
| 10 | Monitor logs | ☐ |
Need a VPS to practice on? Check our recommended VPS providers.