Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 30 ยท Practice and Review

Nginx and Apache Cheat Sheet

A side-by-side Nginx and Apache cheat sheet: matching directives, everyday commands, status code causes and copy-ready snippets for redirects, proxy, cache and TLS.

This is the page to keep open in a second tab. It puts the equivalent Nginx and Apache directives side by side, lists the commands you type most often, explains what each common status code usually means, and gives short snippets for the jobs that come up every week: redirects, proxying, caching, compression and TLS. Every row links back to the lesson where the idea is explained properly, so you can follow a surprising line to its reasons.

Nothing here replaces nginx -t or apachectl configtest. The snippets are starting points that assume standard paths. Always adapt names, test, then reload. The real servers cannot run on this site, so the reference is read-only. The two JavaScript examples at the end are stand-ins: a status-code lookup and a generator that writes both versions of a redirect. They are not the servers.

Where to look first

Directives Same job, different names.
Commands Test, reload, inspect.
Status codes What 403, 502 and 504 usually mean.
Snippets Redirect, proxy, cache and TLS.

Four sections, all linked to the full lessons.

1 / 2

Directives side by side

Task Nginx Apache
Port to listen on listen 80; Listen 80 plus <VirtualHost *:80>
Site name server_name example.com; ServerName example.com, ServerAlias
Document folder root /var/www/site; DocumentRoot /var/www/site
Default file index index.html; DirectoryIndex index.html
Rules for a URL path location /path/ { ... } <Location "/path/"> ... </Location>
Rules for a folder on disk a location plus root or alias <Directory "/var/www/site/x"> ... </Directory>
Rules for a file name location ~ \.inc$ { ... } <FilesMatch "\.inc$"> ... </FilesMatch>
Serve file or fall back try_files $uri $uri/ /index.php; FallbackResource /index.php
Simple redirect return 301 https://example.com$request_uri; Redirect permanent / https://example.com/
Regex rewrite rewrite ^/old/(.*)$ /new/$1 permanent; RewriteRule ^/old/(.*)$ /new/$1 [R=301,L]
Reverse proxy proxy_pass http://127.0.0.1:3000/; ProxyPass "/" "http://127.0.0.1:3000/"
Fix redirect headers from backend proxy_redirect ProxyPassReverse
Pass the Host header proxy_set_header Host $host; ProxyPreserveHost On
PHP-FPM fastcgi_pass unix:/run/php/php-fpm.sock; SetHandler "proxy:unix:/run/php/php-fpm.sock|fcgi://localhost"
Server pool upstream pool { server ...; } <Proxy "balancer://pool"> BalancerMember ... </Proxy>
Custom error page error_page 404 /404.html; ErrorDocument 404 /404.html
Allow or deny by IP allow 10.0.0.0/8; deny all; Require ip 10.0.0.0/8
Password protection auth_basic "Area"; auth_basic_user_file /etc/nginx/.htpasswd; AuthType Basic, AuthName, AuthUserFile, Require valid-user
Add a response header add_header X-Frame-Options "SAMEORIGIN" always; Header always set X-Frame-Options "SAMEORIGIN"
Compression gzip on; gzip_types text/css application/javascript; mod_deflate: AddOutputFilterByType DEFLATE text/css
Upload size limit client_max_body_size 20m; LimitRequestBody 20971520
Keep-alive time keepalive_timeout 30s; KeepAliveTimeout 5 (seconds)
Access log access_log /var/log/nginx/access.log main; CustomLog logs/access_log combined
Hide version server_tokens off; ServerTokens Prod (server-wide), ServerSignature Off
Split the config include conf.d/*.conf; Include, IncludeOptional
Per-directory override files none .htaccess with AllowOverride

Deeper explanations: Nginx Configuration Syntax, Apache httpd Configuration, Redirects and Rewrites, Reverse Proxy Basics.

Two matching orders worth memorizing:

  • Nginx location: = exact, then longest prefix (a ^~ prefix stops here), then first matching regex, then the remembered prefix. See Location Blocks and Matching Order.
  • Apache merge: Directory and .htaccess (shortest path first), then DirectoryMatch, then Files, then Location; the last one wins. See Apache httpd Configuration.

Commands you use every day

Terminal
# Nginx
sudo nginx -t                      # test the configuration
sudo nginx -T                      # test and print the full effective config
sudo systemctl reload nginx        # graceful: apply changes, keep connections
sudo systemctl restart nginx       # hard: stop and start (drops connections)
sudo nginx -s reload               # signal form of reload (no systemd needed)

# Apache (Debian/Ubuntu names; RHEL uses httpd and apachectl)
sudo apache2ctl configtest         # syntax check
sudo apache2ctl -S                 # show parsed virtual hosts
sudo apache2ctl -M                 # list loaded modules
sudo systemctl reload apache2      # graceful reload
sudo a2ensite site.conf            # enable a site (a2dissite to disable)
sudo a2enmod rewrite headers       # enable modules (a2dismod to disable)

# Inspecting a running system
sudo ss -ltnp | grep -E ':80|:443' # what listens on the web ports
sudo journalctl -u nginx -n 50     # recent service messages
sudo tail -f /var/log/nginx/error.log

For requests, curl is the sharpest tool:

Terminal
curl -I https://example.com/                          # headers only
curl -sv -o /dev/null https://example.com/ 2>&1 | head -30   # handshake and headers
curl -I -H "Host: example.com" http://127.0.0.1/      # test a vhost without DNS
curl --resolve example.com:443:203.0.113.10 https://example.com/   # force an IP
curl -I -H "Accept-Encoding: gzip" https://example.com/app.css     # check compression
openssl s_client -connect example.com:443 -servername example.com </dev/null   # inspect the certificate chain

More detail: Installing and Finding Your Way Around and Logs and Troubleshooting.

Status codes and their usual causes

Code Meaning Usual causes and first checks
301 / 302 Moved permanently / temporarily Intended redirect, or a redirect loop if repeated forever
400 Bad request Malformed request, oversized headers or cookies
401 Authentication needed Basic auth or app login missing or wrong
403 Forbidden File permissions, no index file with autoindex off, deny or Require rule, SELinux
404 Not found Wrong root or alias, missing file, rule order
405 Method not allowed Static location receiving a POST, or a limit_except rule
413 Body too large client_max_body_size (default 1 MB) or LimitRequestBody
414 URI too long Extremely long query string, buffer limits
429 Too many requests A rate limit with limit_req_status 429
499 Client closed request (nginx only) The client gave up before the answer, often because of slow backends
500 Internal server error Application error, or an Apache rewrite loop or .htaccess error
502 Bad gateway Backend refused the connection, crashed, or sent an invalid reply
503 Service unavailable No live upstream, overload, maintenance mode
504 Gateway timeout Backend reachable but too slow for proxy_read_timeout

Always confirm in the error log, because the same status can have different causes. The log lines that match each cause are covered in Logs and Troubleshooting.

Snippets to copy and adapt

Redirect HTTP to HTTPS and pick one host name

NGINX
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}
APACHE
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

Reverse proxy with the headers a backend needs

NGINX
location /api/ {
    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;
    proxy_set_header X-Forwarded-Proto $scheme;
}
APACHE
ProxyPreserveHost On
RequestHeader set X-Forwarded-Proto "https"
ProxyPass        "/api/" "http://127.0.0.1:3000/"
ProxyPassReverse "/api/" "http://127.0.0.1:3000/"

Long-lived caching for fingerprinted assets

NGINX
location ~* \.(?:css|js|woff2|svg|png|jpg|webp)$ {
    add_header Cache-Control "public, max-age=31536000, immutable" always;
    access_log off;
}
APACHE
<FilesMatch "\.(css|js|woff2|svg|png|jpg|webp)$">
    Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>

Use this only for files whose names change when their content changes (app.3f9c1a.js). For ordinary files use a short lifetime or no-cache with validators; see Static Files, Caching and MIME Types.

Compression

NGINX
gzip on;
gzip_comp_level 5;
gzip_types text/css application/javascript application/json image/svg+xml;
APACHE
AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json image/svg+xml

HTML is always compressed by nginx's gzip when it is on, and images that are already compressed (JPEG, PNG, WebP, video) should never be listed. See HTTP/2, HTTP/3, gzip and Brotli.

TLS

NGINX
listen 443 ssl;
http2 on;
ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols       TLSv1.2 TLSv1.3;
add_header Strict-Transport-Security "max-age=31536000" always;
APACHE
Protocols h2 http/1.1
SSLEngine on
SSLCertificateFile    /etc/letsencrypt/live/example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
SSLProtocol           -all +TLSv1.2 +TLSv1.3
Header always set Strict-Transport-Security "max-age=31536000"

Get and renew certificates with sudo certbot --nginx -d example.com or sudo certbot --apache -d example.com; the renewal timer is installed with the package. See HTTPS, TLS and Let's Encrypt.

Rate limit and block dotfiles (nginx)

NGINX
limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;   # http level

location / {
    limit_req zone=perip burst=20 nodelay;
}
location ~ /\.(?!well-known) { deny all; }

Two stand-ins to play with

The first looks up a status code. Add codes you meet in your own logs and keep it as a personal glossary.

JS Stand-in: status code lookup

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second generates both versions of a path redirect from one description. It shows how the same intent is spelled in each server, and the exact-match nuance: nginx needs = /old to avoid matching /older, while Apache's Redirect matches on path segments.

JS Stand-in: redirect snippet generator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real configuration is always a little different from a template: a location block belongs inside a server block, and Apache's Redirect can live in a vhost or a .htaccess file. The generator only reminds you of the shape.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which pair of directives does the same job of 'send everything that is not a file to index.php'?

    Both implement the front-controller pattern: serve a real file if there is one, otherwise hand the request to index.php.
  2. 2. Which header combination is right for a fingerprinted asset such as app.3f9c1a.js?

    The file name changes whenever the content does, so browsers may keep it for a year and never revalidate.
  3. 3. A page returns 499 in the nginx access log. What does it indicate?

    499 is an nginx-specific status for a client that gave up. It often points to a slow backend, because users close the tab while waiting.
  4. 4. Which command shows the complete effective nginx configuration, including included files, after testing it?

    Upper-case -T tests the configuration and then prints all of it, which is the quickest way to see what nginx actually loaded.

Summary

  • Most directives have a direct counterpart: server_name and ServerName, root and DocumentRoot, return and Redirect, proxy_pass and ProxyPass.
  • Apache merges sections in a fixed order; nginx picks one location by exact, prefix and regex rules.
  • Test with nginx -t or apachectl configtest, reload gracefully, then reproduce with curl -I.
  • Learn the status codes: 403 permissions, 413 body size, 502 broken backend, 504 slow backend, 499 impatient client.
  • Use fingerprinted file names with long immutable caching, and keep dotfiles denied except .well-known.
  • Copy snippets as starting points, never as finished configuration.

This is the end of the course. A good next step is to revisit Project: A Secure Load-Balanced Production Setup and rebuild it from memory on a test server.