Setting up Nginx with PHP-FPM (PHP FastCGI Process Manager) allows you to serve PHP web applications efficiently. PHP-FPM is a process manager for PHP that handles incoming requests and executes PHP scripts. Here’s a step-by-step guide to set up Nginx with PHP-FPM on Ubuntu:
1. Install Nginx:
If you haven’t already installed Nginx, you can do so by running:
sudo apt update
sudo apt install nginx2. Install PHP and PHP-FPM:
Install PHP and PHP-FPM along with any necessary PHP extensions for your web application:
sudo apt install php-fpm php-mysql php-curl php-gd php-mbstring php-xml php-json php-zipThis command installs PHP-FPM and some common PHP extensions. You can install additional extensions based on your application’s requirements.
3. Configure PHP-FPM:
PHP-FPM comes with a default configuration that should work for most cases. However, you can adjust some settings if needed.
Edit the PHP-FPM configuration file:
sudo nano /etc/php/7.4/fpm/php.iniMake sure to adjust the cgi.fix_pathinfo setting to 0 to enhance security:
cgi.fix_pathinfo=0Save and close the file.
4. Configure Nginx to Use PHP-FPM:
Next, configure Nginx to use PHP-FPM for processing PHP files. Open your Nginx site configuration file:
sudo nano /etc/nginx/sites-available/your-site.confInside the server block, add the following location block to handle PHP files:
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}This configuration tells Nginx to pass PHP requests to the PHP-FPM socket.
5. Test Configuration and Reload Nginx:
Test the Nginx configuration to ensure there are no syntax errors:
sudo nginx -tIf the test is successful, reload Nginx to apply the changes:
sudo systemctl reload nginx6. Start and Enable PHP-FPM:
Start the PHP-FPM service and enable it to start automatically on boot:
sudo systemctl start php7.4-fpm
sudo systemctl enable php7.4-fpm7. Test PHP:
Create a test PHP file in your web document root to ensure that PHP-FPM is working correctly. For example, create a file named info.php:
sudo nano /var/www/html/info.phpAdd the following content to info.php:
php
phpinfo();
?>Save and close the file.
Now, open your web browser and access http://your_domain_or_server_ip/info.php. You should see a PHP information page showing PHP version details and configuration.
8. Secure and Optimize Nginx and PHP-FPM (Optional):
For production use, consider implementing security best practices and optimizing your Nginx and PHP-FPM configurations.
That’s it! You’ve successfully set up Nginx with PHP-FPM on Ubuntu. You can now deploy your PHP web applications on this server configuration.