API And Integrations

Implementing Serverless Redirects Using Cloudflare Workers

  • 17 min read
  • Hostragons Team
Implementing Serverless Redirects Using Cloudflare Workers

Using Cloudflare Workers to implement serverless redirects means capturing a visitor's request at the Cloudflare edge network before it reaches the origin server, and returning a 301, 302, or conditional redirect response. With this method, you can create fast and scalable redirects based on domain, URL path, country, device, language, campaign parameters, or old page matches without touching the web server configuration. This approach is particularly useful for SEO transitions, domain changes, campaign landing page paths, and managing multiple sites, as it provides a low-latency, centralized, and easy-to-maintain solution.

Traditional redirects are typically handled through Apache .htaccess, Nginx server blocks, application code, or hosting control panels. While these methods are still valid, for high-traffic sites, teams managing multiple domains, or projects requiring dynamic decision-making according to different locations, Cloudflare Workers offer a more flexible layer. This is because the redirect logic operates within the Cloudflare data center closest to the user. This reduces the load on the origin server and also lowers the risk of performance issues and outages caused by misconfigured server rules.

In this guide, you will find applicable examples starting from basic 301 redirects using Cloudflare Workers, moving on to path-based, query parameter-based, country-based, mobile device-focused, and bulk redirect scenarios. We will also discuss step-by-step when to use 301 versus 302 from an SEO perspective, what to look for during the testing process, and which checks regarding domain, SSL, and hosting in the Hostragons infrastructure will be beneficial. You can naturally refer to our pages on Domain Registration and DNS Management, SSL Certificate Solutions, and Web Hosting Packages for domain management, secure connections, and efficient publishing.

What Are Cloudflare Workers and Why Use Them for Redirects?

Cloudflare Workers is a serverless platform that allows you to run JavaScript-based code snippets at the edge of the Cloudflare network. The term "serverless" does not mean there are no servers; it means you don't need to worry about server management, scaling, operating system maintenance, or infrastructure capacity. When a visitor sends a request to your site, the Worker handles that request at the edge, runs your rules, and redirects the user to another address if necessary.

The biggest advantage of using Workers for redirects is the level of control it provides. You can perform a simple URL match, but you can also read request headers, the country, the path, query parameters, user-agent information, and host values. For example, you can permanently move your old /products/hosting page to the /web-hosting page, redirect only users coming from outside Turkey to an English subdirectory, or route traffic coming with a specific campaign parameter to a special landing page.

Practically, this approach speeds up operations between SEO teams and technical teams. Imagine you are migrating 450 URLs from an old site to a new one. Instead of editing the server configuration file, going live, and reverting in case of errors, you can manage the redirect map within the Worker or in an external data store like KV. This makes the process of going live, testing, and rolling back more controlled.

Differences Between Server-Based and Cloudflare Workers Redirects

There is no one-size-fits-all method for every project. For a small site, a redirect tool in the hosting control panel may suffice for a few 301 redirects. However, if you need complex logic, high traffic, multiple domains, and rapid changes, Cloudflare Workers become more efficient. The table below summarizes the key differences to consider.

Differences Between Server-Based and Cloudflare Workers Redirects
CriteriaServer-Based RedirectCloudflare Workers Redirect
Execution PointRuns on the origin serverRuns on the Cloudflare edge network
Server LoadEvery request approaches the originRedirect can be completed before reaching the origin
FlexibilityRules depend on server softwareConditional logic can be established with JavaScript
Publishing SpeedServer access and restarts may be requiredQuickly published from the Cloudflare panel
SEO TransitionsPowerful but centralized management can be difficultMap-based and testable structure can be built
Suitable ScenarioA few static redirectsDynamic, multiple, and scalable redirects

You can interpret this table with a simple rule: If you have few redirects, simple conditions, and easy server access, the classic method may work for you. However, if your redirects involve SEO migration, country-based distribution, A/B campaign flows, or multiple domain architecture, the Worker layer will be more sustainable.

Prerequisites Before Getting Started

Completing the technical preparation before using Cloudflare Workers for redirects helps to reduce errors. First, your domain must be active on Cloudflare, and your DNS records must be correctly configured. If the DNS records with gray clouds (proxy feature not enabled) are used, the Worker route may not function as expected. Therefore, check the Cloudflare proxy status for the host where the redirect will be applied.

  • A Cloudflare account and an active domain for redirection.
  • Correct A, CNAME, or related records on the DNS side.
  • Cloudflare proxy activity and correct selection of SSL/TLS mode.
  • Redirect map: old URL, new URL, and status code.
  • SEO checklist: canonical, sitemap, internal links, and index status.
  • Testing tools: browser, curl, or HTTP header check tools.

