Learn to configure NGINX from scratch. This guide explains directives, server blocks & practical setups to speed up your website & improve server...
Your website loads slowly. Traffic spikes crash your server. You need a solution that handles thousands of visitors without breaking a sweat.
NGINX solves these problems. It is a high-performance web server that also works as a reverse proxy, load balancer, and HTTP cache. Whether you run a personal blog or a business application, NGINX delivers speed and reliability while using minimal server resources.
This guide teaches you NGINX configuration from scratch with practical configurations you can use immediately.
What is Nginx and why use it?
NGINX (pronounced engine x) is a web server that handles high traffic efficiently. Unlike traditional servers that create a new thread for each visitor, NGINX uses an event-driven model. One worker process handles multiple connections simultaneously without consuming excessive memory.
Apache creates a separate worker for each visitor. With 10,000 visitors, you need 10,000 workers. NGINX uses a handful of workers that juggle all connections. The difference shows in your server bill and site speed.
NGINX does four main jobs. It serves static files like HTML, CSS, images, and JavaScript directly to browsers. It acts as a reverse proxy by forwarding requests to backend applications. It balances traffic across multiple servers to prevent overload. It caches responses to reduce load on your backend systems.
The configuration is straightforward once you understand the basics.
Deploy the Linux setup on VPS infrastructure
Match CPU, RAM and storage to your Linux services and their expected load.
Linux VPS options for this workload
Review resources and self-managed responsibilities before selecting infrastructure.
Directives are instructions that tell NGINX what to do. Every directive follows this format:
Show the syntax of an Nginx directive
1
directive_name value;
The semicolon is not optional. Forget it, and NGINX refuses to start.
Directives live in different contexts. The main context affects your entire NGINX installation. The HTTP block contains web server settings. Server blocks define individual websites. Location blocks handle specific URL patterns.
More specific directives override general ones. A location directive beats a server directive. This hierarchy lets you set defaults and override them where needed.
Disable gzip for /api/ while keeping it globally enabled
HTTP/2 allows multiplexing multiple requests over a single connection. The ssl_certificate should include your certificate chain. The Strict-Transport-Security header tells browsers to always use HTTPS for one year.
To redirect non-www to www instead, reverse the server_name values.
The server_name directive accepts multiple domains separated by spaces. Wildcards work at the start or end.
Match every example.com subdomain
1
server_name *.example.com;
This matches any subdomain like blog.example.com or api.example.com.
When multiple server blocks could match a request, NGINX follows priority. Exact matches win, then longest wildcard, then first matching regular expression.
Make sure your firewall allows traffic.
Allow HTTP and HTTPS through UFW
12
sudoufw allow 80/tcpsudoufw allow 443/tcp
Without open ports, visitors cannot reach your site.
Location blocks for path management
Location blocks define how NGINX handles specific URIs. NGINX processes location blocks in priority order.
The proxy_pass directive sends requests to your backend. Setting headers ensures the backend receives correct client information.
For load balancing across multiple servers, list them all.
Load balance requests across three backend servers
12345
upstream backend_app {
server 192.168.1.10:3000;
server 192.168.1.11:3000;
server 192.168.1.12:3000;
}
NGINX distributes requests evenly using round robin. Add health checks so NGINX stops routing to failed servers.
Mark a backend unavailable after repeated failures
123
upstream backend_app {
server 192.168.1.10:3000 max_fails=3 fail_timeout=30s;
}
After three failed attempts, NGINX marks the server down for 30 seconds.
Testing and troubleshooting
When things go wrong, check logs first. Error log lives at /var/log/nginx/error.log. Access log is at /var/log/nginx/access.log.
Always test configuration before reloading.
Test the Nginx configuration
1
sudonginx-t
This validates syntax and configuration. Fix any errors before proceeding.
Reload configuration without dropping connections.
Reload Nginx without dropping connections
1
sudonginx-s reload
NGINX starts new workers with updated configuration, then gracefully shuts down old workers.
Check which version you run.
Show the installed Nginx version
1
nginx-v
For compile options and modules, use capital V.
Show Nginx version modules and build options
1
nginx-V
If changes do not take effect, verify you edited the correct file and reloaded NGINX. Check for syntax errors. Look for conflicting directives in different files.
If you get 413 Request Entity Too Large errors, increase the limit.
Allow request bodies up to 50 MiB
1
client_max_body_size 50M;
If you see client IPs as 127.0.0.1 behind a load balancer, configure the real IP module.
Certbot automatically configures NGINX for HTTPS and sets up certificate renewal.
Common troubleshooting scenarios
Nginx fails to start after a configuration change
Run nginx -t to identify the syntax error. The output shows the file and line number. Common causes include missing semicolons, unclosed braces, or invalid directive names.
Test Nginx after a configuration change
1
sudonginx-t
nginx: [emerg] unexpected "}" in /etc/nginx/sites-enabled/example.com:15
The error points to line 15. Check for missing semicolons on previous lines.
Port 80 or 443 already in use
Another process occupies the port. Find what is using it:
Find processes listening on ports 80 and 443
12
sudolsof-i :80sudolsof-i :443
Common culprits include Apache running alongside NGINX. Stop the conflicting service or change NGINX to listen on different ports.
Permission denied errors
NGINX cannot access files or directories. Check file permissions:
Inspect permissions for the example.com document root
1
ls-la /var/www/example.com
NGINX runs as the www-data user by default. Ensure www-data can read files and access directories:
Safety check: Confirm the target and keep a recent backup or snapshot. Preview the affected resources where possible, and document a tested recovery or rollback path before running this command.
Investigate why the backend is slow. Check backend application logs and server resources.
Worker process crashes
Check error logs for segmentation faults or core dumps:
Show the last 100 Nginx error-log lines
1
sudotail-100 /var/log/nginx/error.log
Common causes include third-party modules with bugs, insufficient system resources, or corrupted configurations. Disable recently added modules to isolate the issue.
High memory usage
Check worker process memory:
List Nginx processes and memory usage
1
ps aux |grep nginx
Large SSL session caches consume memory. Reduce cache size:
Reduce the shared SSL session cache to 10 MiB
1
ssl_session_cache shared:SSL:10m;
Reduce worker_connections if memory is constrained:
Limit each Nginx worker to 512 connections
123
events {
worker_connections 512;
}
Logs not rotating
Log files grow too large. Verify logrotate configuration:
Or use IP addresses in upstream blocks instead of hostnames.
Cannot bind to a privileged port (below 1024)
NGINX must run as root to bind to ports 80 and 443. Check NGINX starts with sudo or as a system service. The master process runs as root, worker processes run as www-data.
Verify systemd service configuration:
Show the Nginx systemd unit configuration
1
sudosystemctl cat nginx
Common questions
How do I host multiple websites on one server?
Create a server block for each domain in /etc/nginx/sites-available/. Give each its own server_name and root directory. Enable them by symlinking to sites-enabled and reload.
How do I improve page load speed?
Enable gzip compression in your HTTP block. Set cache headers for static assets using expires directives. Use sendfile for efficient file serving. For caching, use proxy_cache_path to define cache storage and proxy_cache in location blocks to reduce backend load. Consider a CDN for global delivery.
What should I do if NGINX will not start?
Run nginx -t to check for configuration errors. The output shows the file and line number of any issues. Review error logs at /var/log/nginx/error.log for specific messages. Common causes include port conflicts, missing SSL certificates, syntax errors like missing semicolons, or permission issues. Access logs are in /var/log/nginx/access.log. Use tail -f to watch logs in real time.
How do I reload NGINX without downtime?
Run sudo nginx -s reload. NGINX starts new workers with updated configuration while old workers finish serving current requests.
How do I test my SSL configuration?
Visit ssllabs.com/ssltest and enter your domain. Aim for an A or A+ rating. The test identifies weak ciphers, protocol issues, and certificate problems.
Why do my static files return 404 errors?
Check your root or alias paths for typos. Verify files exist in the specified directory. Ensure NGINX has read permissions on files and execute permissions on directories. The www-data user must be able to read your files.
About the author
Peter French
Peter French is the Managing Director at Virtarix, with over 17 years in the tech industry spanning cloud hosting, cybersecurity, and data protection.
Use these practical Bash script examples for Linux server admins, including backups, log checks, disk alerts, cleanup previews, and reports.
Peter French
Cookie-Einstellungen
Wählen Sie, was Virtarix laden darf
Erforderliche Speicherung wird für Währung, Einwilligung und anonyme First-Party-Analytics-Sitzungskontinuität verwendet. Optionale Tools laden nur nach Zustimmung. Widerruf jederzeit über den Footer-Link „Cookie-Einstellungen“.
Noch keine Auswahl gespeichert.
Alle akzeptieren, Alle ablehnen oder benutzerdefiniert speichern.