This example show how to force trailing slashes using a custom _worker.js
file in your Cloudflare Pages project.
Copy the _worker.js
file into your project's build output directory.
For requests to URLS without a trailing slash that would ordinarily serve an HTML asset, we redirect the request to the URL with a trailing slash.
For requests to URLs with a trailing slash, we flatten the default redirect (which would ordinarily strip the trailing slash) and serve the resulting page.
For the file /foo.html
:
- https://forcing-trailing-slashes.pages.dev/foo redirects to https://forcing-trailing-slashes.pages.dev/foo/
- https://forcing-trailing-slashes.pages.dev/foo/ serves
/foo.html
For the file /bar/index.html
:
- https://forcing-trailing-slashes.pages.dev/bar redirects to https://forcing-trailing-slashes.pages.dev/bar/
- https://forcing-trailing-slashes.pages.dev/bar/ serves
/bar/index.html
For the file /bin
:
- https://forcing-trailing-slashes.pages.dev/bin serves
/bin
- https://forcing-trailing-slashes.pages.dev/bin/ does 404 behavior (
404 /404.html
if exists else200 /index.html
)
For the file /index.html
:
- https://forcing-trailing-slashes.pages.dev/ serves
/index.html
- https://forcing-trailing-slashes.pages.dev/index.html redirects to https://forcing-trailing-slashes.pages.dev/
And finally, for a non-existent file:
- https://forcing-trailing-slashes.pages.dev/non-existent does 404 behavior (
404 /404.html
if exists else200 /index.html
)