Building static site from PHP in Cloudflare Pages

I have a static HTML site that I want to deploy through Cloudflare Pages.

I heard we can run PHP during build time in Cloudflare Pages and I don’t want to edit the headers/footers of all pages one by one so I made headers.php and footers.php and included them in index.php as below:

<?php include 'header.php'; . Other codes here . include 'footer.php'; ?>

It is working well on my local server. But while I try to deploy it to Cloudflare pages - it isn’t working.

I have been googling for many hours but I didn’t find how to do it. Please tell me how I can deploy a static site like this.

Thank you.

You can use PHP to build a static site, but if your site would execute a .php script.

1 Like

It is downloading PHP file when I enter ‘domain.tld/index.php’ and says not found when I enter ‘domain.tld’

You can’t run PHP on the server. You would need to render the output to index.html rather than .php.

1 Like

Can you please tell me how can I render the output to index.html? My index.php is as follows. I have HTML codes inside header.php, body-index.php and footer.php

include 'header.php';
include 'body-index.php';
include 'footer.php';

I’m not really sure what the best way to do that in PHP would be, and if you don’t know, you probably should start with a static site generator that’s already written for you. The ones that are supported out of the box on Pages are listed here.

If you want to do the PHP yourself you would probably have to write a script to do it file-by-file and put the output into the build folder. This doesn’t sound fun, but there’s nothing Cloudflare-special about it so whatever you find about generating static HTML files from PHP should work.

Ok, thanks. I might as well use WInHTTRACK to generate copy I guess.

I wrote this bash script to do what you want to achieve, if you or anyone finding this later still wants to use PHP as their templating engine for static site generation. It assumes you have your running PHP site in the /public folder, and will use the /release folder for generated output.

Paste the script below into a file in the root of your project, like (you might have to run chmod +x on that file after creating). Test it, and if it works, you can deploy.

To deploy, when configuring your Cloudflare Pages project, indicate that the build command is ./ and that the build output directory is /release.

Here’s the script I use:


rm -rf release
cp -r public/ release/
find release -type f -name '*.php' -delete

find public -type f -name '*.php' | while read file; do
  release_file=$(echo "$file" | sed -e 's/public/release/' -e 's/\.php$/.html/')
  mkdir -p "$(dirname "$release_file")" && \
  (cd "$(dirname "$file")" && php -f "$(basename "$file")" > "$currentdir/$(dirname "$release_file")/$(basename "$release_file")")