Nginx cheat sheet

This cheat sheet brings together the common settings in Nginx configuration files, from testing and reloading the configuration, through the server block, location match order, and redirects, to PHP-FPM, reverse proxy, caching, and security headers. You can search for a setting, filter by topic, and copy it with one click.

Commands and configuration testing

  • nginx -t

    Checks the syntax of the configuration files and tries to open the files they refer to, such as certificates and logs. Run it after every change and before reloading.

  • nginx -T

    Runs the same test and prints every configuration file that was loaded, including files pulled in with the include directive. Useful for finding the setting that is actually in effect when the configuration is spread across many files.

    Example: nginx -T | grep -n server_name

  • nginx -t && systemctl reload nginx

    Tests the configuration and reloads it only if the test passes. During a reload, the existing worker processes finish the requests they are handling, and the website keeps running without dropping connections.

  • nginx -s reload

    Reloads the configuration by sending a signal to the master process, as an alternative to systemctl. If the new configuration has an error, the server keeps running with the previous configuration.

  • nginx -s reopen

    Reopens the log files, for example after log rotation has moved or compressed them.

  • nginx -v

    Shows the Nginx version. Some of the settings on this page were added in relatively recent versions, so check the version before you copy them.

  • nginx -V

    Shows the version, the compiler version, and the build parameters, including the modules that were built in, for example --with-http_realip_module.

