In this article, we'll explain how to enable PHP using Caddy on Ubuntu. We have described steps to install and configure 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 apt update
2. Install PHP 8.1
The default version of PHP is 8.1 in install and configure. Currently, by default Ubuntu has upto PHP 8.1 version available. If you want to install PHP 8.2 or 8.3, you can use third party repository like Remi. In this article, we are using default PHP 8.1 version.
Execute following command to install PHP-FPM:
sudo apt install php8.1-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.
sudo nano /etc/php/8.1/fpm/pool.d/www.conf
Find following variables and uncomment listen.acl_users:
user = apache
group = apache
;listen.acl_users =
and replace it by
user = caddy
group = caddy
listen.acl_users = caddy
Now, execute following command to start and enable PHP-FPM service:
sudo systemctl start php8.1-fpm && sudo systemctl enable php8.1-fpm
Check the status of PHP-FPM for errors.
sudo systemctl status php8.1-fpm
4. Configure Caddy
We need to add PHP sock file path in Caddyfile. Edit the Caddyfile.
sudo nano /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 * /var/www/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 nano /var/www/hostnextra.com/text.php
Note: Replace hostnextra.com to your domain name.
Add following lines:
<html>
<head>
<title>PHP Works</title>
</head>
<body>
<?php
echo "<h1> Hello World! </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 Ubuntu