How to install and configure nginx with PHP_FPM on Ubuntu Server 20.04

We will learn how to install and set up Nginx as a web server. We will also install PHP to be able to serve dynamic content. We need to install PHP_FPM (FastCGI Process Manager), as Nginx doesn’t support the native execution of PHP scripts.

Follow these steps to install Nginx with PHP_FPM:

Step 1 : Update the apt package repository and install Nginx. As of writing this Ubuntu 16.04 repository contains latest stable release of Nginx

sudo apt-get update
    sudo apt-get install nginx -y

Step 2 : Check if Nginx is properly installed and running

sudo service nginx status

Step 3 : Check the installed version of Nginx

nginx -v

Step 4 : You may want to point your browser to the server IP or domain. You should see a default Nginx welcome page:

Step 5 : Next, proceed with installing PHP_FPM 7.4

sudo apt-get install php7.4-fpm

Step 6 : Configure Nginx to use the PHP processor. Nginx sites are listed at /etc/nginx/sites-available. We will modify the default site:

sudo nano /etc/nginx/sites-available/default

Step 7 : Find a line stating the priority of the index file and add index.php as a first option:

index index.php index.html index.htm;

Step 8 : Next, add the following two location directives

location / {
    # First attempt to serve request as file, then
    # as directory, then fall back to displaying a 404.
    # try_files $uri $uri/ =404;
    try_files $uri $uri/ /index.php;

# pass PHP scripts to FastCGI server
location ~ \.php$ {
    include snippets/fastcgi-php.conf;

    # With php-fpm (or other unix sockets):
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param QUERY_STRING    $query_string;
#       # With php-cgi (or other tcp sockets):
#       fastcgi_pass;

Step 9 : Now, restart Nginx for the changes to take effect

sudo service nginx restart

Step 10 : Save the changes and exit the file. It should look similar to this.

Step 11 : Create an index.php file with some PHP code in it at the path mentioned in the default site configuration:

sudo nano /var/www/html/index.php
    <?php phpinfo(); ?>

Step 12 : Open your browser and point it to your server. You should see the result of your PHP script.

Add Comment