Introduction

Nginx is a powerful web server and reverse proxy server. PHP-FPM (PHP FastCGI Process Manager) is a PHP FastCGI implementation that allows PHP to run as a service.

This guide will walk you through the process of installing and configuring Nginx with PHP-FPM on CentOS 8.

Prerequisites

Before you begin, ensure you have:

  1. A CentOS 8 server with root or sudo access

Step 1: Install Nginx and PHP-FPM

Update the package index and install Nginx and PHP-FPM:

sudo dnf install nginx php-fpm

Step 2: Configure PHP-FPM

Edit the PHP-FPM configuration file:

sudo nano /etc/php-fpm.d/www.conf

Find the listen directive and set it to a Unix socket:

listen = /run/php-fpm/www.sock

Save and close the file, then restart PHP-FPM:

sudo systemctl restart php-fpm

Step 3: Configure Nginx

Edit the Nginx default configuration file:

sudo nano /etc/nginx/nginx.conf

Add the following configuration inside the http block:

server {
    listen       80;
    server_name  example.com;

    root   /usr/share/nginx/html;
    index  index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/run/php-fpm/www.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Replace example.com with your domain name.

Save and close the file, then test the Nginx configuration:

sudo nginx -t

If the test is successful, restart Nginx:

sudo systemctl restart nginx

Step 4: Test PHP

Create a PHP test file:

sudo nano /usr/share/nginx/html/info.php

Add the following PHP code to the file:

<?php
phpinfo();
?>

Save and close the file, then access the PHP test file in a web browser:

http://example.com/info.php

You should see the PHP information page.

Conclusion

Congratulations! You have successfully installed and configured Nginx with PHP-FPM on CentOS 8. You can now host PHP websites and applications using Nginx.

Was this answer helpful? 0 Users Found This Useful (0 Votes)