NGINX Configuration Cheat Sheet, SSL Setup for NGINX, Load Balancing with NGINX

Nginx CheatSheet

Mastering NGINX: Essential Cheat Sheet for Optimal Web Server Performance

NGINX is a versatile web server capable of serving as a reverse proxy, load balancer, and HTTP cache. Whether you're an experienced system administrator or a beginner, having a quick reference guide can simplify NGINX configuration. In this post, we'll explore some key configurations to help you streamline your server setup.

1. Port Configuration

To set up which ports NGINX listens on, use these directives:

  • listen 80; for HTTP traffic.
  • listen 443 ssl; for HTTPS traffic.
  • listen [::]:80; to enable IPv6 support.

You can also specify IPv6 only by using listen [::]:80 ipv6only=on;

2. Access Logging

To manage access logs:

  • Set the log file path with access_log /path/to/file.log;.
  • Control logging with access_log on; to enable or access_log off; to disable.

3. Miscellaneous Settings

For optimizing performance:

  • Enable GZIP compression with gzip on;.
  • Limit client request size with client_max_body_size 10M;.

4. Serving Static Assets

When serving static files, specify their location:

  • Use root /path/to/website; to define where static assets like images or scripts are located.

5. Handling HTML5 History Mode

For Single Page Applications (SPAs) that use HTML5 History Mode:

  • Configure NGINX to handle all routes with try_files $uri $uri/ /index.html;, ensuring your SPA’s routing is managed client-side.

6. Load Balancing

To distribute traffic across multiple servers:

  • Define your backend servers with an upstream block.
  • Use proxy_pass http://backend; to direct traffic to the load-balanced servers.

7. Domain Name Configuration

Manage different domains and subdomains:

  • Use server_name yourdomain.com; to specify which domain your server should handle.
  • For multiple domains, use server_name yourdomain.com www.yourdomain.com;.
  • To catch all subdomains, use server_name *.yourdomain.com;.

8. Redirects

Set up redirects to manage traffic flow:

  • Redirect from one domain to another with return 301 http://newdomain.com$request_uri;.
  • Redirect specific URLs with location /old-url { return 301 http://newdomain.com; }.

9. Reverse Proxy Setup

To forward requests to backend servers:

  • Use proxy_pass http://backend-server; in your location block to handle client requests and pass them to your backend services.

10. SSL Configuration

To secure your site with SSL:

  • Configure SSL with ssl_certificate /path/to/cert.pem; and ssl_certificate_key /path/to/privkey.pem;.
  • Redirect HTTP traffic to HTTPS with return 301 https://$host$request_uri; for better security.