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:
Other codes here
It is working well on my local server. But while I try to deploy it to Cloudflare pages - it isn’t working.
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.
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 build.sh (you might have to run chmod +x build.sh 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 ./build.sh 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")")