This tutorial will instruct you how to modify both the URI path and the Host header of incoming requests using Transform Rules and Origin Rules.
Your website visitors will be routed from https://<YOUR_SOURCE_HOSTNAME>/uploads/* to https://<YOUR_TARGET_HOSTNAME>/*.
In this tutorial you will do the following:
- Create a URL rewrite to remove
/uploadsfrom the path. - Create an origin rule to modify the
Hostheader to desired hostname.
By following these steps, you can effectively manage both URI paths and Host headers to route traffic appropriately and optimize request handling.
-
In the Cloudflare dashboard, go to the Rules Overview page.
Go to Overview ↗ -
Select Create rule > URL Rewrite Rule.
-
Enter a descriptive name for the rule in Rule name.
-
Under If incoming requests match, select Custom filter expression, select Edit expression, and enter the following expression:
Text in Expression Editor:
raw.http.request.uri.path matches "^/uploads/.*" -
Under Set Rewrite parameters, select Path > Rewrite to, and select Dynamic.
-
Define the action for your rewrite URL rule:
Text after Path > Rewrite to > Dynamic:
regex_replace(raw.http.request.uri.path, "^/uploads/", "/")The
regex_replace()function replaces the/uploads/part of the path with/, changing/uploads/example.jpgto/example.jpg. -
Select Deploy.
-
In the Cloudflare dashboard, go to the Rules Overview page.
Go to Overview ↗ -
Select Create rule > Origin Rule.
-
Enter a descriptive name for the rule in Rule name.
-
Under When incoming requests match, define the rule expression:
Text in Expression Editor:
raw.http.request.uri.path matches "^/uploads/.*" -
Under Set origin parameters, select Host Header > Rewrite to.
-
Configure the rule to modify the
Hostheader to desired hostname:Text after Host Header > Rewrite to:
example.comThis will set the
Hostheader toexample.comfor matching requests. Make sure to replaceexample.comwith your actual hostname. -
(Optional) To route requests to a different origin (DNS target), use DNS override:
Text after DNS Record > Override to:
example.comThis will route requests to the DNS target of
example.cominstead of your default DNS record. -
Select Deploy.
After completing this tutorial, incoming traffic for https://<YOUR_SOURCE_HOSTNAME>/uploads/* will be routed to https://<YOUR_TARGET_HOSTNAME>/*.
Ensure the filters for the URL rewrite and the origin rule (or Cloud Connector rule) are precise to avoid unintended rule executions.
Remember that rules are evaluated in sequence, so Transform Rules (including URL rewrites) run before Origin Rules or Cloud Connector.