Configuring Nginx to work with PHP-FPM enhances performance, resource management, security, and scalability when handling PHP-based web applications. This setup is particularly beneficial for web servers experiencing varying levels of traffic and resource demands.
I. Install Nginx and PHP-FPM:
Make sure Nginx and PHP-FPM are installed on your server. You can install them using your package manager. For example, on Debian/Ubuntu:
sudo apt-get update
sudo apt-get install nginx php-fpm
II. Configure PHP-FPM:
1. Edit the PHP-FPM pool configuration file. The default pool configuration file is often located at /etc/php/8.2/fpm/pool.d/www.conf. Adjust the version number based on your PHP version.
sudo nano /etc/php/8.2/fpm/pool.d/www.conf
2. Configure the PHP-FPM pool to listen on a Unix socket. Find or add the listen directive:
listen = /run/php/php8.2-fpm.sock
Adjust the version number accordingly. Save the file and restart PHP-FPM:
sudo systemctl restart php8.2-fpm
III. Configure Nginx:
1. Open the Nginx server block configuration file for your website. This file is often located at /etc/nginx/sites-available/default. You can create a new file if needed.
sudo nano /etc/nginx/sites-available/default
2. Add or modify the following sections to configure Nginx to work with PHP-FPM:
server {
listen 80;
server_name your_domain.com; # Replace with your actual domain or server IP
root /var/www/html; # Replace with the path to your web root
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.2-fpm.sock; # Adjust the version number
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# Additional Nginx configurations...
}
Make sure to adjust the server_name, root, and fastcgi_pass directives based on your setup.
3. Save the Nginx configuration file and test for syntax errors:
sudo nginx -t
4. If there are no errors, restart Nginx to apply the changes:
sudo systemctl restart nginx
VI. Test the configuration:
1. Create a test PHP file in your web root. For example, create a file named info.php:
<?php
phpinfo();
2. Access the test PHP file in your web browser (e.g., http://your_domain.com/info.php). You should see the PHP information page, indicating that Nginx is correctly passing PHP requests to PHP-FPM.
These steps provide a basic setup for Nginx and PHP-FPM. Depending on your specific requirements and application, you may need to customize the configurations further.