Cloudflare 05 ☁️ Custom Domains, Routes & Redirects — Configuring apex domains, subdomains, _redirects, _headers, and Bulk Redirects
Cloudflare Pages and Workers provide sophisticated tools for managing the lifecycle of your URLs. Whether you are mapping a custom domain to your frontend, implementing SEO-friendly redirects for legacy content, or enforcing security via HTTP headers, the platform offers three distinct layers of control: the DNS layer (custom domains), the file-based configuration layer (_redirects and _headers), and the infrastructure layer (Bulk Redirects). Understanding which tool to use is essential for maintaining a site’s structure without causing downtime or SEO penalties.
Custom domains form the identity of your application, while redirects are the plumbing that keeps that identity intact as your URL structure evolves. Bulk Redirects allow you to handle thousands of legacy URL migrations without writing a single line of code, and file-based configurations allow you to keep your SEO and security headers tightly coupled with your source code. Choosing the correct implementation strategy depends on whether you need a permanent 301 redirect, a security policy upgrade, or a complex dynamic routing rule.
This chapter details how to map custom domains to your Cloudflare projects, the syntax and order of operations for _redirects and _headers files, and the strategic use of Cloudflare’s Bulk Redirects service for large-scale migrations. We will clarify when to use file-based configuration versus infrastructure-based rules to ensure your site architecture is scalable and predictable.
Key point: Custom domains provide the identity; _redirects and _headers manage the site’s logical behavior (SEO and security) at the file level, while Bulk Redirects and Page Rules handle massive infrastructure-level changes that fall outside the scope of individual repository deployments.
Why X exists
The legacy URL migration problem. As projects grow, URL structures change. You cannot simply delete old URLs, or your search engine rankings will plummet, and users will hit 404s. Redirects exist to signal to browsers and search engines (via 301/302 status codes) that content has moved, preserving your site’s authority.
The configuration coupling requirement. Developers prefer “infrastructure as code.” If a security header or a redirect rule is defined in a Cloudflare dashboard, it is “hidden” from the repository. By using _redirects and _headers files in the source code, these rules are version-controlled, allowing developers to see the history and context of every change.
The Apex vs. Subdomain DNS limitation. DNS standards restrict how root domains (Apex) work compared to subdomains. Cloudflare simplifies this by providing specific proxy-based solutions that allow root domains to point to Cloudflare infrastructure as easily as subdomains.
The “Bulk” scale problem. If you have 5,000 legacy URLs to redirect, managing them in a _redirects file becomes unwieldy and potentially exceeds file size limits. Bulk Redirects exist to handle massive mapping datasets in the Cloudflare database, decoupled from your specific deployment repository.
The trade-off. File-based redirects are “deployment-dependent”—they only apply when the specific project is deployed. Infrastructure-level rules (like Bulk Redirects) are “global”—they execute before the request even reaches your project. The trade-off is visibility versus performance; file-based rules are easier to manage for developers, but infrastructure rules are more performant for massive datasets.
a. Custom Domains (DNS Layer)
Mapping a custom domain to a Cloudflare Pages project is managed through the “Custom Domains” section in the dashboard. When you add a domain, Cloudflare instructs you to update your DNS records at your registrar to point to the CNAME target provided by Cloudflare. This creates an alias for your project.pages.dev URL.
For Apex domains (example.com), Cloudflare uses CNAME flattening or specialized proxy IP addressing to ensure the root domain maps correctly without violating DNS standards. Once the DNS propagates, Cloudflare automatically provisions an SSL/TLS certificate for your custom domain, ensuring it is secure by default.
# DNS Configuration Example
Type: CNAME
Name: www
Value: my-project.pages.dev
Proxy Status: Proxied (Orange Cloud)
b. The File-Based Layer: _redirects and _headers
These are plain text files placed in your build’s root directory (e.g., public/ or dist/). Cloudflare parses these files during the deployment process and applies the rules to the project’s routing.
The _redirects file follows a simple source destination [status] syntax. It is the preferred way to manage project-specific migrations.
# _redirects
/old-page /new-page 301
/blog/* /posts/:splat 301
The _headers file allows you to define custom HTTP response headers, which are vital for security (Content-Security-Policy) and caching (Cache-Control).
# _headers
/*
X-Frame-Options: DENY
Content-Security-Policy: default-src 'self'
These files must be placed in your build’s output folder. If you are using a framework like React or Next.js, ensure these files are copied into the dist/ or public/ folder during the build process.
c. Infrastructure Layer: Bulk Redirects
Bulk Redirects are a Cloudflare-wide service, not specific to a single project. They are managed via a JSON or CSV file uploaded to the Cloudflare dashboard. This service is designed for scenarios where you need to move a large subset of traffic (e.g., migrating an entire domain to a new one) that does not belong to a specific repository deployment.
Unlike _redirects (which are deployment-specific), Bulk Redirects are executed at the edge, before the request is even handed off to a Page or a Worker. They are the most performant way to handle hundreds of thousands of redirects, as they bypass the application-level logic entirely.
Complete Example Session
# ============================================
# PART 1: DEFINING REDIRECTS (_redirects)
# ============================================
# /old-url /new-url 301
# /temp / 302
# /blog/* /posts/:splat 301
# ============================================
# PART 2: DEFINING HEADERS (_headers)
# ============================================
# /*
# X-Content-Type-Options: nosniff
# Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
# ============================================
# PART 3: MANAGING CUSTOM DOMAIN
# ============================================
# Settings > Custom Domains > Add Domain
# (Cloudflare provides CNAME target)
# ============================================
# PART 4: DNS CONFIGURATION
# ============================================
# Registrar: Add CNAME record (e.g., blog.example.com -> my-site.pages.dev)
# Ensure Orange Cloud is enabled
# ============================================
# PART 5: BULK REDIRECTS (CSV UPLOAD)
# ============================================
# source_url,target_url,status_code
# /legacy-a, /new-a, 301
# /legacy-b, /new-b, 301
# ============================================
# PART 6: PRECEDENCE RULES
# ============================================
# Bulk Redirects (Infrastructure) -> _redirects (App-level)
# Bulk rules take priority if they match first
# ============================================
# PART 7: VERIFYING REDIRECTS
# ============================================
curl -I https://example.com/old-page
# Expect: HTTP/2 301
# ============================================
# PART 8: HEADER DEBUGGING
# ============================================
curl -I https://example.com/
# Expect: X-Content-Type-Options: nosniff
# ============================================
# PART 9: THE CNAME FLATTENING
# ============================================
# Cloudflare handles root domain (Apex) redirects
# to www automatically if configured
# ============================================
# PART 10: CLEANUP
# ============================================
# Remove deprecated redirects in _redirects file
# to keep the file size minimal
The steps above covered configuring custom domains, implementing file-based redirects and headers, and setting up infrastructure-level bulk redirects.
Quick Reference
Redirect Precedence
| Priority | Layer | Best For |
|---|---|---|
| 1 | Bulk Redirects | Massive migrations |
| 2 | Page Rules | Global overrides |
| 3 | _redirects file | Repo-specific logic |
_redirects Syntax
| Syntax | Description |
|---|---|
/src /dest 301 | Permanent redirect |
/src /dest 302 | Temporary redirect |
/src/* /dest/:splat | Wildcard capture |
_headers Syntax
| Syntax | Description |
|---|---|
/* | Applied to all paths |
Key: Value | Header key-value pair |
Best Practices
✅ Do This:
# Keep _redirects file at the root of /dist // ✅
# Use 301 for permanent SEO-friendly moves // ✅
# Always set HSTS header in _headers // ✅
# Use Bulk Redirects for > 500 rules // ✅
# Test redirects using `curl -I` before deploying // ✅
❌ Don’t Do This:
# Put _redirects in the source folder (not dist) // ❌
# Use 302 when you mean 301 (SEO harm) // ❌
# Use redirects for internal navigation // ❌
# Overlap redirects with Page Rules // ❌
# Ignore header security best practices // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Redirect loop | Source == Destination | Check path logic |
| Header missing | File in wrong folder | Ensure in build output |
| Rules not applying | Cache issues | Purge Cloudflare cache |
| 404s after redirect | Incorrect Splat syntax | Check :splat usage |
| Bulk rule ignored | Repo rule takes priority | Check Redirect priority settings |
Real-World Examples
1. Blog Migration
Using _redirects to move /article/123 to /blog/123.
2. Security Hardening
Using _headers to inject a strict CSP on all pages.
3. Domain Swap
Using Bulk Redirects to forward an old acquired domain to a new primary one.
4. SPA Fallback
Using /index.html 200 as a catch-all in _redirects.
5. Language Redirect
Redirecting / to /en/ based on potential header logic (or Workers).
6. Image Hotlinking Defense
Using headers/rules to restrict asset access.
7. Legacy API Support
Redirecting old API v1 endpoints to v2.
8. Canonicalization
Redirecting example.com to www.example.com.
9. Temporary Maintenance
Using 302 redirect to a maintenance page during deployment.
10. SEO Optimization
Ensuring trailing slashes are consistently handled via redirects.
Visual
Routing Precedence
┌──────────────────────────────────────────────┐
│ REQUEST ARRIVES AT EDGE │
│ │ │
│ ▼ │
│ 1. BULK REDIRECTS (Infrastructure) ──► MATCH? (Done)
│ │ │
│ ▼ │
│ 2. _REDIRECTS (App-Level) ─────────► MATCH? (Done)
│ │ │
│ ▼ │
│ 3. SERVE FILE │
└──────────────────────────────────────────────┘
Splat (*) Logic
┌──────────────────────────────────────────────┐
│ RULE: /blog/* /posts/:splat │
│ │
│ Request: /blog/hello-world │
│ Result: /posts/hello-world │
│ │
│ (* captures path, :splat injects it) │
└──────────────────────────────────────────────┘
Custom Domain Flow
┌──────────────────────────────────────────────┐
│ USER ──► DNS (CNAME) ──► CLOUDFLARE │
│ (Custom) (Project Proxy) │
│ │
│ Cloudflare resolves request to │
│ your specific pages.dev deployment. │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Domain Logic | Custom Domains (DNS) |
| App Logic | _redirects |
| Security Logic | _headers |
| Scale Logic | Bulk Redirects |
| Redirect Status | 301 (Permanent), 302 (Temporary) |
| File Location | Build Output Root |
Key takeaways:
- Use the right layer. Don’t use Bulk Redirects for things you can manage in your repository; keep project-specific logic close to the code.
- Order matters. Cloudflare applies infrastructure-level rules (Bulk) before app-level rules (
_redirects), so plan your hierarchy accordingly. - Standardize SEO. Always prefer 301 redirects for permanent moves to preserve your search engine ranking.
- Security is file-based. Managing your security headers in the
_headersfile is the best way to ensure your site is secure by default across all preview and production builds. - Test everything. Redirects are notoriously tricky; always verify with
curl -Ito confirm the status code and final destination before deploying.
Remember: Your domain identity and your URL structure are the most persistent parts of your web presence. Treat your custom domains as your brand identity and your redirects as your site’s history; keep them managed, versioned, and intentional.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!