It is also important for your origin server to be functioning properly on the hosting side. While a Worker redirect can reduce the load on the origin, it does not completely compensate for faulty DNS or SSL configurations. Especially if you are implementing HTTPS redirects, it is beneficial to ensure that your SSL certificate is active on your hosting account with Hostragons. You can refer to How to do Free SSL installation and Redirect Operations via cPanel for additional guidance.

Step-by-Step Guide to Implementing Serverless Redirects Using Cloudflare Workers

1. Create a Worker

Select the corresponding account in the Cloudflare panel, go to the Workers and Pages section, and create a new Worker. At this stage, Cloudflare provides you with a sample script. You can delete this sample and write your redirect logic. Be descriptive in naming; for instance, names like seo-redirects, domain-migration-redirects, or campaign-router will ease future maintenance.

In a basic redirect logic, a request is received, a URL object is created, and if a certain condition is met, the user is redirected to a new address using Response.redirect. A 301 is preferred for permanent SEO migrations, while a 302 is used for temporary campaigns or tests. A 308 can also be used for permanent redirects but in SEO migrations, the most common and understandable option remains the 301 status code.

2. Add a Simple 301 Redirect Rule

The simplest scenario is permanently moving an old page to a new one. The logic is as follows: If the request path is /old-page, redirect the user to /new-page with a 301. Within the Worker, you read the request URL value and check the pathname. This way, the redirect only occurs when the relevant path matches, and other requests continue normally.

For example, if you have transitioned from an old hosting category URL structure to a new one, you can move /hosting-packages to /web-hosting. In this case, you inform search engines that the page has been permanently moved. Within a few weeks, Google will start associating the new URL more clearly, but you need to ensure that a redirect chain is not created and that the old URL goes directly to the final URL.

3. Define the Worker Route

