Nginx and PHP are often used together to serve dynamic web content. Nginx is known for its high performance and efficiency in handling static content, while PHP is a popular scripting language for serverside programming. Here's a basic guide on how to set up Nginx with PHP using PHPFPM (FastCGI Process Manager):
Prerequisites
1、Nginx installed on your server.
2、PHP installed on your server.
3、PHPFPM installed on your server.
StepbyStep Guide
1. Install Nginx and PHPFPM
If you haven't already installed Nginx and PHPFPM, you can do so using the package manager of your operating system. For example, on a Debianbased system like Ubuntu:
sudo apt update sudo apt install nginx phpfpm
On a CentOS/RHELbased system:
sudo yum install epelrelease sudo yum install nginx phpfpm
2. Configure PHPFPM
Edit the PHPFPM pool configuration file, usually located at/etc/php/7.4/fpm/pool.d/www.conf
or similar, depending on your PHP version. Make sure it looks something like this:
[www] user = wwwdata group = wwwdata listen = /run/php/php7.4fpm.sock listen.owner = wwwdata listen.group = wwwdata pm = dynamic pm.max_children = 5 pm.start_servers = 2 pm.min_spare_servers = 1 pm.max_spare_servers = 3 chdir = /
Restart PHPFPM to apply changes:
sudo systemctl restart php7.4fpm
3. Configure Nginx
Edit the Nginx server block configuration file, usually located at/etc/nginx/sitesavailable/default
or/etc/nginx/conf.d/default.conf
. Add the following configuration to handle PHP files:
server { listen 80; server_name your_domain_or_IP; root /var/www/html; index index.php index.html index.htm; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgiphp.conf; fastcgi_pass unix:/run/php/php7.4fpm.sock; } location ~ /\.ht { deny all; } }
Make sure to replaceyour_domain_or_IP
with your actual domain name or IP address.
4. Test PHP Processing
Create a simple PHP file to test if PHP is working correctly with Nginx. Create a file namedinfo.php
in the document root directory (e.g.,/var/www/html
) with the following content:
<?php phpinfo(); ?>
5. Restart Nginx
After making these changes, restart Nginx to apply them:
sudo systemctl restart nginx
6. Access Your PHP File
Open a web browser and navigate tohttp://your_domain_or_IP/info.php
. You should see the PHP information page, confirming that PHP is being processed by Nginx through PHPFPM.
Troubleshooting Tips
Ensure both Nginx and PHPFPM services are running:
sudo systemctl status nginx sudo systemctl status php7.4fpm
Check Nginx error logs for any issues:
sudo tail f /var/log/nginx/error.log
Check PHPFPM error logs for any issues:
sudo tail f /var/log/php7.4fpm.log
By following these steps, you should have a working setup of Nginx serving PHP content via PHPFPM.