Skip to main content

Nginx Configuration That Keeps Sites Fast

· 6 min read
Customer Care Engineer

Published on September 19, 2026

Nginx Configuration That Keeps Sites Fast

A site can look perfectly healthy until a small Nginx configuration mistake turns a routine deploy into a 502 error, an SSL warning, or a redirect loop that sends visitors nowhere useful. Nginx is fast and dependable, but it is also exacting: one directive in the wrong place can change how an entire site behaves. The good news is that a clean approach makes Nginx configuration much less mysterious.

This guide focuses on the settings that matter most when hosting websites: server blocks, PHP handling, HTTPS, redirects, static files, caching, and safe testing. You do not need to memorize every Nginx directive. You need to understand which decisions affect your site and how to verify them before they affect your visitors.

Start With a Clear Nginx Configuration Layout

Most Linux installations separate global settings from individual website settings. The main configuration file, commonly found at /etc/nginx/nginx.conf, controls worker processes, logging, compression, and included configuration directories. Individual sites usually live in a directory such as sites-available, sites-enabled, or conf.d.

This separation is useful for a practical reason: global settings should be changed carefully and rarely, while website-level settings need regular attention. A new domain, a staging site, or a redirect rule belongs in that site’s server block, not in the main file.

Before changing anything, identify the active configuration and test it:

bash nginx -t

If the test succeeds, reload Nginx without dropping active connections:

bash systemctl reload nginx

Use reload for normal configuration changes. A full restart is sometimes necessary, but it is not the first move when you are updating a virtual host. Small habits like this prevent a five-minute task from becoming a late-night recovery job.

Build One Server Block Per Website

A server block tells Nginx which domain it serves, where website files are stored, and how requests should be handled. Think of it as the front desk for one website. When several domains share one server, a tidy server block is what keeps traffic going to the right place.

A basic HTTP site might look like this:

server {
listen 80;
server_name example.com www.example.com;

root /var/www/example.com/public;
index index.php index.html;

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

The server_name should list every hostname you intend to serve. If visitors can reach both the root domain and www, include both, then decide which one should become canonical through a redirect.

The root path must point to the directory containing public web files, not necessarily the project’s top-level folder. For WordPress, this is often the folder where wp-admin, wp-content, and wp-includes exist. For Laravel and similar frameworks, it is typically the public directory. Pointing Nginx at the wrong folder can expose files that should never be publicly available.

The try_files rule deserves attention. It checks whether a requested file or directory exists before passing unmatched requests to the application. This is essential for WordPress permalinks and many modern PHP applications. Without it, pages may work only when visitors use the full URL with index.php attached. Not ideal, and not a problem you want customers to report first.

Avoid the Default Server Trap

Nginx needs a default server for requests that do not match a configured hostname. If the wrong site is set as default, an unknown domain or a direct IP request may display somebody else’s website. That is confusing at best and risky at worst.

For multi-site servers, use a simple default server that returns no useful content, such as a 404 response. Keep real websites in explicit server blocks with their own server\_name values. It is a small boundary that makes a shared server easier to manage.

Configure PHP Without Guesswork

Nginx does not process PHP on its own. It passes PHP requests to PHP-FPM, which runs the code. The connection is normally a Unix socket or a local TCP port.

A common PHP location block looks like this:

location ~ \.php$ {
try_files $uri =404;

include fastcgi_params;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

The PHP version and socket path vary by server. If Nginx returns a 502 Bad Gateway error after a PHP update, the socket path is one of the first places to check. PHP-FPM may be stopped, running a different version, or listening somewhere other than the path defined in Nginx.

The try_files $uri =404; line is also worth keeping. It stops Nginx from sending requests for nonexistent PHP files to the PHP processor. That improves both security and error handling.

For WordPress, avoid adding broad rules copied from random forum posts unless you know why they are needed. WordPress already works well with a clean try_files setup, proper PHP handling, and writable permissions only where WordPress needs them. More rules do not automatically mean a better configuration.

Make HTTPS the Default Path

Every public website should serve HTTPS and redirect HTTP traffic to the secure version. The usual pattern is an HTTP server block that performs only the redirect, plus a separate HTTPS block that serves the site.

server {
listen 80;
server_name example.com www.example.com;

return 301 https://example.com$request_uri;
}

The HTTPS server block then listens on port 443 and includes the certificate and private key paths. Certificate files depend on how SSL is provisioned, but the principle stays the same: keep certificate configuration inside the site that uses it.

A permanent 301 redirect is appropriate once you are confident about the destination. During an active migration or a short-term test, a 302 redirect can be safer because browsers do not cache it as aggressively. This is one of those cases where the technically strongest-looking option is not always the right operational choice.

Also choose one preferred hostname. Redirect either www to the root domain or the root domain to www. Serving both without a consistent redirect can split analytics, create duplicate pages for search engines, and make cookie behavior harder to diagnose.

Serve Static Files Efficiently and Safely

Images, CSS, JavaScript, fonts, and downloadable files should not consume PHP resources when Nginx can deliver them directly. Set reasonable browser caching for files that rarely change:

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

Thirty days is a sensible starting point, not a law. If your file names include version numbers or hashed filenames, longer caching can work very well. If the same filename is frequently replaced, a long cache can leave visitors seeing an older design or script. Caching is always an agreement between speed and how quickly changes must appear.

Do not expose hidden files by accident. A simple rule can block requests for dotfiles while allowing the .well-known directory used by certificate validation:

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

Depending on your certificate setup, you may need a specific exception for .well-known. Test renewal behavior after making access rules stricter. Security rules should reduce exposure, not quietly break services you rely on.

Use Security Headers With Context

Response headers can improve browser-side protection, but they need testing. Common examples include X-Content-Type-Options nosniff, Referrer-Policy, and Content-Security-Policy. The last one is powerful and easy to misconfigure. A strict policy can block scripts, fonts, payment widgets, analytics, or embedded content if it is introduced without understanding the site’s dependencies.

Start with headers that have a clear purpose and low risk, then add a content security policy in report-only mode if your application supports it. The goal is not to collect an impressive stack of directives. The goal is to reduce real risk without breaking the pages people need to use.

Rate limiting can also help with abusive traffic and login attacks, especially for WordPress login endpoints. But aggressive limits can block legitimate users behind shared office networks or mobile carriers. Review logs and adjust based on actual traffic patterns rather than choosing numbers that merely sound strict.

Test Changes Like They Matter

Every Nginx change should follow the same short routine: back up or copy the current file, make one focused change, run nginx -t, reload Nginx, and test the website from a browser and command line. Check the intended domain, the non-canonical domain, HTTP, HTTPS, and a page handled by PHP.

When something fails, read the error logs before rewriting the configuration. Nginx access and error logs often reveal whether the problem is a missing file, incorrect permission, failed upstream connection, or bad redirect. Guessing can create three new problems while fixing none.

A control panel can remove much of this manual work by creating and organizing website-level settings, certificates, PHP versions, and logs in one place. FASTPANEL is designed for that practical middle ground: you keep control of your hosting environment without turning every domain change into a configuration archaeology project.

Good Nginx configuration is not about building the longest file or using every available directive. It is about making each site predictable: the right domain reaches the right files, PHP has a healthy upstream, HTTPS is enforced, static content is efficient, and changes are tested before visitors meet them. Once that foundation is in place, managing a growing server becomes far less dramatic - exactly how it should be.