How to use php inside html on caddy?

1. Caddy version (caddy version):

2. How I run Caddy:

caddy run
caddy reload —config Caddyfile

a. System environment:

Ubuntu 20.04

b. Command:

paste command here

c. Service/unit/compose file:

paste full file contents here

d. My complete Caddyfile or JSON config: {
} {
root * /var/www/html
#rewrite * /index.html
php_fastcgi unix//run/php/php7.4-fpm.sock
handle_errors {
	@404 {
		expression {http.error.status_code} == 404
	handle @404 {
		rewrite * /404.html
	@403 {
		expression {http.error.status_code} == 403
	handle @403 {
		rewrite * /403.html

3. The problem I’m having:

I need to be able to use php inside html file, i know it can be done in apache2 but how do i do this in caddy? normal php files works fine.

4. Error messages and/or full log output:

5. What I already tried:

6. Links to relevant resources:

I think you need to use the expanded form of php_fastcgi instead and make the appropriate modifications for it to also handle *.html.

What you’re trying to do is outside the norm of typical PHP apps, so it’s not supported out of the box with the php_fastcgi directive, but you can do it the long way.

1 Like

i don’t understand how to use the expanded form, i mean i just

route {
@phpFiles path *.html

Or it’s more complicated than that? .htaccess was so much easier, im just lost with caddy v2 php inside html

Well, you’re doing something atypical. The php_fastcgi directive was designed for serving modern PHP apps that use index.php for routing. If you’re not doing that, then you need to do things manually.

You’d replace your php_fastcgi line with this:

route {
	# Add trailing slash for directory requests
	@canonicalPath {
		file {path}/index.php
		not path */
	redir @canonicalPath {path}/ 308

	# If the requested file does not exist, try index files
	@indexFiles file {
		try_files {path} {path}/index.php index.php
		split_path .php
	rewrite @indexFiles {http.matchers.file.relative}

	# Proxy PHP files to the FastCGI responder
	@phpFiles path *.php *.html
	reverse_proxy @phpFiles unix//run/php/php7.4-fpm.sock {
		transport fastcgi {
			split .php

But that said, I realized that the split option of php_fastcgi might be all you need to make this work:

php_fastcgi unix//run/php/php7.4-fpm.sock {
	split .php .html

So try that first, and if it doesn’t work, try the expanded form I wrote above.

neither one is working :frowning: i checked index.html also it’s fine i added the code inside <?php ?> tags

actually, i found more easier way, changing the file extension from html to php while having html code and php code mix. it works!


That’s the correct way to do it. :+1:

This topic was automatically closed after 30 days. New replies are no longer allowed.