Rewrite response to remove .html from appearing in the address bar

1. The problem I’m having:

I am trying to configure a very simple static server scenario to remove the .HTML extension from appearing in the browser address bar. E.g. my source files that are being served all end in .HTML but I want a clean url presented to the end user

2. Error messages and/or full log output:

None at this time

3. Caddy version: v2.6.4 h1:2hwYqiRwk1tf3VruhMpLcYTg+11fCdr8S3jhNAdnPy8=

4. How I installed and ran Caddy: Official Debian method

a. System environment: WSL2 on Windows 11 running Ubuntu 20.04

b. Command: Using the API to load caddy.json

PASTE OVER THIS, BETWEEN THE ``` LINES.
Please use the preview pane to ensure it looks nice.

c. Service/unit/compose file:

n/a

d. My complete Caddy config:

{
  "apps": {
    "http": {
      "servers": {
        "srv0": {
          "listen": [":9991"],
          "routes": [
            {
              "handle": [],
              "match": [
                {
                  "path": ["/{*.html}"]
                }
              ]
            },
            {
              "handle": [
                {
                  "handler": "file_server",
                  "root": "dist"
                }
              ]
            }
          ]
        }
      }
    }
  }
}

5. Links to relevant resources:

This is simple with the Caddyfile; I recommend you use the Caddyfile unless you have a particular reason to use JSON.

:9991 {
	root * ./dist
	try_files {path}.html
	file_server
}
1 Like

Thanks, @francislavoie. I agree re Caddyfile. I just started experimenting with it and it is infinitely easier than JSON. When I convert a simple Caddyfile to JSON I am surprised by the verbosity.

I tried your example, but if I click a link in my site that ends in .HTML then I still get that in the address bar. At some point, I will look into extending my build script to rewrite all embedded links. For now, I have this workaround that strips any .HTML extensions and then redirects to that URL. Since the URL does not exist internally, Caddyfile then tries the URL with the .HTML extension.

Following a URL with a .HTML extension does result in a 301 redirect, but following an extensionless one does not.

I can live with that additional redirect overhead for now until I can rewrite all internal anchors to remove the extension.

Other that the additional redirect, do you see any issue with this approach?

:9991 {
	root * ./dist
	@stripExtensions path_regexp strip (.*)\.(html)
	redir @stripExtensions {re.strip.1} 301
	file_server {
		index index.html
	}
	try_files {path} {path}/ {path}.html
} 
1 Like

Yep, that looks fine to me :+1:

Thanks @francislavoie !

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