The combination of PHP and Nginx has become increasingly popular in modern web development, providing a high-performance and stable server environment. This article walks you through the step-by-step process of installing PHP and Nginx on a CentOS system, enabling you to quickly set up a flexible web service.
Before installation, make sure your system is updated to the latest version by running:
<span class="fun">sudo yum update</span>
To install the latest PHP versions easily, add the EPEL and Remi repositories first:
sudo yum install epel-release -y
sudo yum install https://rpms.remirepo.net/enterprise/remi-release-7.rpm -y
Enable the PHP 8.1 repository with the following command. You can also choose other versions as needed:
<span class="fun">sudo yum-config-manager --enable remi-php81</span>
Next, install PHP along with common extensions to cover most project requirements:
<span class="fun">sudo yum install php php-cli php-fpm php-mysqlnd php-xml php-mbstring -y</span>
After installation, edit the PHP-FPM configuration file to ensure the service runs under the nginx user:
<span class="fun">sudo vi /etc/php-fpm.d/www.conf</span>
Change the following lines accordingly:
user = nginx
group = nginx
Install Nginx using yum:
<span class="fun">sudo yum install nginx -y</span>
sudo systemctl start nginx
sudo systemctl enable nginx
Create or edit the Nginx configuration file to enable PHP processing:
<span class="fun">sudo vi /etc/nginx/conf.d/default.conf</span>
Add the following content:
server {
listen 80;
server_name your_domain.com; # Replace with your domain or IP address
root /usr/share/nginx/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
Create a simple PHP test file to verify the setup:
<span class="fun">echo "<?php phpinfo(); ?>" | sudo tee /usr/share/nginx/html/info.php</span>
Visit http://your_domain.com/info.php in your browser. If you see the PHP information page, PHP and Nginx have been successfully installed.
Following these steps, you have successfully installed and configured PHP and Nginx on your CentOS system, providing a solid foundation for web development. Hopefully, this guide helps you quickly master the setup process.