Nginx + PHP-FPM Setup Guide

A practical Linux setup for serving PHP applications with Nginx and PHP-FPM.

Back to Guides ยท Home

What this guide covers: package installation, PHP-FPM socket setup, Nginx server block config, and common 502 fixes.

Scope: Ubuntu/Debian and Rocky/Alma/CentOS style systems.

1. Install Nginx and PHP-FPM (Ubuntu / Debian)

sudo apt update
sudo apt install -y nginx php-fpm php-mysql

sudo systemctl enable --now nginx
sudo systemctl enable --now php8.2-fpm

sudo systemctl status nginx --no-pager
sudo systemctl status php8.2-fpm --no-pager

If your PHP version differs, replace php8.2-fpm with the installed version (for example php8.1-fpm).

2. Install Nginx and PHP-FPM (Rocky / AlmaLinux / CentOS)

sudo dnf install -y nginx php php-fpm php-mysqlnd

sudo systemctl enable --now nginx
sudo systemctl enable --now php-fpm

sudo systemctl status nginx --no-pager
sudo systemctl status php-fpm --no-pager

3. Configure PHP-FPM Pool

# Ubuntu pool file (version may vary):
# /etc/php/8.2/fpm/pool.d/www.conf

# Rocky pool file:
# /etc/php-fpm.d/www.conf

# Ensure PHP-FPM user/group match Nginx worker user where needed.
# Common users: www-data (Ubuntu), nginx (Rocky)

# Restart PHP-FPM after edits
sudo systemctl restart php8.2-fpm
# or
sudo systemctl restart php-fpm

4. Nginx Server Block for PHP

Use a minimal but safe baseline:

server {
    listen 80;
    server_name example.com;

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

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

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

        # Option A: Unix socket (Ubuntu typical)
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;

        # Option B: PHP-FPM TCP (common on Rocky)
        # fastcgi_pass 127.0.0.1:9000;
    }

    location ~ /\.ht {
        deny all;
    }
}
# Test and reload Nginx
sudo nginx -t
sudo systemctl reload nginx

5. Create and Test a PHP Page

sudo mkdir -p /var/www/example/public
echo '/dev/null

# Open in browser: http://example.com
# Remove phpinfo page after validation in production.

6. Security Baseline

  1. Set proper ownership and permissions on app files.
  2. Do not expose unnecessary write permissions to web user.
  3. Disable sensitive PHP functions only if your app supports it.
  4. Use HTTPS and secure headers once the site is online.

7. Common Troubleshooting

Issue Typical Cause Fix
502 Bad Gateway Wrong fastcgi_pass socket/port or PHP-FPM not running Check FPM status and verify socket path from pool config
Download prompt for .php file PHP location block missing or incorrect Add location ~ \.php$ section and reload Nginx
Permission denied App files owned by wrong user/group Correct ownership and directory permissions