Configuration Presets
Select a preset to auto-fill common configuration patterns. Customize any setting after selecting a preset.
Server Configuration
Basic Settings
Document Root
SSL/TLS Configuration
Performance & Optimization
Security Headers
Logging
Generated Configuration
# Select a preset or configure options above to generate nginx config
1. Save the config to
/etc/nginx/sites-available/yoursite.conf (Ubuntu/Debian) or /etc/nginx/conf.d/yoursite.conf (CentOS/RHEL)2. For Ubuntu/Debian:
sudo ln -s /etc/nginx/sites-available/yoursite.conf /etc/nginx/sites-enabled/3. Test configuration:
sudo nginx -t4. Reload nginx:
sudo systemctl reload nginx or sudo nginx -s reload
Common Nginx Directives Reference
| Directive | Purpose | Example |
|---|---|---|
server_name |
Defines which domains this server block handles | server_name example.com www.example.com; |
listen |
Port and protocol to listen on | listen 80; or listen 443 ssl; |
root |
Document root directory for static files | root /var/www/html; |
index |
Default files to serve for directory requests | index index.html index.htm; |
location |
Defines how to handle specific URI patterns | location / { ... } |
try_files |
Check for files in order, fall back to index | try_files $uri $uri/ /index.html; |
proxy_pass |
Forward requests to backend server | proxy_pass http://localhost:3000; |
proxy_set_header |
Set headers for proxied requests | proxy_set_header Host $host; |
ssl_certificate |
Path to SSL certificate file | ssl_certificate /etc/ssl/certs/cert.pem; |
ssl_certificate_key |
Path to SSL private key file | ssl_certificate_key /etc/ssl/private/key.pem; |
gzip |
Enable or disable gzip compression | gzip on; |
add_header |
Add HTTP response headers | add_header X-Frame-Options DENY; |
return |
Return a status code and optional URL | return 301 https://$host$request_uri; |
access_log |
Path to access log file | access_log /var/log/nginx/access.log; |
error_log |
Path to error log file | error_log /var/log/nginx/error.log; |
What Is Nginx?
Nginx (pronounced "engine-x") is a high-performance web server, reverse proxy, and load balancer. Originally created by Igor Sysoev in 2004 to solve the C10K problem (handling 10,000+ concurrent connections), nginx is now one of the most popular web servers in the world — powering over 400 million websites including Netflix, Dropbox, and WordPress.com.
Unlike traditional web servers that create a new process or thread for each connection, nginx uses an asynchronous, event-driven architecture. This allows it to handle thousands of concurrent connections with minimal memory usage — making it ideal for high-traffic sites and applications.
Nginx excels at serving static content (HTML, CSS, JavaScript, images), proxying requests to backend application servers (Node.js, Python, Go, Ruby), load balancing across multiple servers, SSL/TLS termination, and caching. Its configuration syntax is declarative and straightforward once you understand the core concepts.
Common Nginx Use Cases
1. Static Site Hosting
Nginx serves HTML, CSS, JavaScript, and images directly from disk with exceptional performance. For static sites (plain HTML, Jekyll, Hugo, Gatsby), nginx is significantly faster than Apache or Node.js-based servers — easily handling 10,000+ requests per second on modest hardware.
2. Reverse Proxy for Backend Applications
Nginx sits in front of application servers (Express, Flask, Rails, ASP.NET Core) to handle SSL termination, load balancing, compression, and caching. This offloads work from your application and allows you to run multiple backend services on a single server using different ports or paths.
3. Single Page Application (SPA) Hosting
For React, Vue, Angular, and other SPAs with client-side routing, nginx serves the static build files and uses try_files to route all requests to index.html. This ensures deep links and refreshes work correctly without 404 errors.
4. PHP Application Hosting
Nginx connects to PHP-FPM (FastCGI Process Manager) to serve PHP applications like WordPress, Laravel, and Symfony. Unlike Apache's mod_php, nginx + PHP-FPM uses less memory and handles concurrent requests more efficiently.
5. Load Balancing
Nginx distributes incoming requests across multiple backend servers using round-robin, least connections, or IP hash algorithms. This increases availability, improves response times, and allows zero-downtime deployments.
6. SSL/TLS Termination
Nginx handles HTTPS encryption and decryption, allowing backend servers to communicate over unencrypted HTTP internally. This simplifies backend configuration and centralizes certificate management.
Understanding Nginx Configuration Structure
Nginx configuration files use a hierarchical block structure with directives. The main config file is /etc/nginx/nginx.conf, which typically includes files from /etc/nginx/conf.d/ or /etc/nginx/sites-enabled/.
Configuration Hierarchy
- Main context: Global settings like worker processes and error log
- Events context: Connection processing settings
- HTTP context: HTTP server settings, MIME types, defaults
- Server context: Virtual host definitions (server blocks)
- Location context: URI-specific settings within a server block
Server Block Basics
A server block defines how nginx handles requests for a specific domain or IP address. Key components include:
- listen: Port and protocol (80 for HTTP, 443 ssl for HTTPS)
- server_name: Domain names this block responds to
- root: Base directory for static files
- location blocks: URI-specific configuration
- SSL directives: Certificate paths and TLS settings
Best Practices for Nginx Configuration
1. Always Test Before Reloading
Run sudo nginx -t before reloading. A syntax error will prevent nginx from starting and break your site. Testing catches errors before they cause downtime.
2. Use Separate Server Blocks for HTTP and HTTPS
Create one server block for port 80 that redirects to HTTPS, and another for port 443 with SSL configuration. This is clearer than combining them with conditional logic.
3. Enable Gzip Compression
Gzip reduces bandwidth by 60-80% for text-based assets (HTML, CSS, JavaScript, JSON). Set gzip_comp_level 5; for optimal compression without excessive CPU usage.
4. Set Browser Caching for Static Assets
Add expires directives for images, fonts, and CSS/JS files. For example, expires 1y; for immutable assets with hashed filenames, and expires 1h; for frequently updated files.
5. Add Security Headers
Include headers like X-Frame-Options DENY, X-Content-Type-Options nosniff, and Referrer-Policy no-referrer-when-downgrade. For HTTPS sites, add Strict-Transport-Security to enforce HTTPS.
6. Use try_files for Single Page Applications
SPAs need try_files $uri $uri/ /index.html; to handle client-side routing. Without this, refreshing a deep link returns a 404.
7. Set Appropriate Worker Processes
In nginx.conf, set worker_processes auto; to match the number of CPU cores. This maximizes performance for CPU-bound workloads.
8. Use Upstream Blocks for Proxying
Define backend servers in an upstream block instead of hardcoding IPs in proxy_pass. This makes load balancing and failover configuration easier.
SSL/TLS Configuration with Let's Encrypt
Let's Encrypt provides free SSL certificates with automatic renewal. To set up HTTPS with Let's Encrypt:
Using Certbot (Recommended)
# Install Certbot
sudo apt install certbot python3-certbot-nginx # Ubuntu/Debian
sudo yum install certbot python3-certbot-nginx # CentOS/RHEL
# Obtain certificate and auto-configure nginx
sudo certbot --nginx -d example.com -d www.example.com
# Test auto-renewal
sudo certbot renew --dry-run
Certbot automatically modifies your nginx config to add SSL directives, creates a redirect from HTTP to HTTPS, and sets up a cron job for automatic certificate renewal every 90 days.
Manual SSL Configuration
If you have certificates from another provider, add these directives to your server block:
listen 443 ssl http2;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
Troubleshooting Common Nginx Issues
Configuration Won't Load
Run sudo nginx -t to see the exact syntax error and line number. Common issues: missing semicolons, mismatched braces, invalid directive names, or incorrect file paths.
502 Bad Gateway
Nginx can't reach the backend server specified in proxy_pass. Check that:
- The backend server is running (
systemctl status your-app) - The port in
proxy_passmatches the backend's listening port - Firewall rules allow connections between nginx and the backend
- SELinux is not blocking the connection (CentOS/RHEL)
404 Not Found for Static Files
Verify the root directive points to the correct directory. Check file permissions — nginx needs read access to the files and execute access to all parent directories. Run namei -l /path/to/file to see permission chain.
SSL Certificate Errors
Ensure certificate and key files exist at the specified paths and are readable by nginx. Check certificate validity with openssl x509 -in /path/to/cert.pem -noout -dates. Verify the certificate chain includes intermediate certificates.
Changes Not Taking Effect
After editing config files, reload nginx: sudo systemctl reload nginx or sudo nginx -s reload. Reload does not restart connections — for major changes, use sudo systemctl restart nginx.
Frequently Asked Questions
What is an nginx server block?
A server block is nginx's equivalent to Apache's virtual host. It defines how nginx should handle requests for a specific domain or IP address. Each server block contains directives for server name, root directory, SSL certificates, proxy settings, and other configuration options. You can have multiple server blocks in one nginx installation to host multiple sites.
Where do I put nginx server block configuration files?
On Ubuntu/Debian systems, place config files in /etc/nginx/sites-available/ and create a symlink in /etc/nginx/sites-enabled/ to activate them. On CentOS/RHEL, use /etc/nginx/conf.d/ with a .conf extension. Always test with sudo nginx -t before reloading.
How do I enable SSL/HTTPS in nginx?
Add a listen 443 ssl; directive, specify ssl_certificate and ssl_certificate_key paths, and include SSL parameters like protocols and ciphers. For production, use Let's Encrypt with Certbot to obtain free SSL certificates: sudo certbot --nginx -d yourdomain.com. Always redirect HTTP to HTTPS for security.
What is the difference between a static site and reverse proxy configuration?
Static site configs use root and try_files to serve HTML, CSS, and JavaScript files directly from disk. Reverse proxy configs use proxy_pass to forward requests to a backend application server (Node.js, Python, Go, etc.) and nginx acts as a frontend intermediary handling SSL, caching, and load balancing.
How do I redirect HTTP to HTTPS in nginx?
Create a separate server block listening on port 80 with a return 301 https://$host$request_uri; directive. This sends a permanent redirect to the HTTPS version. Include this before your SSL server block listening on port 443.
What are the most important security headers for nginx?
Key security headers include X-Frame-Options DENY (prevent clickjacking), X-Content-Type-Options nosniff (prevent MIME sniffing), X-XSS-Protection "1; mode=block" (legacy XSS protection), Referrer-Policy no-referrer-when-downgrade, and Content-Security-Policy (prevent XSS and injection attacks). For HTTPS sites, add Strict-Transport-Security "max-age=31536000; includeSubDomains" for HSTS.
How do I enable gzip compression in nginx?
Add gzip on; in your server block or http block, along with gzip_types to specify MIME types to compress (text/css, application/json, application/javascript, etc.), gzip_comp_level 5; (4-6 is optimal), and gzip_min_length 1000; (minimum bytes before compression). This reduces bandwidth by 60-80% and improves load times for text-based assets.
What is the try_files directive in nginx?
try_files checks for files in the specified order. For example, try_files $uri $uri/ /index.html; first checks if the requested URI is a file, then a directory, then falls back to /index.html. This is essential for single-page applications (React, Vue, Angular) that use client-side routing — without it, refreshing a deep link returns a 404.
How do I set up rate limiting in nginx?
Define a limit_req_zone in the http block (outside server blocks): limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s; then apply it in a server or location block with limit_req zone=mylimit burst=20 nodelay;. This limits each IP to 10 requests per second with a burst allowance of 20 requests.
What proxy headers should I set for reverse proxy configurations?
Essential headers include proxy_set_header Host $host; (preserve original host), proxy_set_header X-Real-IP $remote_addr; (client IP), proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; (IP chain), and proxy_set_header X-Forwarded-Proto $scheme; (HTTP vs HTTPS). These help backend applications know the original request details behind the proxy.
How do I test nginx configuration before applying it?
Run sudo nginx -t to test the configuration syntax and validity. If successful, reload nginx with sudo systemctl reload nginx or sudo nginx -s reload. Never restart nginx without testing first — a syntax error will prevent nginx from starting and break your site.
What is the difference between reload and restart for nginx?
reload gracefully applies configuration changes without dropping existing connections — nginx spawns new worker processes with the new config and waits for old processes to finish handling their requests. restart stops nginx completely and starts fresh, dropping all active connections. Use reload for configuration changes, restart only when necessary (major version upgrades, stuck processes).
How do I serve multiple sites on one server with nginx?
Create a separate server block for each site, each with its own server_name directive matching the domain. Place configs in /etc/nginx/sites-available/ and symlink to sites-enabled/. Nginx automatically routes requests to the correct server block based on the Host header. You can host dozens of sites on a single nginx instance.
Privacy & Limitations
- Client-side only. All configuration generation happens in your browser. No data is sent to any server.
- Template starting point. Generated configs are starting points — adjust paths, ports, and settings to match your environment.
- Test before deploying. Always run
sudo nginx -tbefore reloading in production. Test thoroughly in a staging environment first. - Not a substitute for documentation. This tool generates common configurations. For advanced features (load balancing, caching, rewrite rules), consult the official nginx documentation.
Related Tools
These tools complement nginx configuration for DevOps and web development workflows.
- Htaccess Generator - Generate Apache .htaccess configurations for redirects, rewrites, and security
- Dockerfile Generator - Create Docker container configurations for web applications and services
- JSON Formatter - Format and validate JSON configuration files and API responses
- XML Formatter - Format and validate XML configuration files and data
Related Tools
View all toolsBig-O Notation Visualizer
Interactive plot of O(1) through O(n!) complexity curves with operation count comparison
JSON Formatter
Format and beautify JSON with proper indentation
JSON Validator
Validate JSON syntax and show errors
CSV to JSON Converter
Convert CSV data to JSON format with auto-detection
JSON to CSV Converter
Convert JSON arrays to CSV format with nested object handling
JWT Decoder
Decode JWT tokens and display header and payload
Nginx Config Generator FAQ
What is an nginx server block?
A server block is nginx's equivalent to Apache's virtual host. It defines how nginx should handle requests for a specific domain or IP address. Each server block contains directives for server name, root directory, SSL certificates, proxy settings, and other configuration options.
Where do I put nginx server block configuration files?
On Ubuntu/Debian systems, place config files in /etc/nginx/sites-available/ and create a symlink in /etc/nginx/sites-enabled/. On CentOS/RHEL, use /etc/nginx/conf.d/ with a .conf extension. Always test with 'sudo nginx -t' before reloading.
How do I enable SSL/HTTPS in nginx?
Add a listen 443 ssl directive, specify ssl_certificate and ssl_certificate_key paths, and include SSL parameters like protocols and ciphers. For production, use Let's Encrypt with Certbot to obtain free SSL certificates. Always redirect HTTP to HTTPS for security.
What is the difference between a static site and reverse proxy configuration?
Static site configs use root and try_files to serve HTML, CSS, and JavaScript files directly from disk. Reverse proxy configs use proxy_pass to forward requests to a backend application server (Node.js, Python, Go, etc.) and nginx acts as a frontend intermediary handling SSL, caching, and load balancing.
How do I redirect HTTP to HTTPS in nginx?
Create a separate server block listening on port 80 with a return 301 https://$host$request_uri; directive. This sends a permanent redirect to the HTTPS version. Include this before your SSL server block listening on port 443.
What are the most important security headers for nginx?
Key security headers include X-Frame-Options DENY (prevent clickjacking), X-Content-Type-Options nosniff (prevent MIME sniffing), X-XSS-Protection (legacy XSS protection), Referrer-Policy (control referrer information), and Content-Security-Policy (prevent XSS and injection attacks). Modern configs should also include Strict-Transport-Security for HSTS.
How do I enable gzip compression in nginx?
Add gzip on; in your server block or http block, along with gzip_types to specify MIME types to compress (text/css, application/json, etc.), gzip_comp_level (4-6 is optimal), and gzip_min_length (typically 1000 bytes). This reduces bandwidth and improves load times for text-based assets.
What is the try_files directive in nginx?
try_files checks for files in the specified order. For example, try_files $uri $uri/ /index.html; first checks if the requested URI is a file, then a directory, then falls back to /index.html. This is essential for single-page applications (React, Vue, Angular) that use client-side routing.
How do I set up rate limiting in nginx?
Define a limit_req_zone in the http block (limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;) then apply it in a server or location block with limit_req zone=mylimit burst=20 nodelay;. This limits each IP to 10 requests per second with a burst allowance of 20.
What proxy headers should I set for reverse proxy configurations?
Essential headers include proxy_set_header Host $host; (preserve original host), proxy_set_header X-Real-IP $remote_addr; (client IP), proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; (IP chain), and proxy_set_header X-Forwarded-Proto $scheme; (HTTP vs HTTPS). These help backend applications know the original request details.
How do I test nginx configuration before applying it?
Run sudo nginx -t to test the configuration syntax and validity. If successful, reload nginx with sudo systemctl reload nginx or sudo nginx -s reload. Never restart nginx without testing first — a syntax error will prevent nginx from starting and break your site.