Hosting & Deployment

Nginx Server Blocks and Reverse Proxy Basics

Configure Nginx server blocks for PHP-FPM or HTTP upstreams, with correct routing, forwarded headers, and troubleshooting steps.

Nginx server blocks map incoming host names to a document root or an upstream application. Nginx can serve static files directly, pass PHP requests to PHP-FPM using FastCGI, or proxy HTTP traffic to another service. These are different protocols and should not be mixed: fastcgi_pass is for FastCGI backends, while proxy_pass is for HTTP upstreams.

A simple PHP-FPM server block

server {
    listen 80;
    server_name example.com www.example.com;
    root /srv/www/example/public;
    index index.php;

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

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/php-fpm-example.sock;
    }

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

The socket path and included parameter file vary by distribution. Confirm that the PHP-FPM pool creates the socket with permissions that allow Nginx to connect. Never expose internal configuration files, repository metadata, or private storage through a location rule.

Reverse proxy responsibilities

When Nginx sits in front of an application server, it commonly forwards the original host and client information using headers such as Host, X-Real-IP, and X-Forwarded-For. The backend must trust these headers only from known proxy addresses. Otherwise, a client may forge its apparent IP address or scheme.

Validate and reload

Use:

sudo nginx -t
sudo systemctl reload nginx
sudo nginx -T

nginx -T prints the effective configuration and may reveal secrets embedded in configuration files; handle its output carefully. Reload rather than restart when possible so existing connections can finish.

Common mistakes

A missing SCRIPT_FILENAME often causes PHP file-not-found errors. A wrong socket path causes gateway errors. An incorrect try_files rule can bypass the front controller or create redirect loops. Check Nginx error logs and PHP-FPM logs together; each layer reports a different part of the request. If a control panel manages Nginx, use its supported configuration interface rather than editing generated files.

Share this page Help other developers discover this resource.