Nginx and FastCGI: A High-Performance PHP Setup
Running PHP applications with Nginx and FastCGI offers significant performance and scalability advantages over the traditional Apache/mod_php approach. This guide details setting up this high-performance architecture on Ubuntu Server, leveraging the efficiency of FastCGI and the power of Nginx.
FastCGI: A Performance Boost
CGI's inherent overhead of creating a new process for each request is mitigated by FastCGI. FastCGI maintains persistent processes, significantly reducing CPU and time consumption. This leads to improved scalability and overall server efficiency. The image below illustrates a typical CGI process.
Installation and Basic Configuration
Install PHP and Nginx: Use apt to install the necessary packages:
sudo apt-get install php5-cli php5-fpm nginx
Configure Nginx: Avoid directly editing the default Nginx configuration. Instead, create a copy:
cd /etc/nginx sudo rm sites-enabled/default sudo cp sites-available/default sites-available/my-default sudo ln -s /etc/nginx/sites-available/my-default sites-enabled/default
Enable FastCGI: Uncomment the relevant lines in /etc/nginx/sites-available/my-default
to route PHP requests to the FastCGI service (php5-fpm). The crucial section should resemble this:
location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; }
Start Nginx:
sudo service nginx start
Verify Installation: Create info.php
(containing <?php phpinfo(); ?>
) in the web root (/usr/share/nginx/html
). Accessing info.php
in your browser should display PHP information, confirming the integration of Nginx and PHP via FastCGI. The Server API should show "FPM/FastCGI".
Essential Configuration Enhancements
Web Root Permissions: Adjust permissions to avoid constant sudo
usage:
sudo adduser <username> www-data sudo chgrp -R www-data /usr/share/nginx/html sudo chmod -R g+rw /usr/share/nginx/html sudo chmod g+s /usr/share/nginx/html
Handle Non-Existent Scripts: Add a try_files
directive to the Nginx configuration to enhance security:
location ~ \.php$ { try_files $uri $uri/ =404; # ... other FastCGI directives ... }
Migrating from Apache: Use online converters to translate Apache directives (e.g., .htaccess
rules) to Nginx equivalents. Carefully review the converted configuration before implementing it.
Conclusion
This guide provides a robust foundation for setting up a high-performance PHP environment using Nginx and FastCGI. By following these steps and incorporating the recommended security and performance enhancements, you can create a scalable and efficient web server for your PHP applications. Remember to always consult the official documentation for Nginx and PHP for the most up-to-date information and best practices.
The above is the detailed content of Setting Up PHP behind Nginx with FastCGI. For more information, please follow other related articles on the PHP Chinese website!