basforge

Search titles, text and the “If it doesn’t work” cases.

    RU
    ConfigHomelabnginx

    nginx and PHP-FPM: WordPress, Laravel, socket permissions, and fastcgi_cache

    Line-by-line configs for WordPress and Laravel: connecting to the PHP-FPM Unix socket, resolving the nginx vs www-data permission mismatch, blocking .php execution in upload directories, syncing limits with php.ini, and caching pages in fastcgi_cache.

    Installing PHP-FPM and fixing Unix socket permissions

    Install php8.3-fpm explicitly (on Ubuntu 26.04 the default package is php8.5-fpm), not the bare php metapackage: php pulls in apache2 and libapache2-mod-php, which grab port 80 (Web servers since 2008).

    Right after installing php8.3-fpm alongside the official nginx.org package, socket permissions clash:

    ls -la /run/php/php8.3-fpm.sock
    # srw-rw---- 1 www-data www-data 0 Nov 25 17:16 /run/php/php8.3-fpm.sock

    The socket grants read/write access only to owner www-data and group www-data (0660), while official nginx.org workers run as user nginx. The first .php request returns 502 Bad Gateway with (13: Permission denied).

    Grant the nginx worker user access via the www-data group:

    sudo usermod -aG www-data nginx
    sudo systemctl restart nginx

    Use a one-time restart, not reload: Linux assigns supplementary groups at process start. Both nginx and php8.3-fpm then share the socket without modifying system PHP configs (an alternative is setting listen.group = nginx in /etc/php/8.3/fpm/pool.d/www.conf).

    When PHP-FPM runs in a separate Docker container, use TCP (fastcgi_pass php:9000;) instead of unix:/run/php/… — Unix socket permissions don’t apply there.

    Scenario 1: WordPress with upload protection and fastcgi_cache

    This config handles WordPress pretty permalinks, blocks execution of .php files dropped into the media library, and adds a disk fastcgi_cache: repeat anonymous page views return in sub-millisecond time without touching PHP or the database.

    Create the cache directory first: sudo mkdir -p /var/cache/nginx/fastcgi && sudo chown nginx:www-data /var/cache/nginx/fastcgi.

    /etc/nginx/conf.d/wp.example.org.conf
    fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2
                       keys_zone=WP_CACHE:10m inactive=60m max_size=256m;
    fastcgi_cache_key "$scheme$request_method$host$request_uri";
    Key part

    Lives in the http context (outside server). Defines the disk cache directory, levels=1:2 subdirectory layout, WP_CACHE:10m in-memory key zone (~80,000 keys), 60m idle eviction, and a 256m disk cap. The cache key combines scheme, method, host, and URI.

    server {
        listen 80;
        server_name wp.example.org;
        root /var/www/wp.example.org;
        index index.php index.html;
        client_max_body_size 32m;

    Document root and request body limit (raise alongside php.ini, see table below). For HTTPS on port 443, add the TLS directives from HTTPS & HTTP/3.

        set $skip_cache 0;
        if ($request_method = POST) { set $skip_cache 1; }
        if ($query_string != "") { set $skip_cache 1; }
        if ($request_uri ~* "/wp-admin/|/wp-login\.php") { set $skip_cache 1; }
        if ($http_cookie ~* "wordpress_logged_in_|comment_author") { set $skip_cache 1; }

    Cache bypass rules: POST forms, query strings (?…), /wp-admin/, and logged-in users carrying wordpress_logged_in_ cookies always hit live PHP. At the server level (outside location), if is safe.

        location ~* /(?:uploads|files)/.*\.php$ {
            deny all;
        }
    
        location ~ /\.(?!well-known) {
            deny all;
        }
    Key part

    Blocks any .php execution inside upload directories — even if an attacker uploads a script through a vulnerable plugin, nginx responds 403. This block must sit **above** location ~ \.php$.

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

    WordPress pretty permalinks: serve a static file or directory if it exists, otherwise route through /index.php with the original ?$args.

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

    PHP handler. try_files $uri =404; keeps missing .php paths out of PHP-FPM (preventing File not found. errors and PATH_INFO attacks). include fastcgi_params; loads standard parameters from the nginx.org package, and SCRIPT_FILENAME gives PHP the exact script path. On Ubuntu 26.04, set the socket to unix:/run/php/php8.5-fpm.sock.

            fastcgi_cache WP_CACHE;
            fastcgi_cache_valid 200 10m;
            fastcgi_cache_bypass $skip_cache;
            fastcgi_no_cache $skip_cache;
            add_header X-FastCGI-Cache $upstream_cache_status always;
        }
    }

    Cache 200 responses for 10 minutes, bypass on $skip_cache = 1, and expose cache status (MISS, HIT, BYPASS) in X-FastCGI-Cache for verification.

    Scenario 2: Laravel and modern PHP frameworks

    Laravel and Symfony keep application code, .env, and vendor/ one level above the web root — expose only the public/ directory.

    /etc/nginx/conf.d/laravel.example.org.conf
    server {
        listen 80;
        server_name laravel.example.org;
        root /var/www/laravel.example.org/public;
        index index.php;
    
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
    Key part

    Point root strictly at public/: .env, composer.json, and source files above public/ remain unreachable over HTTP.

        location ~ \.php$ {
            try_files $uri =404;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
            fastcgi_pass unix:/run/php/php8.3-fpm.sock;
        }
    
        location ~ /\.(?!well-known) {
            deny all;
        }
    }
    Key part

    Use $realpath_root instead of $document_root in SCRIPT_FILENAME: during zero-downtime deployments that flip a current symlink to releases/<version>, PHP OPcache receives the resolved release directory and won’t serve stale bytecode.

    Upload limits and PHP-FPM pool: settings to change alongside nginx

    Raising the limit in nginx alone isn’t enough — uploads pass through three limits across two services:

    Parameter File Default Controls
    client_max_body_size nginx site config 1m Max HTTP request body size
    upload_max_filesize /etc/php/8.3/fpm/php.ini 2M Max size of a single uploaded file
    post_max_size /etc/php/8.3/fpm/php.ini 8M Max total POST body size (set slightly above upload_max_filesize)
    pm.max_children /etc/php/8.3/fpm/pool.d/www.conf 5 Max concurrent PHP worker processes in the pool

    After editing php.ini or www.conf, reload PHP-FPM: sudo systemctl reload php8.3-fpm.

    How to check

    1. Validate syntax and apply:
      sudo nginx -t && sudo systemctl reload nginx
    2. Check fastcgi_cache: the first request returns MISS, the second returns HIT (served from cache without invoking PHP), and a request carrying a login cookie returns BYPASS:
      curl -sI -H "Host: wp.example.org" http://127.0.0.1/hello | grep -iE '^(HTTP/|x-fastcgi-cache)'
      # HTTP/1.1 200 OK
      # X-FastCGI-Cache: MISS
      curl -sI -H "Host: wp.example.org" http://127.0.0.1/hello | grep -iE '^(HTTP/|x-fastcgi-cache)'
      # HTTP/1.1 200 OK
      # X-FastCGI-Cache: HIT
      curl -sI -H "Host: wp.example.org" -H "Cookie: wordpress_logged_in_1=abc" http://127.0.0.1/hello \
        | grep -iE '^(HTTP/|x-fastcgi-cache)'
      # HTTP/1.1 200 OK
      # X-FastCGI-Cache: BYPASS
    3. Verify upload blocking and missing .php handling:
      curl -s -o /dev/null -w "uploads-php:%{http_code}\n" -H "Host: wp.example.org" \
        http://127.0.0.1/wp-content/uploads/shell.php
      # uploads-php:403
      curl -s -o /dev/null -w "missing-php:%{http_code}\n" -H "Host: wp.example.org" \
        http://127.0.0.1/nonexistent.php
      # missing-php:404

    If it doesn’t work

    502 Bad Gateway on every PHP page, and /var/log/nginx/error.log logs connect() to unix:/run/php/php8.3-fpm.sock failed (13: Permission denied)

    Cause
    nginx from the official nginx.org repo runs as user nginx, while Ubuntu’s PHP-FPM creates its socket owned by www-data:www-data with mode 0660.
    Fix
    Add the nginx user to the www-data group and restart the service once (a plain reload won’t pick up new supplementary groups): sudo usermod -aG www-data nginx && sudo systemctl restart nginx.

    502 Bad Gateway, and error.log logs connect() to unix:/run/php/php8.3-fpm.sock failed (2: No such file or directory)

    Cause
    PHP-FPM is stopped, or the host runs a different PHP version (on Ubuntu 26.04 the socket is php8.5-fpm.sock).
    Fix
    Check the socket path with ls -la /run/php/ and inspect the service status with systemctl status php8.3-fpm.

    Files larger than 2 MB fail to upload in WordPress or an admin panel even with client_max_body_size 32m; in nginx

    Cause
    /etc/php/8.3/fpm/php.ini enforces its own defaults: upload_max_filesize = 2M and post_max_size = 8M.
    Fix
    Raise both settings in php.ini (for example upload_max_filesize = 32M, post_max_size = 36M) and reload the pool: sudo systemctl reload php8.3-fpm.

    A PHP file inside /wp-content/uploads/ still executes despite a deny all block

    Cause
    The regex location ~* /(?:uploads|files)/.*\.php$ sits below location ~ \.php$: nginx evaluates regex locations top to bottom and stops at the first match.
    Fix
    Move the blocking location above location ~ \.php$ and run sudo nginx -t && sudo systemctl reload nginx.

    Six or more concurrent PHP requests slow the site down sharply while CPU sits idle

    Cause
    /etc/php/8.3/fpm/pool.d/www.conf defaults to pm.max_children = 5, queuing the sixth concurrent request.
    Fix
    Measure average memory per PHP worker, raise pm.max_children (leaving headroom for the OS and database), and restart php8.3-fpm.