DEV3 Technologies home

DEV3 Developer Forum

How do I set up an Nginx server block with PHP-FPM for a PHP site?

DevOps helpSolved0 views
dev3 ·

I installed Nginx and PHP 8.3 on Ubuntu. Visiting my domain shows the default Nginx page, and .php files download instead of running. What is a correct server block?

#nginx#php-fpm#server-block

0

1 reply

dev3 · Accepted answer

Nginx does not run PHP itself; it passes .php requests to PHP-FPM through a socket. Downloads of PHP source mean no location ~ \.php$ block is active (or the wrong server block matched).

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;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }

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

Steps on Debian/Ubuntu

  1. Save it as /etc/nginx/sites-available/example.com.
  2. Enable: sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/.
  3. Remove the default site if it conflicts: sudo rm /etc/nginx/sites-enabled/default.
  4. Test and reload: sudo nginx -t && sudo systemctl reload nginx.

Check PHP-FPM: systemctl status php8.3-fpm, and confirm the socket path with ls /run/php/. A mismatched version in the path is the commonest mistake.

Notes

  • root should point at the public folder (for Laravel, public), never the project root.
  • try_files in the PHP location prevents arbitrary file execution on some old setups; the fastcgi-php.conf snippet includes it.
  • File ownership: the www-data user must read the files and write only where needed (storage, uploads).
  • Server name matching: requests to an IP or unknown host fall to the first (default) server block.

You can generate a starting config with the Nginx config generator.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.