Nginx Directives Cheat Sheet

Common Nginx configuration for static sites, proxies, PHP and SSL


Basic server block

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example;
    index index.html index.php;
}

Reverse proxy

location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

PHP-FPM

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}

Redirects

server {
    listen 80;
    server_name example.com;
    return 301 https://example.com$request_uri;
}
rewrite ^/old$ /new permanent;
rewrite ^/page/(.*)$ /$1 last;

SSL / HTTPS

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate     /etc/ssl/example.crt;
    ssl_certificate_key /etc/ssl/example.key;
}

Compression and caching

gzip on;
gzip_types text/css application/javascript application/json;

location ~* \.(jpg|jpeg|png|gif|css|js|svg|woff2)$ {
    expires 30d;
    add_header Cache-Control "public";
}

Testing and reloading

nginx -t            # test config
nginx -s reload     # reload without downtime
nginx -s stop       # stop