Add .html extension if missing

1. Output of caddy version:

v2.6.2 h1:wKoFIxpmOJLGl3QXoo6PNbYvGW4xLEgo32GPBEjWL8o=

2. How I run Caddy:

I run Caddy using Google Cloud Run to serve my Docker image which uses the official Caddy Docker image as its parent image.

a. System environment:

Google Cloud Run.

b. Command:


c. Service/unit/compose file:

FROM caddy

COPY website/Caddyfile /etc/caddy/Caddyfile
COPY website/public /srv

d. My complete Caddy config:

	auto_https off

:{$PORT} {
	root * /srv
	encode gzip

	handle_errors {
		rewrite * /{err.status_code}.html

	header / {
		Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
		X-XSS-Protection "1; mode=block"
		X-Frame-Options "DENY"
		X-Content-Type-Options "nosniff"
		Referrer-Policy "strict-origin-when-cross-origin"
		Permissions-Policy "fullscreen=(self)"
		cache-control "max-age=0,no-cache,no-store,must-revalidate"

	@static {
		path_regexp \.(ico|css|js|gif|jpg|jpeg|png|svg|woff)$

	header @static Cache-Control max-age=604800

	@plausible path /js/script.js /api/event
	handle @plausible {
		rewrite /js/script.js /js/script.js
		reverse_proxy {
			header_up Host {http.reverse_proxy.upstream.hostport}

3. The problem I’m having:

How do I rewrite the request URL so that a .html extension is added if not already present?

4. Error messages and/or full log output:


5. What I already tried:

6. Links to relevant resources:

Maybe something like this?

@missingHTML not path *.html
rewrite @missingHTML {path}.html
1 Like

Alternatively with try_files, which will check if the file exists on disk before trying to rewrite:

try_files {path}.html

Two things:

  • using header / will only match requests to only exactly / and nothing else, so all other requests will not have these header operations applied to them.
  • deleting the Server header has no benefit.

You can shorten this slightly:

	@static path_regexp \.(ico|css|js|gif|jpg|jpeg|png|svg|woff)$
	header @static Cache-Control max-age=604800

This rewrite isn’t doing anything; it’s tautological. If the path is already /js/script.js then rewriting to /js/script.js does nothing at all. You can just remove this line.

You can shorten this to header_up Host {upstream_hostport}

1 Like

Thanks for the solution and for pointing out improvements to the rest of my Caddyfile!

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