NGINX Cheat Sheet
Server Block Structure
# Define a server block (listens on port 80 by default for HTTP)
server {
listen [port]; # Optional, default is 80
server_name example.com www.example.com;
root /path/to/root;
index index.html;
}
Location Block
# Define location blocks for specific path handling
location / {
# Configuration for the root location
}
location /static/ {
# Configuration for the "/static/" path
}
Listen on Port
server {
# Standard HTTP Protocol
listen 80;
# Standard HTTPS Protocol
listen 443 ssl;
# Listen on 80 using IPv6
listen [::]:80;
# Listen only on using IPv6
listen [::]:80 ipv6only=on;
}
Redirects
# Redirects www to non-www
server {
listen 80;
server_name www.example.com;
return 301 http: //example.com$request_uri;
}
Domain Name
server {
# Listen to yourdomain.com
server_name yourdomain.com;
# Listen to multiple domains
server_name yourdomain.com www.yourdomain.com;
# Listen to all domains
server_name *.yourdomain.com;
# Listen to all top-level domains
server_name yourdomain.*;
# Listen to unspecified Hostname (Listens to IP address itself)
server_name "";
}
HTTPS Configuration
# Enable SSL for secure connections
server {
listen 443 ssl;
server_name example.com;
# SSL certificates from a trusted CA
ssl_certificate /path/to/certificate.crt;
ssl_certificate_key /path/to/private.key;
# Configure appropriate cipher suites
ssl_chipers HIGH:!aNULL:!MD5;
# Additional SSL configurations go here
}
Reverse Proxy
server {
# Set up a reverse proxy for a backend application
location /app/ {
proxy_pass http://backend-server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
Basic Authentication
server {
# Set up basic authentication
location /secure/ {
auth_basic "Restricted";
auth_basic_user_file /path/to/.htpasswd;
}
}
Load Balancing
# Configure load balancing with round-robin method
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
Custom Error Page
# Define custom error pages for various status code
error_page 404 /404.html;
location = /404.html {
root /path/to/error/pages;
}
Gzip Compression
# Enable Gzip compression for text-based content
gzip on;
gzip_types text/plain text/css application/javascript text/xml;
No Comments