Intro
Nginx is one of the most widely used web servers and reverse proxies, but its default configuration is not optimized for security. Exposing an unhardened Nginx instance can lead to information disclosure, unauthorized access, or full server compromise. This guide walks through a practical hardening process: from establishing a baseline inventory, to applying scoped configuration changes, to verifying and maintaining a secure posture. You will learn how to hide version information, restrict access, manage TLS, handle secrets safely, set correct file permissions, and limit network exposure. Each step includes concrete commands or configuration snippets and their expected results, so you can follow along on your own server. By the end, you will have a repeatable checklist to keep Nginx secure over time.
Version and Environment Inventory
Before making any changes, document what you are working with. Knowing your Nginx version, operating system, and current configuration helps you understand which hardening steps are applicable and provides a rollback point.
Check Nginx Version and Compile-Time Options
Start by checking the installed Nginx version and the configure arguments used at build time. These arguments reveal which modules are compiled in - important because some security features require specific modules. Run:
nginx -V 2>&1 | head -n5
Example output:
nginx version: nginx/1.24.0
built by gcc 12.2.0 (Debian 12.2.0-14)
built with OpenSSL 3.0.9 30 May 2023
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf ...
Note the version: if it is old, you may need to upgrade before hardening, as newer versions include security fixes. Also note modules such as --with-http_ssl_module (required for TLS) and --with-http_v2_module.
Determine Operating System and Package Manager
Your commands for installing, updating, and managing Nginx depend on the OS. Check with:
cat /etc/os-release
Example output:
NAME="Ubuntu"
VERSION="22.04.3 LTS (Jammy Jellyfish)"
ID=ubuntu
...
Also find your package manager: apt for Debian/Ubuntu, yum or dnf for RHEL/CentOS, etc.
Locate Configuration Files and Include Structure
The main configuration file is typically /etc/nginx/nginx.conf. It often includes additional files from /etc/nginx/conf.d/ and /etc/nginx/sites-enabled/. Document the include structure to avoid editing the wrong file:
nginx -T 2>/dev/null | grep -E 'include|server_name' | head -n20
This prints the effective configuration includes. Example:
include /etc/nginx/modules-enabled/*.conf;
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
Identify Network Exposure
List listening ports and interfaces to understand what is exposed:
sudo ss -tulpn | grep nginx
Example output:
tcp LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=1234, fd=6))
tcp LISTEN 0 511 0.0.0.0:443 0.0.0.0:* users:(("nginx",pid=1234, fd=7))
If Nginx is listening on all interfaces (0.0.0.0), that is a broad exposure. You may want to restrict it to specific IPs later.
Backup Current Configuration
Always create a backup before edits:
sudo cp -r /etc/nginx /etc/nginx.backup.$(date +%Y%m%d)
Verify backup:
ls -ld /etc/nginx.backup.*
With the environment documented, you are ready to harden configuration safely.
Safe Configuration Path
Apply changes incrementally and test after each step. Nginx provides nginx -t to validate configuration syntax before reloading. This prevents downtime from typos.
1. Hide Nginx Version and Server Tokens
By default, Nginx reveals its version in the Server response header and on error pages. This aids attackers in identifying vulnerabilities. Disable it in the main context (http block) of /etc/nginx/nginx.conf:
http {
server_tokens off;
...
}
After reload, check response headers:
curl -I http://localhost
Expected output:
HTTP/1.1 200 OK
Server: nginx
Date: ...
Instead of Server: nginx/1.24.0, only nginx is shown. Note: server_tokens cannot remove the Server header entirely without modifying source or using a module; but removing the version is sufficient to deter casual scanning.
2. Disable Unnecessary HTTP Methods
If your application only uses GET, POST, and HEAD, block other methods like TRACE, DELETE, PUT. This reduces attack surface. In the server or location block, add:
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 405;
}
Alternatively, use limit_except for more precise control:
location / {
limit_except GET HEAD POST {
deny all;
}
}
Test with a TRACE request:
curl -X TRACE http://localhost
Expected response:
HTTP/1.1 405 Not Allowed
3. Set Security Headers
Add common security headers to protect against clickjacking, MIME sniffing, and XSS. In the server block:
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
For HTTPS sites, consider adding HSTS (only after confirming TLS works):
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
Verify with:
curl -I http://localhost
Check that headers appear.
4. Configure TLS Securely
If you serve HTTPS, verify your TLS settings. Ensure you have ssl_certificate and ssl_certificate_key directives. Then, enforce modern protocols and ciphers:
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
Also enable OCSP stapling for certificate status checking:
ssl_stapling on;
ssl_stapling_verify on;
Test TLS configuration with openssl s_client:
echo | openssl s_client -connect localhost:443 -tls1_2 2>/dev/null | grep -E 'Protocol|Cipher'
Expected output shows negotiated TLS 1.2 or 1.3 and a strong cipher.
5. Restrict Access to Sensitive Locations
Prevent access to hidden files (e.g., .git, .env) and backup files. In the server block:
location ~ /\. {
deny all;
}
location ~ \.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)$ {
deny all;
}
Test by attempting to fetch a forbidden file:
curl -I http://localhost/.git/config
Expected: HTTP/1.1 403 Forbidden.
6. Manage Secrets Properly
Avoid hardcoding secrets (API keys, database passwords) in Nginx configuration files. Use environment variables or external files with restricted permissions. For example, if you need a value in a config, use env directive and set_by_lua (if Lua module available) or use include with a file containing variables but ensure file permissions are 600 and owned by root.
Better: use Nginx's auth_basic for password files, but store password hashes, not plaintext. Generate with htpasswd:
sudo htpasswd -c /etc/nginx/.htpasswd username
Then configure:
location /admin {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
Set file permissions:
sudo chmod 640 /etc/nginx/.htpasswd
sudo chown root:www-data /etc/nginx/.htpasswd
Test access:
curl -I http://localhost/admin
Expected: HTTP/1.1 401 Unauthorized.
7. Set Correct File Permissions and Ownership
Nginx master process runs as root, but worker processes run as a less privileged user (often www-data or nginx). Ensure Nginx configuration files are owned by root and not writable by others:
sudo find /etc/nginx -type f -exec chmod 644 {} \;
sudo find /etc/nginx -type d -exec chmod 755 {} \;
sudo chown -R root:root /etc/nginx
For certificates and keys: keys must be readable only by root and the Nginx user. Typically:
sudo chmod 600 /etc/nginx/ssl/example.key
sudo chmod 644 /etc/nginx/ssl/example.crt
sudo chown root:root /etc/nginx/ssl/example.key /etc/nginx/ssl/example.crt
Check with:
ls -l /etc/nginx/ssl/
8. Limit Network Exposure
If Nginx should only listen on a specific interface (e.g., internal network), specify the IP in listen directives:
server {
listen 192.168.1.10:80;
...
}
Check listening sockets again:
sudo ss -tulpn | grep nginx
It should show only the specified IP, not 0.0.0.0 or ::.
9. Enable Rate Limiting and Connection Limits
Protect against brute-force and DoS attacks. In the http block, define a shared memory zone:
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=addr_limit:10m;
Apply in server or location:
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
limit_conn addr_limit 10;
...
}
Test by sending many requests quickly with ab or wrk. You should see 503 responses when limit exceeded.
After each change, run nginx -t and reload:
sudo nginx -t
sudo systemctl reload nginx
Verification and Diagnostics
After applying security configurations, you must verify they are effective. This section covers observable checks and expected results.
Test Configuration Syntax
Always run before reloading:
sudo nginx -t
Expected output:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
If errors, fix them before proceeding.
Inspect Response Headers
Use curl -I to check for security headers and server token hiding:
curl -I http://localhost
Look for:
Server: nginx
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Referrer-Policy: strict-origin-when-cross-origin
Validate TLS Security
Use online tools like SSL Labs (but for local testing, use openssl or testssl.sh):
testssl https://yourdomain.com
Check for supported protocols and ciphers. Ensure TLSv1.0 and TLSv1.1 are not supported. Example negative test:
echo | openssl s_client -connect localhost:443 -tls1 2>/dev/null | grep 'Protocol' || echo "TLS 1.0 not supported (good)"
Test Access Restrictions
Attempt to access forbidden paths:
curl -I http://localhost/.git/config
curl -I http://localhost/backup.sql
Expect 403 Forbidden.
Attempt a disallowed method:
curl -X DELETE http://localhost/
Expect 405 Not Allowed.
Test rate limiting by sending many requests:
for i in {1..100}; do curl -s -o /dev/null -w "%{http_code}\n" http://localhost/api/; done | sort | uniq -c
You should see a mix of 200 and 503 (or 429) responses.
Verify File Permissions
Run a script to find world-writable files in Nginx directories:
sudo find /etc/nginx -type f -perm /o+w -exec ls -l {} \;
No output means no world-writable files.
Check that secret files are not readable by others:
sudo ls -l /etc/nginx/.htpasswd
Monitor Logs
Check access and error logs for unusual patterns, such as 403/404 storms from a single IP, which may indicate scanning. Tail logs:
sudo tail -f /var/log/nginx/access.log /var/log/nginx/error.log
Use grep to count 404s by IP:
sudo awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head
Use Nginx Amplify or Other Monitoring (Optional)
If available, set up monitoring to track metrics like requests per second, error rates, and security events.
Common Pitfalls and How to Avoid Them
Even experienced administrators can make mistakes that weaken security or break the server. Here are the most frequent issues, why they happen, and how to avoid or recover from them.
1. Forgetting to Test Configuration Before Reload
Why it happens: Under time pressure, administrators skip nginx -t and reload a flawed configuration.
Impact: Nginx may fail to reload (keeping old config) or, worse, start with broken settings causing downtime.
How to avoid: Always run sudo nginx -t before sudo systemctl reload nginx. Make it a habit.
Recovery: If reload fails, check sudo systemctl status nginx and logs. Fix the syntax and test again.
2. Overly Permissive File Permissions
Why it happens: During debugging, permissions are relaxed (e.g., chmod 777) and never restored.
Impact: Any local user or compromised process can read or modify sensitive files, including SSL private keys and htpasswd files.
How to avoid: Use the least privilege principle. Set config files to 644 owned by root, keys to 600 owned by root, and ensure Nginx user has only read access where needed.
Recovery: Run the permission-fixing commands from Section 7 and audit with find /etc/nginx -type f -perm /o+w.
3. Hardcoding Secrets in Configuration Files
Why it happens: Convenience; placing passwords or API keys directly in nginx.conf or included files.
Impact: If the configuration is ever exposed (e.g., via a misconfigured location block or backup), secrets are leaked.
How to avoid: Use environment variables, external files with strict permissions, or secret management tools. For basic auth, store only password hashes, never plaintext.
Recovery: Immediately change any exposed credentials, then refactor the configuration to remove hardcoded secrets.
4. Misconfiguring Access Control Rules
Why it happens: Incorrect order of allow and deny directives, or using regex location blocks that do not match as intended.
Impact: Either unauthorized users gain access or legitimate users are locked out.
How to avoid: Test access rules with curl from different IPs (or simulate with X-Forwarded-For if applicable). Start with a default deny policy and explicitly allow necessary IPs.
Recovery: If locked out, revert the configuration or adjust rules from a trusted IP (e.g., via a management interface).
5. Aggressive Rate Limiting
Why it happens: Setting the rate too low or burst too small, causing legitimate users to be throttled.
Impact: Users experience 503 errors and the service appears down.
How to avoid: Analyze normal traffic patterns first. Set burst and nodelay appropriately, and use allowlists for known good IPs (e.g., office IP, monitoring services).
Recovery: Adjust the rate and burst values upward, or add geo/map to exempt certain IPs.
6. Weakening TLS by Mixing Old Protocols
Why it happens: To support legacy clients, administrators enable TLSv1 or TLSv1.1, which are deprecated.
Impact: Connection is vulnerable to downgrade attacks (e.g., POODLE).
How to avoid: Enforce TLS 1.2 and 1.3 only. Check compatibility with modern browsers (all current ones support TLS 1.2).
Recovery: Remove old protocols from ssl_protocols and test with openssl s_client -tls1 to confirm it fails.
7. Ignoring Logs and Monitoring
Why it happens: Logs are verbose and often ignored until a security incident occurs.
Impact: Attack attempts go unnoticed, allowing attackers to probe for weaknesses over time.
How to avoid: Set up log rotation, use monitoring tools (e.g., Nginx Amplify, ELK stack, or simple scripts), and review logs regularly. Create alerts for high volumes of 4xx/5xx errors.
Recovery: If you suspect an ongoing attack, analyze logs to identify source IPs and block them temporarily with deny directives or firewall rules.
Ongoing Operations and Governance
To keep Nginx secure, assign clear ownership and review cycles. This prevents security drift and ensures that changes are tested and documented.
Define a Single Owner for Nginx Security
Appoint one person as the Nginx security owner. This person is accountable for:
- Applying configuration changes and testing them.
- Reviewing security advisories and applying patches.
- Maintaining the backup and rollback plan.
- Conducting quarterly audits (see checklist below).
If possible, name a backup person to cover absences, but the primary owner has final responsibility.
Establish a Review Cycle
Security is not a one-time task. Schedule the following:
- Weekly: Check logs for anomalies (spikes in 404s, authentication failures).
- Monthly: Review Nginx version and installed modules for updates; run
testsslor SSL Labs scan. - Quarterly: Full configuration audit: permissions, headers, TLS settings, access rules, and rate limits. Run the operations checklist below and update documentation.
Document Changes
Maintain a changelog in a file like /etc/nginx/CHANGELOG.md noting:
- Date and description of change.
- Why the change was made.
- Who made it and who reviewed it.
- Rollback steps if needed.
This is invaluable during troubleshooting or security incidents.
Operations Checklist
Use this checklist for regular reviews and after any configuration change. It summarizes the hardening steps and verification actions.
| Step | Action | Verification Command | Expected Result |
|---|---|---|---|
| 1 | Backup current config | cp -r /etc/nginx /etc/nginx.backup.date | Backup directory exists |
| 2 | Disable version tokens | Add server_tokens off; | curl -I shows Server: nginx only |
| 3 | Restrict HTTP methods | Add limit_except or if block | curl -X DELETE returns 405 |
| 4 | Add security headers | Add add_header directives | Headers appear in response |
| 5 | Harden TLS | Set ssl_protocols, ssl_ciphers, HSTS | testssl shows no old protocols |
| 6 | Block sensitive files | Add location denies for dotfiles and backups | curl for .git returns 403 |
| 7 | Manage secrets | Use auth_basic with htpasswd, secure perms | curl for protected area returns 401 |
| 8 | Set file permissions | chmod and chown as described | find shows no world-writable files |
| 9 | Limit network exposure | Specify IP in listen | ss -tulpn shows only intended IPs |
| 10 | Enable rate limiting | Define zones and apply | Flood test yields 503s |
| 11 | Validate config | nginx -t | Syntax OK |
| 12 | Monitor logs | tail and awk | Identify anomalies |
Run through this checklist quarterly or after major changes. Keep the backup copy for at least one month.
Conclusion
Hardening Nginx is not a one-time task but an ongoing process. By following this guide, you have established a baseline, applied scoped security improvements in a safe order, and verified each change with observable commands. You now have a repeatable checklist to maintain security as your environment evolves. Start with the most impactful changes: hide version tokens, add security headers, and enforce TLS. Then systematically work through access controls, permissions, and rate limiting. Remember to always test before reloading (nginx -t) and keep backups. With these practices, your Nginx deployment will be significantly more resistant to common attacks and misconfigurations. For further reading, consult the official Nginx documentation and security advisories. Your next step is to apply this checklist to a staging environment, confirm everything works, and then roll out to production with confidence.
Example Timeline and Ownership
To make this operational, here is a concrete example of how to assign ownership and review cycles for a typical small team:
- Nginx Security Owner: Priya Shah, Engineering Lead. Responsible for all configuration changes and quarterly audits.
- Backup Owner: Marcus Chen, DevOps Engineer. Covers when Priya is unavailable.
- Weekly Log Review: Priya or Marcus checks
access.loganderror.logevery Monday for anomalies. - Monthly Update Review: On the first Wednesday of each month, Priya checks for Nginx updates and new security advisories.
- Quarterly Full Audit: Scheduled for January 15, April 15, July 15, and October 15. Priya runs the entire operations checklist, updates
CHANGELOG.md, and reports to the team.
This structure ensures accountability and keeps security fresh in everyone's mind.