Technology

Edge Logic with Cloudflare Workers and BunnyCDN Edge Rules

When we review client architectures at dchost.com, we still see a lot of logic living directly on the origin server: URL redirects in .htaccess, PHP scripts only used for simple rewrites, or whole frameworks bootstrapped just to set a few security headers. All of this work can be pushed much closer to your visitors. Cloudflare Workers and BunnyCDN Edge Rules let you run logic on edge nodes around the world, so decisions are made before the request even hits your VPS or dedicated server. The result is lower latency, less load on your origin, and a cleaner application stack.

In this article we will focus on three practical edge use cases that you can start using today: URL rewrites and redirects, HTTP security headers, and offloading simple logic from the origin to the CDN. We will look at how Cloudflare Workers and BunnyCDN Edge Rules differ, how to choose the right one for each task, and how to design a strategy that fits a modern hosting setup on dchost.com infrastructure.

What Does Running Logic at the Edge Really Mean?

“The edge” simply means servers that are geographically close to your visitors. A CDN like Cloudflare or BunnyCDN operates many PoPs (points of presence) worldwide. Traditionally, these PoPs only cached and served static files. Today, they can also execute logic before forwarding a request to your origin or before sending a response back to the browser.

Instead of asking your PHP application or Nginx/Apache to handle every redirect, header, or micro-decision, you can move that logic to the CDN. The benefits are clear:

  • Lower latency: Redirects and rewrites complete at the nearest edge node, not on a distant origin.
  • Less origin load: Fewer hits reach your VPS or dedicated server, which means more capacity for real application work.
  • Simpler application code: Old rewrite rules and small glue scripts disappear from the codebase.
  • Central control: Rules live in one edge layer instead of being duplicated across multiple app servers.

If you are already using a CDN for caching, edge logic is the natural next step. It sits nicely beside the kind of caching strategies we discuss in our CDN caching playbook for WordPress and WooCommerce, but works even for fully dynamic applications.

Cloudflare Workers vs BunnyCDN Edge Rules: The Mental Model

Cloudflare Workers and BunnyCDN Edge Rules both live at the edge, but they occupy different layers of complexity.

  • Cloudflare Workers: A programmable JavaScript runtime that can inspect, modify, or generate requests and responses. Think of it as a tiny, globally distributed serverless function.
  • BunnyCDN Edge Rules: A rule engine with conditions (URL, country, header, etc.) and actions (redirect, rewrite, set header, cache control). Think of it as a powerful GUI for common policies.

Cloudflare Workers in Practice

Workers are event-driven scripts that handle HTTP requests. A minimal Worker looks like this:

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const url = new URL(request.url);

  // Simple rewrite example
  if (url.pathname.startsWith("/blog")) {
    url.pathname = url.pathname.replace("/blog", "/articles");
    return fetch(url.toString(), request);
  }

  // Pass through if no special handling
  return fetch(request);
}

With this model, you can:

  • Rewrite URLs or route requests based on cookies, headers, or geo-IP.
  • Generate responses entirely at the edge (for example, a maintenance page).
  • Inject or modify headers on both the request and response.
  • Implement lightweight authentication or feature flags without touching your origin.

BunnyCDN Edge Rules in Practice

