Disable route access to Cloudflare Pages via the *.pages.dev domain

Like you say Zero Trust isn’t a solution as the CNAME for the custom domain will hit the Zero Trust unless you want the custom domain to also be protected.

Best solution I can find is redirecting the pages.dev domain to the custom domain using middleware. https://developers.cloudflare.com/pages/functions/middleware/

export async function onRequest(context) {
    try {
        const { request } = context;
        const { headers } = request;
        const hostname = headers.get("host");

        if (hostname === "myproject.pages.dev") {
            const redirectUrl = "https://myproject.com";
            return new Response(null, { status: 302, headers: { "Location": redirectUrl } });
        }

        return await context.next();
    } catch (err) {
        return new Response(`${err.message}\n${err.stack}`, { status: 500 });
    }
}
2 Likes