To set up Nginx and PHP-FPM to handle custom error pages for PHP applications, follow these steps:
Install Nginx and PHP-FPM:
On Ubuntu, you can use the following commands to install Nginx and PHP-FPM:
sudo apt update
sudo apt install nginx php-fpm
Configure Nginx to use PHP-FPM:
Open the Nginx configuration file in a text editor. On Ubuntu, the file is located at /etc/nginx/sites-available/default
.
Uncomment the server
block and update the location ~ \.php$
section to include the following lines:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}
Replace php7.4-fpm.sock
with the appropriate PHP-FPM socket version installed on your system.
Configure Nginx to handle custom error pages:
Inside the server
block, add the following lines to configure Nginx to handle custom error pages:
error_page 404 /404.php;
error_page 500 502 503 504 /50x.php;
location = /404.php {
root /path/to/your/php/app;
internal;
}
location = /50x.php {
root /path/to/your/php/app;
internal;
}
Replace /path/to/your/php/app
with the actual path to your PHP application's root directory.
Create the custom error pages:
Inside your PHP application's root directory, create the 404.php
and 50x.php
files with your desired custom error page content.
Restart Nginx and PHP-FPM:
After making the changes, save the Nginx configuration file and restart both Nginx and PHP-FPM using the following commands:
sudo systemctl restart nginx
sudo systemctl restart php7.4-fpm # Replace with the appropriate PHP-FPM version
Now, when a PHP application running on Nginx encounters a 404 error or a 500 series error, Nginx will use the custom error pages you created to handle these errors.