File layout

  • /etc/nginx/nginx.conf

    The main configuration file in most package installations. When Nginx is built from source, it's usually in /usr/local/nginx/conf.

  • /etc/nginx/conf.d/*.conf

    A directory for additional configuration files, which the main configuration file loads inside the http block. A common practice is to keep a separate file for each website and avoid editing nginx.conf itself.

  • /etc/nginx/sites-available/ /etc/nginx/sites-enabled/

    A layout common on Debian and Ubuntu: website configurations are kept in sites-available and are loaded only when they have a symbolic link in the sites-enabled directory.

  • ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

    Enables a website in the Debian and Ubuntu layout. To disable the website, delete only the link, and the original file stays. Then test the configuration and reload it.

  • include /etc/nginx/snippets/security-headers.conf;

    Loads an external configuration file at the point where the directive appears. This way, you keep repeated settings, such as security headers, in one file and include it in several websites.

  • /var/log/nginx/access.log /var/log/nginx/error.log

    The common location of the access log and the error log in package installations. The error log is the first place to look when a website returns a 502 or 403 error.

The server block

  • server { listen 80; listen [::]:80; server_name example.com www.example.com; root /var/www/example.com; index index.html; }

    A basic website over HTTP, on IPv4 and IPv6. The server_name directive sets which domain names the block answers to, root sets the directory of the files, and index sets the file served when a directory is requested.

  • server { listen 443 ssl; listen [::]:443 ssl; http2 on; server_name example.com; ssl_certificate /etc/ssl/example.com/fullchain.pem; ssl_certificate_key /etc/ssl/example.com/privkey.pem; root /var/www/example.com; }

    A website over HTTPS with HTTP/2. In recent versions of Nginx, HTTP/2 is turned on with the http2 on directive, and the http2 parameter of the listen line is deprecated. In older versions, write listen 443 ssl http2 instead of the http2 on directive.

  • server_name example.com *.example.com;

    The * character replaces the first or last part of the domain name, here any subdomain of example.com. When several blocks match, an exact name wins over a name with a wildcard.

  • server_name .example.com;

    A dot at the start of the name is a shorthand that matches both the domain itself and all of its subdomains.

  • server { listen 80 default_server; server_name _; return 444; }

    A default block for requests with a domain name that isn't configured on the server, for example direct access to the IP address. Code 444 is a special Nginx code that closes the connection without a response.

  • location /images/ { alias /data/photos/; }

    The alias directive replaces the part of the URL that matched the location with another path, while root appends the full URL to the path. Here, /images/logo.png is served from the file /data/photos/logo.png. Make sure both paths end with a slash.

location and match order

  • location = /favicon.ico { access_log off; }

    Exact match (=): matches only this exact URL, and when such a match is found, the search stops immediately. Suited to URLs that are requested often.

  • location /docs/ { try_files $uri $uri/ =404; }

    Prefix match (no modifier): of all the matching prefixes, Nginx remembers the longest one and goes on to check regular expressions. The remembered prefix is used only if no regular expression matches.

  • location ^~ /static/ { expires 7d; }

    Prefix with ^~: when this is the longest matching prefix, regular expressions aren't checked at all. This keeps a regex location, for example one for image files, from catching requests for this directory.

  • location ~ \.php$ { # PHP-FPM settings }

    A case-sensitive regular expression (~). The expressions are checked in the order they appear in the file, and the first match is chosen, so their order matters.

  • location ~* \.(?:jpg|jpeg|png|webp|svg)$ { expires 30d; }

    A case-insensitive regular expression (~*), so both .JPG and .jpg match.

  • location @fallback { proxy_pass http://127.0.0.1:3000; }

    A named location (@): it isn't used for regular requests, only as an internal target, for example in the last parameter of try_files or in error_page.

  • location /internal-files/ { internal; }

    Limits a location to internal requests only, such as error pages. Direct access from the browser gets a 404 code.

try_files and PHP

  • location / { try_files $uri $uri/ =404; }

    A static website: Nginx looks for a file with the name in the URL, then a directory, and returns 404 if neither exists.

  • location / { try_files $uri $uri/ /index.php?$args; }

    The common pattern for WordPress and similar content management systems: existing files are served directly, and every other URL is passed to index.php with its parameters. This is the equivalent of the WordPress rewrite rules in a .htaccess file.

  • root /var/www/example.com/public; location / { try_files $uri $uri/ /index.php?$query_string; }

    The common pattern for Laravel and frameworks with a front controller. The root directory points to the public directory, so the application's code and configuration files can't be accessed from the browser.

  • location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/run/php/php-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }

    Passes PHP files to PHP-FPM for processing. The socket path varies between distributions and versions, so copy it from the PHP-FPM pool configuration. The line try_files $uri =404 prevents passing files that don't exist. Some distributions include a ready-made file in the snippets directory that already contains some of these settings.

  • fastcgi_pass 127.0.0.1:9000;

    Connects to PHP-FPM by address and port instead of a socket, when the pool is configured to listen on TCP.

  • fastcgi_read_timeout 120s;

    How long to wait for a response from PHP-FPM. The default is 60 seconds, and when a long script runs past this time, the visitor gets a 504 error. The time is measured between two successive reads, not for the whole response.

Redirects and rewrites

  • server { listen 80; listen [::]:80; server_name example.com www.example.com; return 301 https://example.com$request_uri; }

    Redirects all HTTP traffic to the HTTPS address without www, with the path and parameters, in a single permanent redirect. Before you turn it on, make sure the HTTPS block and the SSL certificate work.

  • server { listen 443 ssl; http2 on; server_name www.example.com; ssl_certificate /etc/ssl/example.com/fullchain.pem; ssl_certificate_key /etc/ssl/example.com/privkey.pem; return 301 https://example.com$request_uri; }

    Redirects www to the address without www over HTTPS as well. The SSL certificate must also cover the name with www, or the browser shows a warning before the redirect. For a redirect in the opposite direction, swap the names.

  • location = /old-page { return 301 https://example.com/new-page; }

    A permanent redirect from a single page to a new page. The Nginx documentation recommends a separate server or location block with return instead of an if condition on the domain name.

  • rewrite ^/blog/(.*)$ /news/$1 permanent;

    A permanent redirect (301) based on a regular expression. The part in parentheses is captured in $1, and the original parameters are kept in the target URL. The redirect flag sends a temporary redirect (302).

  • rewrite ^/product/([0-9]+)$ /product.php?id=$1 last;

    An internal rewrite: the visitor sees /product/25, and the server processes product.php. The last flag starts a new location search based on the new URL. Inside a location, use the break flag, because last can create a loop that ends in a 500 error.

  • rewrite ^/search/(.*)$ /find?q=$1? last;

    A question mark at the end of the target URL stops the original parameters from being appended to the new URL.

  • return 302 https://example.com/sale;

    A temporary redirect, for example when the original page will be back later. The return directive supports the redirect codes 301, 302, 303, 307, and 308.

Caching and compression

  • location ~* \.(?:css|js|woff2|jpg|jpeg|png|webp|svg)$ { expires 30d; access_log off; }

    Keeps static files in the browser cache for 30 days. The expires directive sends both Expires and Cache-Control with max-age, so don't add another Cache-Control with add_header next to it.

  • add_header Cache-Control "public, max-age=31536000, immutable";

    Caching for a full year, for files whose name changes with every update, such as app.3f9a2c.js. With files whose name stays the same, visitors may see an old version until the period ends.

  • add_header_inherit merge;

    Caution, a common trap: a location inherits the add_header directives of the server block only when it has no add_header of its own. Adding a cache header in a location removes all the security headers there. The fix is to repeat the headers in the location or, in recent versions of Nginx, to add the add_header_inherit merge directive, which merges in the headers from the level above.

  • gzip on; gzip_vary on; gzip_min_length 1000; gzip_proxied any; gzip_types text/plain text/css application/javascript application/json application/xml image/svg+xml;

    gzip compression for text files. The text/html type is always compressed and doesn't need to be listed, and gzip_vary adds the Vary: Accept-Encoding header for intermediate caches. Images such as JPEG and WebP are already compressed, so don't add them.

Security headers

  • add_header X-Content-Type-Options "nosniff" always;

    Stops the browser from guessing the file type. The always parameter sends the header with every response code, including error pages. Without it, the header is sent only with codes such as 200, 301, and 304.

  • add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    Sets how much information about the current page is sent to another website when a visitor clicks a link: the full URL is sent only within the website, and other websites get only the domain name.

  • add_header X-Frame-Options "SAMEORIGIN" always;

    Prevents other websites from displaying your website in an iframe, as protection against clickjacking. The modern way to get the same protection is frame-ancestors in a CSP policy.

  • add_header Content-Security-Policy "frame-ancestors 'self'" always;

    The CSP version of the protection against display in an iframe, which also lets you name allowed websites. When the website already sends a CSP policy, add frame-ancestors to the existing policy.

  • add_header Strict-Transport-Security "max-age=31536000" always;

    Caution: tells the browser to access the website only over HTTPS for the period set in seconds, here one year. An SSL certificate problem during that period will block access to the website. Start with a small value, and add includeSubDomains only when all subdomains work over HTTPS.

  • server_tokens off;

    Removes the Nginx version number from error pages and from the Server header. The default is on.

Reverse proxy and WebSocket

  • 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; proxy_set_header X-Forwarded-Proto $scheme; }

    Passes requests to an application listening on a local port, for example Node.js or Python. Without the Host header, the application gets the address from proxy_pass, and the X-Forwarded headers pass on the visitor's address and the original protocol.

  • location /api/ { proxy_pass http://127.0.0.1:8080/; }

    Careful with the slash: when proxy_pass includes a path, even a single slash, the part that matched the location is replaced with it, so /api/users reaches the application as /users. Without a path, as in http://127.0.0.1:8080, the URL is passed as is.

  • map $http_upgrade $connection_upgrade { default upgrade; '' close; }

    Goes in the http block and sets the value of the Connection header based on the visitor's upgrade request, in preparation for WebSocket in the next setting.

  • location /ws/ { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_read_timeout 300s; }

    Support for WebSocket connections, for example for chat or real-time updates. The proxy_http_version 1.1 line is needed in older versions of Nginx, and in recent versions it's the default. Nginx closes a connection that has had no data for 60 seconds, so the time is extended here.

Access, limits, and the visitor's IP

  • client_max_body_size 64m;

    The maximum request size, for example for file uploads. The default is only 1 MB, and a larger request gets a 413 error. On a PHP website, also raise the upload limits in the PHP settings.

  • location ~ /\.(?!well-known) { deny all; }

    Blocks access to files and directories whose names start with a dot, such as .git and .env, and returns a 403 code. The .well-known directory is excluded because it's used to validate SSL certificates and other services.

  • location ~* \.(?:bak|sql|log|ini|sh)$ { deny all; }

    Blocks files by extension, such as backups, database files, and logs left in the website directory.

  • location /admin/ { allow 203.0.113.10; allow 198.51.100.0/24; deny all; }

    Allows access only from specific IP addresses. The rules are checked in order until the first match, so deny all goes last. On a PHP website, pay attention to the match order, as explained in the password protection setting below.

  • htpasswd -c /etc/nginx/.htpasswd admin

    A shell command, not a line in the configuration file. Creates a password file with a first user. The htpasswd tool comes in the httpd-tools or apache2-utils package, depending on the distribution. Caution: the -c option overwrites an existing file, so to add more users, run the command without it.

  • location ^~ /admin/ { auth_basic "Restricted area"; auth_basic_user_file /etc/nginx/.htpasswd; location ~ \.php$ { fastcgi_pass unix:/run/php/php-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }

    Protects a directory with a username and password. On a PHP website, it's important to use ^~ and an inner PHP block: otherwise requests for .php files in the directory are handled by the PHP regex location and bypass the protection. Turn on the protection only on a website that runs over HTTPS.

  • limit_req_zone $binary_remote_addr zone=perip:10m rate=10r/s;

    Goes in the http block and defines a zone for rate limiting by IP address, here up to 10 requests per second on average. On a 64-bit server, a 1 MB zone keeps the state of about 8,000 addresses.

  • limit_req zone=perip burst=20 nodelay; limit_req_status 429;

    Turns on the limit in a server or location block, alongside its existing settings. burst allows a short burst of requests, and nodelay serves it without delay. Excess requests are rejected with code 503 by default, and here with code 429. A value that is too low can block regular visitors.

  • set_real_ip_from 192.0.2.0/24; real_ip_header X-Forwarded-For; real_ip_recursive on;

    For a website behind a CDN or a load balancer, replaces the proxy address with the visitor's real address, in the logs and in access rules. In set_real_ip_from, list only the address ranges the provider publishes, or anyone can spoof their address. When Nginx is built from source, the module isn't built by default, and you can confirm it's there in the nginx -V output.

Error pages and logs

  • error_page 404 /404.html;

    Shows a custom page when a page isn't found, and the visitor still gets the original 404 code.

  • error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; internal; }

    One page for several server error codes. The internal directive blocks direct access to the page, so it's shown only as an error page.

  • access_log /var/log/nginx/example.com.access.log;

    A separate access log for the website, in the default combined format. A separate log for each website makes it easier to check its traffic and errors.

  • access_log off;

    Turns off request logging at the level where it appears, for example in the location for static files, to keep the log smaller.

  • error_log /var/log/nginx/example.com.error.log warn;

    An error log for the website with a logging level. The levels, from the most detailed to the most severe, are debug, info, notice, warn, error, crit, alert, and emerg, and each level also includes the more severe ones. The default is error, and the debug level requires a build with --with-debug.

Nginx doesn't read .htaccess files, and all settings go in the server's configuration files, inside blocks: http for general settings, server for each website, and location for specific URLs on the website. The settings equivalent to .htaccess rules are on the .htaccess cheat sheet, and the differences between web servers are explained on the web servers page. The domain names, paths, and IP addresses on this page are examples, so replace them with your real values.

Before any change, save a copy of the file, and after the change, run nginx -t and only then reload the configuration. Some settings exist only in recent versions of Nginx, such as the http2 on and add_header_inherit directives, and in recent versions proxy connections use HTTP/1.1 by default. The nginx -v command shows the installed version.

To check the headers your website sends after the change, use the HTTP header analyzer, and to check the redirect chain of a URL, use the redirect checker.

Did you know?

On a Linux VPS, you connect over SSH with full root access and install the web server that suits your website. This way, you can edit every Nginx configuration file, from website settings and SSL certificates to a reverse proxy for applications running on the server.

Linux VPS plans

Nginx FAQ

How do I apply a change to the Nginx configuration without taking my website down?

After editing the file, run nginx -t to check the syntax, and if the test passes, reload the configuration with systemctl reload nginx or nginx -s reload. During a reload, Nginx starts new processes with the new configuration, and the old processes finish the requests they are handling, so visitors aren't disconnected. If the new configuration has an error, the server keeps running with the previous configuration.

How do I move a website on Nginx to HTTPS?

Once an SSL certificate is installed, set up a server block that listens on port 443 with the ssl parameter and the ssl_certificate and ssl_certificate_key directives. In the block that listens on port 80, add return 301 to the HTTPS address with $request_uri, so every URL is redirected to the same path on the encrypted version. This cheat sheet shows both blocks in full, including a redirect to your preferred address with or without www.

Can I use a .htaccess file with Nginx?

No. Nginx doesn't read .htaccess files, and all rules go in the server's configuration files. Most rules have a simple equivalent: redirects are written with return or rewrite, friendly URLs for WordPress and Laravel with try_files, and access blocks with deny. The advantage is performance, because the server doesn't have to look for such files on every request.

How do I set up Nginx as a reverse proxy for an application?

In a location block, add proxy_pass with the address and port the application listens on, for example http://127.0.0.1:3000, and pass on the Host, X-Forwarded-For, and X-Forwarded-Proto headers, so the application knows the domain, the visitor, and the protocol the visitor uses. For applications with WebSocket connections, also add the Upgrade and Connection headers. This way, Nginx handles the SSL certificate, caching, and compression, and the application can focus on its own logic.

How do I increase the maximum upload size in Nginx?

Raise the value of client_max_body_size in the http, server, or location block, for example client_max_body_size 64m. The default is 1 MB, and a larger file is blocked with a 413 error. On PHP websites, also raise upload_max_filesize and post_max_size in the PHP settings the same way, and then reload Nginx and PHP-FPM.

Shopping cart

Your cart is emptyYou can start with one of our popular plans.

Site search

Accessibility

Text size
100%
Accessibility statement