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 server-side programming. Here's a basic guide on how to set up Nginx with PHP using PHP-FPM (FastCGI Process Manager):
Prerequisites
1、Nginx installed on your server.
2、PHP installed on your server.
3、PHP-FPM installed on your server.
Step-by-Step Guide
1. Install Nginx and PHP-FPM
If you haven't already installed Nginx and PHP-FPM, you can do so using the package manager of your operating system. For example, on a Debian-based system like Ubuntu:
sudo apt update sudo apt install nginx php-fpm
On a CentOS/RHEL-based system:
sudo yum install epel-release sudo yum install nginx php-fpm
2. Configure PHP-FPM
Edit the PHP-FPM 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 = www-data group = www-data listen = /run/php/php7.4-fpm.sock listen.owner = www-data listen.group = www-data pm = dynamic pm.max_children = 5 pm.start_servers = 2 pm.min_spare_servers = 1 pm.max_spare_servers = 3 chdir = /
Restart PHP-FPM to apply changes:
sudo systemctl restart php7.4-fpm
3. Configure Nginx
Edit the Nginx server block configuration file, usually located at/etc/nginx/sites-available/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/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.4-fpm.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 PHP-FPM.
Troubleshooting Tips
Ensure both Nginx and PHP-FPM services are running:
sudo systemctl status nginx sudo systemctl status php7.4-fpm
Check Nginx error logs for any issues:
sudo tail -f /var/log/nginx/error.log
Check PHP-FPM error logs for any issues:
sudo tail -f /var/log/php7.4-fpm.log
By following these steps, you should have a working setup of Nginx serving PHP content via PHP-FPM.