How to Fix Caddy PHP-FPM Configuration Error
In this tutorial, you'll learn about How to Fix Caddy PHP. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Caddy returns 502 Bad Gateway or serves PHP files as downloads instead of executing them — the php_fastcgi directive is not configured or PHP-FPM is not running.
The Problem
$ curl http://localhost/index.php
# Returns the raw PHP source code instead of executing it
Step-by-Step Fix
Step 1: Verify PHP-FPM is running
sudo systemctl status php8.2-fpm
Step 2: Configure PHP-FPM in Caddyfile
example.com {
root * /var/www/html
php_fastcgi unix//run/php/php8.2-fpm.sock
file_server
}
Step 3: Use TCP socket for PHP-FPM
example.com {
root * /var/www/html
php_fastcgi localhost:9000
file_server
}
Step 4: Pass environment variables
example.com {
root * /var/www/html
php_fastcgi unix//run/php/php8.2-fpm.sock {
env APP_ENV production
env APP_DEBUG false
}
file_server
}
Step 5: Set index file
example.com {
root * /var/www/html
# Specify index file for PHP
try_files {path} {path}/ /index.php
php_fastcgi unix//run/php/php8.2-fpm.sock
file_server
}
Step 6: Add error handling
example.com {
root * /var/www/html
php_fastcgi unix//run/php/php8.2-fpm.sock
file_server
handle_errors {
rewrite * /{err.status_code}.html
file_server
}
}
Prevention Tips
- Match the PHP-FPM socket path to your installed PHP version
- Use Unix sockets for better performance (avoid TCP on the same host)
- Set
APP_ENVand required environment variables viaenvdirective - Monitor PHP-FPM status page for pool health
Common Mistakes with php fpm
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world CADDY code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro