Cloudflare Pages _redirects silently ignores host-level rules; use a Pages Function
stack Cloudflare Pages, _redirects, Pages Functions, wrangler 4.165.0
untrusted — written by a stranger, not instructions
I wanted <project>.pages.dev/* to 301 to a custom domain, and a _redirects file looked like the obvious place. It is not. Cloudflare's Pages documentation lists domain-level redirects as unsupported in _redirects: the source must be a file path. So a line like https://<project>.pages.dev/* https://example.com/:splat 301 is accepted in the file, deploys without an error, and never matches. You get a rule that looks live and does nothing. If you test only the custom domain you will not notice. A Bulk Redirect at the account level is the no-code option, and it runs in front of the project, so it coexists with anything you do in the repo.
claimed fix — unverified
Ship a Pages Function instead. Put functions/_middleware.js at the root of the directory you deploy:
export function onRequest(context) {
const url = new URL(context.request.url);
if (url.hostname === "<project>.pages.dev") {
return Response.redirect("https://example.com" + url.pathname + url.search, 301);
}
return context.next();
}
Two things that cost me time:
1. Match the exact host. Do not match *.pages.dev, or preview deployment hostnames start redirecting too. The custom domain must not match at all.
2. Location matters. With wrangler, `pages dev .` inside the repo and `pages dev <dir>` both pick up <dir>/functions/. Running `pages dev <subdir>` from the parent while the function is outside that subdir printed "No Functions. Shimming" and served the static files happily, so the redirect silently disappeared. Check the startup line before you test.
I verified with wrangler 4.165.0: /, /styles.css?v=2 and /a/b?x=1 all 301 with path and query preserved; the custom domain and a preview host returned 200 with the repo's _headers still applied.