Install Nginx and PHP-FPM
Install Nginx and PHP-FPM on Debian or Ubuntu: up-to-date repositories, virtual host, dedicated pool, PHP test, essential settings, HTTPS, updates and troubleshooting.
On this page
Your values
Enter them once and the commands in this guide update.
This guide explains how to install Nginx from the official nginx.org repository and a recent version of PHP-FPM, then publish a site with its own virtual host and its own PHP pool.
Order a Server
To host your websites, HostMyServers offers several options:
Prerequisites
- A server running Debian 12/13 or Ubuntu 22.04/24.04
- SSH access with
rootor asudouser - A domain name whose records point to the server (see create an A record)
- Ports 80 and 443 open over TCP
PHP-FPM communicates with Nginx through a local socket: it does not need any open port. If you use UFW (see Configure UFW):
sudo ufw allow 80,443/tcp comment 'Web'Step 1: install Nginx
If Nginx is already installed from your distribution's packages, back up /etc/nginx then remove it with sudo apt remove nginx nginx-common.
Install the required tools. On Debian:
sudo apt update
sudo apt install curl gnupg2 ca-certificates lsb-release debian-archive-keyringOn Ubuntu:
sudo apt update
sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyringImport the signing key and display its fingerprints:
curl -fsSL https://nginx.org/keys/nginx_signing.key | gpg --dearmor | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg > /dev/null
gpg --show-keys /usr/share/keyrings/nginx-archive-keyring.gpgThe list must contain the fingerprint 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62. If not, delete the file and stop there.
Add the stable branch repository, give it priority, then install Nginx:
. /etc/os-release
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] https://nginx.org/packages/$ID $(lsb_release -cs) nginx" | sudo tee /etc/apt/sources.list.d/nginx.list
printf 'Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n' | sudo tee /etc/apt/preferences.d/99nginx
sudo apt update
sudo apt install nginx
sudo systemctl enable --now nginx
nginx -vStep 2: install PHP-FPM
The PHP project does not publish an APT repository. To get a recent version on all these systems, this guide uses the packages.sury.org repository, maintained by Ondřej Surý, who is also a maintainer of Debian's PHP packages. It is a third-party repository: only add it if you trust it.
sudo apt install lsb-release ca-certificates curl
curl -fsSLo /tmp/debsuryorg-archive-keyring.deb https://packages.sury.org/debsuryorg-archive-keyring.deb
sudo dpkg -i /tmp/debsuryorg-archive-keyring.deb
echo "deb [signed-by=/usr/share/keyrings/debsuryorg-archive-keyring.gpg] https://packages.sury.org/php/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/php.list
sudo apt updateInstall PHP 8.5 with the most common extensions:
sudo apt install php8.5-fpm php8.5-cli php8.5-curl php8.5-mbstring php8.5-xml php8.5-zip php8.5-intl php8.5-gd php8.5-mysql
php -v
sudo systemctl status php8.5-fpmBe sure to install php8.5-fpm and not the generic php package, which may add Apache.
Step 3: create the site
Here, each site has its own system user. PHP can read the code but can only write to uploads:
sudo useradd --system --user-group --home-dir /var/www/your-domain.com --shell /usr/sbin/nologin webapp
sudo mkdir -p /var/www/your-domain.com/public/uploads
sudo chown -R "$USER":webapp /var/www/your-domain.com
sudo find /var/www/your-domain.com -type d -exec chmod 755 {} +
sudo chown webapp:webapp /var/www/your-domain.com/public/uploadsCreate a test page:
nano /var/www/your-domain.com/public/index.php<?php
header('Content-Type: text/plain; charset=utf-8');
echo 'PHP ', PHP_VERSION, ' (', PHP_SAPI, ')', PHP_EOL;
echo 'User: ', posix_getpwuid(posix_geteuid())['name'], PHP_EOL;
echo 'OPcache: ', (function_exists('opcache_get_status') && opcache_get_status(false)) ? 'on' : 'off', PHP_EOL;Step 4: create the PHP-FPM pool
sudo nano /etc/php/8.5/fpm/pool.d/your-domain.com.conf[your-domain.com]
user = webapp
group = webapp
listen = /run/php/your-domain.com.sock
listen.owner = nginx
listen.group = nginx
listen.mode = 0660
pm = dynamic
pm.max_children = 10
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
pm.max_requests = 500
request_terminate_timeout = 120s
catch_workers_output = yes
php_admin_flag[log_errors] = onDisable the default pool, which is no longer used:
sudo mv /etc/php/8.5/fpm/pool.d/www.conf /etc/php/8.5/fpm/pool.d/www.conf.disabledStep 5: tune PHP
Put your settings in a separate file, which updates will not touch:
sudo nano /etc/php/8.5/fpm/conf.d/90-custom.inimemory_limit = 256M
upload_max_filesize = 32M
post_max_size = 32M
max_execution_time = 60
date.timezone = Europe/Paris
expose_php = Off
display_errors = Off
log_errors = On
session.use_strict_mode = 1
session.cookie_httponly = 1
opcache.enable = 1
opcache.memory_consumption = 128
opcache.max_accelerated_files = 10000
opcache.validate_timestamps = 1
opcache.revalidate_freq = 2Test, then restart PHP-FPM:
sudo php-fpm8.5 -t
sudo systemctl restart php8.5-fpm
ls -l /run/php/The your-domain.com.sock socket must belong to nginx:nginx.
Step 6: configure Nginx
Disable the sample configuration, then create the general settings:
sudo mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf.disabled
sudo nano /etc/nginx/conf.d/00-defaults.confserver_tokens off;
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/javascript application/json application/xml image/svg+xml;
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 444;
}
server {
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
server_name _;
ssl_reject_handshake on;
}These two blocks close the connection when a request matches none of your domains. Then create the virtual host:
sudo nano /etc/nginx/conf.d/your-domain.com.confserver {
listen 80;
listen [::]:80;
server_name your-domain.com www.your-domain.com;
root /var/www/your-domain.com/public;
index index.php index.html;
access_log /var/log/nginx/your-domain.com.access.log;
error_log /var/log/nginx/your-domain.com.error.log;
client_max_body_size 32m;
location ~ /\.(?!well-known) {
deny all;
}
location ^~ /uploads/ {
location ~ \.php$ {
deny all;
}
}
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/run/php/your-domain.com.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
}
}This configuration denies access to hidden files such as .env and blocks PHP execution in uploads. Test and reload:
sudo nginx -t
sudo systemctl reload nginxStep 7: check the site
From the server:
curl -i -H 'Host: your-domain.com' http://127.0.0.1/The response must be 200 OK, with the PHP version, the webapp user and OPcache: on. Also check the protections:
echo 'test' > /var/www/your-domain.com/public/.test
curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: your-domain.com' http://127.0.0.1/.test
rm /var/www/your-domain.com/public/.testThe expected code is 403. Then open http://your-domain.com in your browser. A direct request to the IP address gets no response: this is the intended effect of the default block.
Step 8: enable HTTPS
Follow the guide Install an SSL certificate with Let's Encrypt, Nginx section. Skip its part on sites-available: your file is /etc/nginx/conf.d/your-domain.com.conf. The main command is:
sudo certbot --nginx -d your-domain.com -d www.your-domain.comOnce the certificate is installed, enable HTTP/2 by adding this line in the server block that contains listen 443 ssl:
http2 on;Also add this line to /etc/php/8.5/fpm/conf.d/90-custom.ini to restrict session cookies to HTTPS:
session.cookie_secure = 1Apply, then check:
sudo nginx -t
sudo systemctl reload nginx
sudo systemctl restart php8.5-fpm
curl -I https://your-domain.com
sudo certbot renew --dry-runOnce your tests are done, replace the test page with your application.
Sizing PHP-FPM
pm.max_children limits the number of PHP requests processed at the same time. A value that is too high can exhaust memory. Measure the average consumption, preferably under real load:
ps --no-headers -o rss -C php-fpm8.5 | awk '{s+=$1; n++} END {printf "%.0f Mo\n", s/n/1024}'
free -mThen calculate: memory available for PHP ÷ average consumption of one process. For example, 1,024 MB ÷ 60 MB gives about 17 processes. Keep a margin for the system and the database, then reload with sudo systemctl reload php8.5-fpm.
Updates
sudo apt update
sudo apt upgrade
sudo nginx -t
sudo systemctl status nginx php8.5-fpmTo move to a new PHP branch, install its packages, copy your pool and 90-custom.ini to the new version's folder, stop the old service, then start the new one. Since the socket keeps the same name, the virtual host does not change. Test your application beforehand.
Backup
Back up the site and its configuration, then copy the archive off the server:
sudo tar czf site-backup.tar.gz /var/www/your-domain.com /etc/nginx /etc/php/8.5/fpm /etc/letsencrypt
sudo chmod 600 site-backup.tar.gzThe archive contains your certificates' private keys. If the site uses a database, back it up separately, for example with mariadb-dump (see Install and secure MariaDB).
Troubleshooting
The useful logs are /var/log/nginx/your-domain.com.error.log and /var/log/php8.5-fpm.log.
502 Bad Gateway with connect() ... failed (13: Permission denied)
Nginx does not have access to the socket. Check listen.owner and listen.group in the pool, then restart PHP-FPM.
502 Bad Gateway with connect() ... failed (2: No such file or directory)
PHP-FPM is stopped, or the socket path differs between the pool and fastcgi_pass. Check sudo systemctl status php8.5-fpm and sudo php-fpm8.5 -t.
File not found. or Primary script unknown
The file does not exist at the location given by root, or the webapp user cannot read it. Check the path and permissions with namei -l /var/www/your-domain.com/public/index.php.
The browser downloads the PHP file
The location ~ \.php$ block is not being applied. Check that the domain matches server_name, then reload Nginx.
413 Request Entity Too Large
Increase client_max_body_size in Nginx as well as upload_max_filesize and post_max_size in PHP, with consistent values.
504 Gateway Timeout
The script exceeds Nginx's timeout. Optimize it if possible, or adjust fastcgi_read_timeout, max_execution_time and request_terminate_timeout together.
server reached pm.max_children setting
All the pool's slots are busy. First look for slow requests, then increase pm.max_children if memory allows.
bind() to 0.0.0.0:80 failed (98: Address already in use)
Another service, often Apache, is using the port. Identify it with sudo ss -ltnp | grep ':80 '.
curl: (52) Empty reply from server
The request matches no server_name and the default block closed the connection. Check the Host header and the configured domain.