BunnyCDN Edge Rules are configured in the dashboard. Instead of code, you define conditions and actions through a UI. Some typical conditions:

  • URL path matches /blog/*
  • Country is not one of [US, DE, TR]
  • HTTP header User-Agent contains bot
  • File extension is one of .jpg, .png, .webp

And actions might include:

  • Redirect (301/302) to another URL.
  • Rewrite the URL path without changing what the browser sees.
  • Add, override, or remove HTTP headers.
  • Force HTTPS, change caching behaviour, or deny access.

Edge Rules are ideal for teams who want strong control but prefer configuration over code. For advanced behaviour (custom logic, third-party APIs, complex routing), you step up to Cloudflare Workers.

URL Rewrites and Redirects at the Edge

Let us start with the most common and impactful use case: URL rewrites and redirects. These usually live in .htaccess, Nginx config, or even in application routes. Moving them to the edge gives you instant responses and keeps your origin config cleaner.

Common Rewrite and Redirect Scenarios

  • HTTP to HTTPS: Force all visitors to use secure URLs.
  • www to non-www (or the opposite): Canonicalize hosts for SEO and simplicity.
  • Legacy URL migrations: Redirect /old-blog/post-name to /blog/post-name after a site restructure.
  • Language-specific paths: Redirect visitors from certain countries to /en/, /de/, or /tr/ paths.
  • Clean URLs for SPAs: Rewrite /app/* to /app/index.html while keeping the original path in the browser.

These are the kinds of rules that can sit entirely at the edge. Your origin only serves the final target URL.

URL Rewrite Example with Cloudflare Workers

Here is a Worker that handles three common tasks: HTTPS enforcement, “www” canonicalization, and a legacy blog path migration.

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const url = new URL(request.url);

  // 1) Force HTTPS
  if (url.protocol === "http:") {
    url.protocol = "https:";
    return Response.redirect(url.toString(), 301);
  }

  // 2) Force non-www
  if (url.hostname.startsWith("www.")) {
    url.hostname = url.hostname.replace(/^www./, "");
    return Response.redirect(url.toString(), 301);
  }

  // 3) Legacy blog URLs: /old-blog/> /blog/
  if (url.pathname.startsWith("/old-blog/")) {
    url.pathname = url.pathname.replace("/old-blog/", "/blog/");
    return Response.redirect(url.toString(), 301);
  }

  // Otherwise, just pass to origin
  return fetch(request);
}

Notice that the origin server does not know any of these rules exist. It receives only the final URL. That makes migrations (for example, moving from one CMS to another) easier, because the redirect logic is decoupled from the app itself.

URL Rewrite Examples with BunnyCDN Edge Rules

With BunnyCDN Edge Rules you would configure similar behaviour in the dashboard:

  1. Force HTTPS:
    • Condition: Protocol is HTTP.
    • Action: Redirect to HTTPS (status 301).
  2. Legacy blog migration:
    • Condition: URL path begins with /old-blog/.
    • Action: Redirect to https://example.com/blog/$1 (using a path capture if needed).
  3. SPA index rewrite:
    • Condition: URL path begins with /app/ and file extension is empty.
    • Action: Rewrite path to /app/index.html while keeping the browser URL unchanged.

For teams that frequently adjust redirects (SEO work, marketing campaigns, language rollouts), having these rules in a single CDN layer is much nicer than juggling Nginx snippets and .htaccess fragments on every origin.

Security Headers from the Edge Instead of the Origin

Another perfect match for edge logic is HTTP security headers. Things like HSTS, CSP, X-Frame-Options, and Referrer-Policy are sent with every response, so it is wasteful to generate them with application code. The edge can attach them after the origin responds, or even for fully cached content without hitting the origin at all.

If you want a deep dive into what each header does, our HTTP security headers guide (HSTS, CSP, X-Frame-Options and Referrer-Policy) covers the concepts in detail. Here, we will focus on how to push them to the edge.

Which Headers Make Sense at the Edge?

Most purely declarative headers are excellent candidates for edge injection:

  • Strict-Transport-Security (HSTS)
  • Content-Security-Policy (CSP) – for many static patterns
  • X-Frame-Options
  • X-Content-Type-Options
  • Referrer-Policy
  • Permissions-Policy

Headers that depend on business logic (for example, different CSP for admin vs public pages, or signed cookies) might still live in the application. But you can often cover 80–90% of cases at the edge and only override selectively from the origin if needed.

Setting Security Headers with a Cloudflare Worker

Here is a Worker that wraps the origin response and attaches a standard set of security headers:

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const response = await fetch(request);
  const newHeaders = new Headers(response.headers);

  newHeaders.set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
  newHeaders.set("X-Frame-Options", "SAMEORIGIN");
  newHeaders.set("X-Content-Type-Options", "nosniff");
  newHeaders.set("Referrer-Policy", "strict-origin-when-cross-origin");
  newHeaders.set("Permissions-Policy", "geolocation=()",);

  // Example CSP - adapt carefully to your site
  newHeaders.set("Content-Security-Policy", "default-src 'self'; img-src 'self' https: data:; script-src 'self' 'unsafe-inline' https:; style-src 'self' 'unsafe-inline' https:");

  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers: newHeaders
  });
}

This Worker does not change the body or status code; it simply strengthens your responses with a consistent header set. You can even apply stricter policies on certain paths, for example a hardened CSP on /admin and a more permissive one on legacy sections.

If you are also using Cloudflare’s security features, you can combine this with WAF and bot protection as described in our Cloudflare security settings guide for WAF, rate limiting and bots. The Worker handles headers, while the WAF blocks malicious traffic before it reaches your application.

Setting Security Headers with BunnyCDN Edge Rules

BunnyCDN Edge Rules make header injection even simpler for straightforward setups. A common pattern:

  1. Create an Edge Rule with no path condition (apply to all URLs), or a restricted path if you prefer.
  2. Choose the action “Add Response Header” or “Set Response Header”.
  3. Define headers like:
    • Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
    • X-Frame-Options: SAMEORIGIN
    • X-Content-Type-Options: nosniff
    • Referrer-Policy: strict-origin-when-cross-origin

For CSP and Permissions-Policy you can separate them into their own rules, or keep them at the origin if you need deeper application awareness. The key benefit is that static assets and cached HTML now carry the correct headers automatically, without consuming any CPU cycles on your origin server.

Offloading Simple Logic from Your Origin Server

Beyond rewrites and headers, there is a wide range of “small but useful” logic that fits naturally at the edge. Moving this code away from the origin helps you keep your VPS or dedicated server focused on running the main application and database.

Edge-Friendly Logic Examples

  • Maintenance pages: Serve a static “We will be back soon” page entirely from the edge while you work on the origin.
  • Geolocation-based routing: Route users from certain regions to /eu/ or /us/ versions, or to region-specific backends.
  • Simple A/B testing: Randomly send a fraction of visitors to /variant-b/ and label them with a cookie, without extra load on your app.
  • Static API responses: For configuration endpoints that rarely change, respond directly from a Worker instead of hitting PHP/Node.js.
  • Referrer-based blocking: Deny or challenge suspicious referral patterns before they reach the origin.

On Cloudflare, these are typically implemented with Workers. On BunnyCDN, some of them can be covered with Edge Rules (for example, simple country-based blocking or redirects), while others would need to remain at the origin.

Maintenance Mode with Cloudflare Workers

A very practical pattern we use during deployments is a temporary maintenance page served at the edge:

const MAINTENANCE = false; // flip to true during deployment

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  if (MAINTENANCE) {
    return new Response("<h1>We&apos;ll be back soon</h1>", {
      status: 503,
      headers: {
        "Content-Type": "text/html; charset=utf-8",
        "Retry-After": "300"
      }
    });
  }

  return fetch(request);
}

Switch one flag and the entire site is in maintenance mode from the edge, while you safely deploy changes on your dchost.com VPS or dedicated server. Because it is served by the CDN, your origin can even be temporarily offline during some parts of the maintenance window.

Geolocation-Based Redirects with BunnyCDN Edge Rules

BunnyCDN exposes the visitor’s country to Edge Rules, so you can configure simple geolocation logic without code. For example:

  • Condition: Country is in [DE, AT, CH].
  • Action: Redirect to https://example.com/de$path with status 302.

Or you might block traffic from certain regions from accessing an admin path:

  • Condition: URL path begins with /admin AND country is not in your approved list.
  • Action: Return 403 Forbidden.

For more complex geolocation logic (combining country with cookies, AB tests, or feature flags), you would typically move up to Cloudflare Workers, where you can implement arbitrary JavaScript logic.

What Should Stay on the Origin?

Not everything belongs at the edge. In general, keep the following on your origin:

  • Anything that needs your database: Cart logic, user accounts, permissions, search, reporting.
  • Heavy computation: Image processing, video encoding, large PDF generation.
  • Complex business rules: Pricing, discounts, licensing checks, internal APIs between microservices.

The edge is best for fast, stateless, request/response adjustments. While Cloudflare Workers can make external API calls and even maintain durable state, that is usually a later stage of maturity. Start by extracting clearly isolated logic (rewrites, headers, simple blocks) and scale from there.

Designing an Edge Logic Strategy for a Site Hosted on dchost.com

When clients host their origin on a dchost.com VPS, dedicated server or colocated machine, we often propose a layered architecture:

  • Layer 1 – DNS and CDN: Cloudflare or BunnyCDN in front, handling TLS termination, caching, and edge logic.
  • Layer 2 – Origin web stack: Nginx or Apache, PHP-FPM or Node.js, running on a tuned VPS or dedicated server.
  • Layer 3 – Data and background jobs: MariaDB/MySQL/PostgreSQL, Redis, and background workers.

This aligns well with other patterns we describe, such as building a robust CDN caching and edge rules strategy or using GeoDNS and multi-region hosting architectures for low latency. Edge logic simply becomes part of the first layer.

Step-by-Step Rollout Plan

  1. Inventory existing logic:
    • Collect redirects from .htaccess, Nginx configs, and application code.
    • List all security headers currently sent by your app or server.
    • Identify small PHP or Node.js scripts that mostly do “glue” work.
  2. Classify what can move to the edge:
    • Redirects and host/HTTPS canonicalization – edge-friendly.
    • Static security headers – great at the edge.
    • Small utility endpoints that rarely change – possible Worker candidates.
  3. Decide on the tool per task:
    • Use BunnyCDN Edge Rules for straightforward redirects, header injection and access control.
    • Use Cloudflare Workers when you need real logic, conditions or external calls.
  4. Roll out gradually:
    • Start with non-critical paths (for example, old URL redirects).
    • Monitor logs and error rates at the origin to ensure nothing breaks.
    • Once stable, remove the equivalent rules from your origin configs.
  5. Document and version control:
    • Keep Worker scripts in Git alongside your application.
    • Export or document BunnyCDN Edge Rules so they can be recreated if needed.

As you clean up origin configs, you will also find that migrations become easier. When you move a site from shared hosting to a VPS (or between VPS plans at dchost.com), most of the URL and header behaviour stays at the edge, untouched by the change underneath.

When Not to Use Edge Logic: Pitfalls and Limits

Edge logic is powerful, but there are some pitfalls to avoid:

  • Debugging complexity: If you split related logic between the origin and edge without clear boundaries, debugging becomes harder. Keep responsibilities well-defined.
  • Caching interactions: A Worker that dynamically changes responses needs to be aware of cache headers. Misconfigured cache rules can lead to stale or mixed content. Our article on HTTP Cache-Control, ETag and CDN rules for faster sites is a helpful companion here.
  • Vendor lock-in: Deeply custom Workers (or very specific Edge Rules) can make future CDN changes more involved. Keep scripts modular and documented.
  • Security assumptions: Edge logic does not replace a WAF or proper origin hardening. Combine it with firewall rules and WAF policies as we describe in our guide to WAF and bot protection with Cloudflare, ModSecurity and Fail2ban.
  • Stateful logic: Anything that needs strong consistency across requests (transactions, user balances, etc.) should remain in your application and database, not in an edge script.

If you are unsure whether a piece of logic belongs at the edge or origin, a good rule of thumb is: if it can be expressed purely as “if this request looks like X, then transform or block it”, it is a strong candidate for the edge. If it needs internal data or complex rules, keep it in your main stack.

Summary: Building a Clean Edge Layer on Top of dchost.com Hosting

Moving logic to the edge is one of the simplest ways to make your hosting stack both faster and cleaner. Cloudflare Workers give you a programmable runtime for complex routing, rewrites and small services, while BunnyCDN Edge Rules cover a large percentage of real-world needs through a straightforward rule engine. Together, they can handle URL rewrites, redirects, HTTP security headers and a surprising amount of everyday glue logic before any request reaches your origin.

On the origin side, a well-tuned dchost.com VPS, dedicated server or colocated machine can then focus on what it does best: running your PHP, Node.js, or other application code and serving the database. You cut down TTFB, free up CPU for real work, and make future migrations less painful because so much behaviour is standardized at the edge layer.

If you want help designing this stack, our team at dchost.com works with Cloudflare and BunnyCDN setups daily. We can review your current redirects, security headers and application glue code, then propose a concrete plan to move the right pieces to the edge while keeping your core app safe and maintainable. Combine that with the right hosting plan on our infrastructure, and you get a modern, resilient architecture that feels faster to every visitor, everywhere in the world.

Frequently Asked Questions

Cloudflare Workers provide a full JavaScript runtime at the edge. You can write custom logic that inspects and modifies requests and responses, calls external APIs, and even generates responses without touching your origin. BunnyCDN Edge Rules are a configuration-driven engine: you define conditions (URL, country, file type, headers) and choose from predefined actions such as redirects, rewrites, header changes and cache tweaks. In practice, BunnyCDN Edge Rules are ideal for common policies like HTTPS redirects and security headers, while Cloudflare Workers are better for advanced routing, A/B testing, custom maintenance pages and other scenarios that need real programming logic.

Start with tasks that are stateless and purely request-based. Typical candidates are HTTP to HTTPS redirects, www to non-www canonicalization, legacy URL migrations, simple path rewrites (for example, SPA index mapping), and standard HTTP security headers like HSTS, X-Frame-Options and Referrer-Policy. You can also consider maintenance pages, geolocation-based redirects and simple referrer-based blocking. Anything that needs your database, complex business rules or heavy computation should remain on your origin, where your application and data layer are in full control.

For many projects, yes. Headers such as Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, Referrer-Policy and most Permissions-Policy directives are excellent candidates for edge injection via Cloudflare Workers or BunnyCDN Edge Rules. You can also set a baseline Content-Security-Policy at the edge and override it from the origin for special sections like admin panels. The key is to keep your configuration consistent and test thoroughly; misconfigured CSP in particular can break scripts or styles. If you need a deeper primer on each header, refer to our dedicated HTTP security headers guide and then decide which ones you are comfortable moving to the edge layer.

No. Edge logic complements, but does not replace, your VPS, dedicated server or web server stack. Workers and Edge Rules are excellent for fast, stateless decisions and transformations close to the user. Your origin server is still responsible for running your main application, handling authentication, talking to the database, processing business logic and serving dynamic pages. A good architecture lets the edge handle repetitive boilerplate like redirects and headers, while the origin focuses on the parts that truly require your app and data. At dchost.com we design stacks so both layers work together cleanly rather than overlapping responsibilities.

Edge logic and caching are closely related but separate concerns. Caching decides whether a response can be served from the CDN cache or must be fetched from the origin. Edge logic, via Workers or Edge Rules, can run before or after cache decisions depending on how you configure it. For example, you might run a Worker to normalize URLs and set cache keys, and then let the CDN cache the normalized responses. Or you may inject security headers after a cached response is retrieved, without re-contacting the origin. It is important to understand cache headers (Cache-Control, ETag, etc.) and test carefully so that dynamic decisions are not accidentally cached. Our articles on CDN caching rules and HTTP cache control are helpful references when designing this layer.