Writing the Worker code alone is not enough; you need to specify which requests it will work on using a route. For example, example.com/* encompasses all paths under the main domain. If you want it to work only in a specific subdirectory, you can define a narrower route like example.com/old-blog/*. Keeping the route scope broader than necessary can lead to unexpected redirects.

Before going live, it is good practice to test the route scope on a staging or test subdomain. For instance, you can run the rule on test.example.com/* and check the header and redirect behavior. If everything is correct, you can move to the production domain route. This method is especially helpful in preventing faulty bulk redirects in large SEO migration projects.

4. Publish and Test the HTTP Status Code

After the Worker is published, it is not sufficient to just check if the page opens in the browser. Browser cache may sometimes show old results. Instead, verify that the 301 or 302 status code is returned correctly by performing an HTTP header check. Additionally, ensure that the final URL in the Location header is what you expect.

  • Does the old URL go directly to the new URL?
  • Is the redirect code 301 or 302?
  • Is there an extra chain forming from HTTP to HTTPS?
  • Are the www and non-www variations consistent?
  • Is the use of slashes at the end of the URL standardized?
  • Do mobile and desktop users see the same SEO target?

Common Redirect Scenarios

Single Page Redirect

Single page redirects are the simplest and safest start. They are used when an old service page, campaign page, or blog post is moved to a new address. The key point here is that the content intention of the old page must align with that of the new page. Redirecting an old SSL guide directly to the homepage diminishes user experience and can scatter SEO signals. Instead, it is better to redirect to the new SSL guide or category page that is the closest match.

Bulk URL Map Redirect

In site migration projects, it may be necessary to redirect dozens or even thousands of URLs. You can define a map object within the Worker to match old paths to new ones. For example, you would map /old-blog/what-is-cloudflare to /blog/what-is-cloudflare. This approach is practical for small to medium-sized lists. However, embedding a long list of over 1000 URLs in the code becomes challenging in terms of maintenance. In this case, reading the redirect map via Cloudflare KV, R2, or an external API provides a more professional architecture.

When performing bulk redirects, prepare a three-column table in Excel or Google Sheets: old URL, new URL, status code. Then ensure that the same URL does not go to multiple targets, that the final URL returns a 200 status code, and that it is not blocked by robots.txt. A common mistake in SEO migrations is to bulk send old URLs to unrelated pages on the new site. While this may seem to reduce crawl loss in the short term, it can weaken quality signals in the long term.

Country-Based Redirect

Cloudflare allows you to use the country information from which the request originates. For example, you can redirect users coming from Turkey to /tr and users from Germany to /de. However, care must be taken with country-based automatic redirects from an SEO perspective. Googlebot often crawls from specific locations, and misconfigurations may hinder the discovery of different language versions. Thus, hreflang tags, language selector links, and sitemap distinctions must be properly structured.

It is generally safer to implement country-based redirects with a 302 instead of a permanent 301. This way, you provide a temporary experience based on the user’s location and do not claim that the page has been permanently moved elsewhere. Additionally, giving users the option to change their language or country selection is important for the user experience.

Device or User-Agent Based Redirect

Redirecting mobile users to a different page used to be a common approach; however, responsive design is now considered healthier. Still, user-agent-based redirects can be used for special app download pages, mobile campaign flows, or lightweight landing page experiences. SEO caution is also necessary here. Presenting completely different content to desktop and mobile users can lead to inconsistent signals.

If you are implementing device-based redirects, the content intention of the page shown to mobile users must align with the desktop page. Also, do not forget Google’s mobile-first indexing approach. Since the mobile experience is one of the main indexing signals, it is not enough to optimize just the desktop page.

Campaign Redirect Based on Query Parameters

Worker redirects are extremely useful for digital marketing teams. For example, you can send users coming with the utm_campaign=blackfriday parameter to a special campaign page. This can be resolved on the edge without requiring additional development on the origin application. However, ensure that UTM parameters are not completely lost. If necessary for analytical measurement, carry the parameters over to the new URL or track them correctly in your campaign platform.

Choosing Between 301, 302, 307, and 308 from an SEO Perspective

The choice of redirect code is not just a technical detail; it conveys to search engines the intention behind moving the page. A 301 indicates a permanent move and is the most commonly used code in SEO migrations. A 302 is a temporary redirect, preferred in campaigns, tests, location, or time-limited flows. A 307 provides temporary redirect behavior while preserving the HTTP method. A 308 is a permanent redirect similar to a 301, preserving the method.

Choosing Between 301, 302, 307, and 308 from an SEO Perspective
CodeMeaningWhen to Use?SEO Note
301Permanent RedirectWhen a page or domain is permanently movedSuitable for transferring SEO signals to the new URL
302Temporary RedirectIn campaigns, tests, country, or device-based flowsDoes not convey a permanent move message
307Temporary, preserves methodWhen methods like POST need to be preservedGenerally not the first choice for SEO page moves
308Permanent, preserves methodIn modern API and permanent method preservation scenariosMay be suitable but 301 is more commonly understood

The golden rule for SEO is this: Use 301 for permanently moved pages with clear new counterparts; opt for 302 in temporary, personalized, or condition-based redirects. Additionally, avoid redirect chains. If the old URL first goes from HTTP to HTTPS, then from non-www to www, and finally to the new page, a three-step chain is created. The ideal structure is for the old URL to go to the final HTTPS URL in a single step.

Best Practices for Performance and Security

Best Practices for Performance and Security

Cloudflare Workers are fast; however, poorly written redirect logic can still produce delays and errors. Keep your rules simple, avoid writing overly complex regular expressions, and do not let large lists grow uncontrollably within the code. For very large redirect lists, using key-value storage structures like KV provides better performance and maintainability. Also, to prevent erroneous infinite loops, ensure that the target URL is not the same as the current host and path.

  • Assign clear ownership for each rule: SEO, software, or marketing team.
  • Backup the redirect map before making changes.
  • Test on a staging domain before going live.
  • Before deciding on a 301, ensure that the new URL is indeed permanent.
  • After each publication, manually check 10-20 sample URLs.
  • Monitor 404 reports and coverage data in Google Search Console.
  • Do not leave internal links on the old URL; update them to the new URL.

On the security side, be cautious of open redirect risks. Using user-provided parameters like next, redirect, or url directly as targets can lead to attackers misusing your trusted domain. If you are implementing parameter-based redirects, only whitelist allowed domains. For example, only your domains or verified campaign domains should be targets.

SSL configuration is also a critical issue. When using Flexible SSL on Cloudflare, if there is no HTTPS on the origin side, you may encounter complex redirect loops. The healthiest structure generally involves using Full or Full strict SSL mode. For this, your origin server must have a valid SSL certificate. Hostragons SSL solutions can facilitate this: Buy SSL Certificate and Corporate Hosting Security.

Key Considerations for Hostragons Infrastructure

When using Cloudflare Workers redirects for sites hosted on Hostragons, you need to consider three layers together: domain DNS, hosting configuration, and application redirects. First, the nameserver records of the domain must be directed to Cloudflare. Then, your DNS records should point to the Hostragons hosting server, and the proxy-enabled records should be activated with orange clouds.

Secondly, ensure that the domain, addon domain, or alias structures defined in your hosting panel are correct. Even if the redirect occurs on the Cloudflare edge, some requests will still reach the origin server. Therefore, if there is a misconfigured virtual host, missing SSL, or faulty root directory configuration on the origin side, the user experience may be affected. For domain and hosting alignments, you may find Domain Forwarding Guide and cPanel Hosting Management content helpful.

Thirdly, check the application-level redirects. WordPress, Laravel, custom PHP applications, or other CMSs may have their own HTTPS, www, or language redirects. If a Cloudflare Worker runs a second rule on the same issue, loops or chains may occur. The best approach is to consolidate redirect responsibilities into a single layer. For example, all domain and SEO migration redirects can remain on Workers, while in-application user session redirects can stay on the software side.

Testing, Monitoring, and Debugging

Once the redirect is published, the monitoring process is as crucial as the setup. Within the first 24 hours, check the most critical URLs, revenue-generating landing pages, the most visited pages in organic traffic, and old URLs that have backlinks. Monitor the Indexing and Page Experience reports in Google Search Console. When examined together with server logs, Cloudflare analytics, and analytics data, erroneous redirects are identified more quickly.

Common patterns in debugging include mistakenly using 302 instead of 301, redirecting the old URL to the homepage instead of the new URL, inconsistent behavior in slash variations, case sensitivity, and loss of query parameters. Especially for e-commerce, SaaS, and hosting sites, misdirected price, product, category, and support pages can directly impact conversion rates.

After a publication, apply a simple checklist. First, randomly select examples from the old URL list. Second, test each one with a header check tool. Third, ensure that the final page returns a 200 status code. Fourth, verify that the page content matches the search intent of the old page. Fifth, confirm that internal links have been updated to the new URLs. These five steps can help prevent many technically functional but SEO-weak redirects.

Example Strategy: Moving Old Hosting Pages to a New Information Architecture

Let’s consider a concrete scenario. A hosting company is renewing its old URL structure and moving pages like /linux-hosting, /wordpress-hosting-plans, /ssl-security, and /domain-check to a simpler structure. The new targets are /web-hosting, /wordpress-hosting, /ssl-certificates, and /domain-checking. In this case, four clear 301 rules are defined on the Worker. Subsequently, the site menus, footer links, sitemap, and canonical tags are updated to the new URLs.

The goal in this transition is not just to send the user to the correct page. It is also to clearly show search engines the new counterparts of the old pages. If the old /linux-hosting page redirects to the homepage, Google may lose the context of that page. On the other hand, the /web-hosting page is closer to the same product intent. Therefore, a good redirect map is more than just a technical file; it is part of an SEO strategy.

Frequently Asked Questions

Are redirects made with Cloudflare Workers safe for SEO?

Yes, they are safe when the correct status code and target URL are used. Use 301 for permanent page moves and 302 for temporary or conditional flows. Additionally, avoid redirect chains, loops, and unrelated target page errors.

Does the origin server need to be operational for Worker redirects?

If the redirect is completed entirely on the Cloudflare edge, it can return a response without reaching the origin server. However, since the redirected final page will operate on the origin or another infrastructure, the hosting, DNS, and SSL configurations must be healthy.

Is it better to use Workers instead of Cloudflare Page Rules?

For a few simple redirects, Page Rules or Redirect Rules may be sufficient. However, if you need path, country, device, parameter, multi-domain, or map-based dynamic logic, Workers provide a more flexible and scalable solution.

Will changing a 301 redirect later cause issues?

A 301 should not be changed frequently as it gives a permanent signal. Browsers and search engines can cache 301 results. Therefore, ensure that the target URL is permanent and meets the right content intention before publishing a 301.

Can redirects between www and non-www be implemented with Cloudflare Workers?

Yes. You can redirect non-www addresses to their www version or vice versa by checking the host value. The important thing is to establish a single standard, prepare the SSL certificate to cover both variations, and update internal links according to the same standard.

Conclusion

Implementing serverless redirects using Cloudflare Workers is a powerful method that provides both performance and operational flexibility in modern web projects. As long as you correctly select between 301 and 302 codes, carefully prepare your redirect map, and check the DNS, SSL, and hosting layers together, you can manage SEO transitions more securely. While simple rules may suffice for smaller projects, testing, monitoring, and documentation become critical in large migrations.

By correctly configuring your domain, hosting, and SSL infrastructure on Hostragons, you can establish a more solid foundation for your Cloudflare Workers redirects. If you need assistance, you can explore our pages on Web Hosting Packages, Domain Lookup, and SSL Certificate Solutions to plan the right infrastructure for your project.

Share this article:

Hostragons Team

Up-to-date guides from our expert team on hosting, servers, and domain names. Let's find the right solution for your project together.

Contact Us