Enable PHP Using Caddy on AlmaLinux

Configuration

By Jennifer Mathew

Updated on Jan 27, 2024

In this article, we'll explain how to enable PHP using Caddy. We have described steps to configure Caddy to accept PHP. PHP is popular server side language. 
Here we'll install PHP and configure it in Caddyfile.

1. Keep the server updated

Execute following command to update the server:

sudo dnf update -y

2. Install PHP 8.0

The default version of PHP is 7.4 in AlmaLinux, we need to change it to PHP 8.0. Currently, by default AlmaLinux has upto PHP 8.0 version available. If you want to install PHP 8.1, 8.2 or 8.3, you can use third party repository like Remi. In this article, we are using default PHP 8.0 version.

First, check the available version of PHP using following command:

sudo dnf module list php

Next, reset the PHP module.

sudo dnf module reset php

Now, execute following command to enable PHP 8.0 for installation.

sudo dnf module enable php:8.0

Finally, install PHP-FPM using following command:

sudo dnf install php-fpm -y

Note: You can install some common PHP package like *php-mysqlnd php-gd php-cli php-curl php-mbstring php-bcmath php-zip php-opcache php-xml php-json php-intl* as per your requirements.

3. Configure PHP

To work PHP in Caddy, we need to make some changes in PHP-FPM configuration file. First, open a www.conf file.

vi /etc/php-fpm.d/www.conf

Find following variables:

user = apache
group = apache
listen.acl_users = apache,nginx

and replace it by

user = caddy
group = caddy
listen.acl_users = apache,nginx,caddy

Now, execute following command to start and enable PHP-FPM service:

sudo systemctl start php-fpm && sudo systemctl enable php-fpm

Check the status of PHP-FPM for errors.

sudo systemctl status php-fpm

4. Configure Caddy

We need to add PHP sock file path in *Caddyfile*. Edit the Caddyfile.

sudo vi /etc/caddy/Caddyfile

Edit the configuration file to include php_fastcgi directive and set it to PHP-FPM socket as an argument. Like Shown below:

hostnextra.com {
        # Set this path to your site's directory.
        root * /usr/share/hostnextra.com

       # Serve a PHP site through php-fpm
        php_fastcgi unix//run/php-fpm/www.sock

        # Enable the static file server.
        file_server

}

Note: Replace hostnextra.com with your domain name.

Test and reload the Caddy using following command:

caddy validate
caddy reload

5. Create a PHP file

Create a new PHP file test.php in your web files directory

sudo vi /usr/share/hostnextra.com/text.php

Note: Replace hostnextra.com to your domain name.

Add following lines:

<html>
    <head>
        <title>PHP Works</title>
    </head>
    <body>
        <h1>PHP Works! AlmaLinux</h1>  
    </body>
</html>

Save and exit.

Navigate to your browser and access the test.php page.

https://hostnextra.com/test.php

That's it. We have seen how to enable PHP using Caddy on AlmaLinux