如何在Cloudflare Worker中配置自定义Host Header?附场景示例
How to Rewrite Host Header to
new.ex.com for www.ex.com Requests in Cloudflare Workers Got it, let's break down exactly how to set this up. The goal here is to intercept all requests to your www.ex.com subdomain (which points to 1.2.3.4) and rewrite their Host header to new.ex.com before sending the request to your origin server.
Step 1: Create a New Cloudflare Worker
- Head to your Cloudflare dashboard, go to the Workers & Pages section
- Click Create Worker, give it a descriptive name (like
host-header-rewrite), and replace the default boilerplate code with the snippet below.
Step 2: Use This Worker Code
This code will check for the target Host header and modify it as needed:
addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { // Clone the request because original requests are immutable in Workers const modifiedRequest = new Request(request) // Check if incoming Host header matches your target const currentHost = modifiedRequest.headers.get('Host') if (currentHost === 'www.ex.com') { // Overwrite the Host header with your desired value modifiedRequest.headers.set('Host', 'new.ex.com') } // Forward the modified request to your origin server return fetch(modifiedRequest) }
Code Explanation:
- We listen for all incoming
fetchevents (every request passing through Cloudflare triggers this) - We clone the original request because request objects in Cloudflare Workers are read-only by default—you can't modify the original directly
- We check if the incoming Host header is exactly
www.ex.com(matching your setup) - If it matches, we replace the Host header with
new.ex.com - Finally, we send the modified request to your origin server
Step 3: Attach the Worker to Your www.ex.com Route
- Go back to your domain's Cloudflare dashboard, navigate to Workers Routes
- Click Add route
- In the Route field, enter
www.ex.com/*(this matches all requests to your www subdomain, including paths likewww.ex.com/about) - Select the worker you just created from the Worker dropdown
- Save the route to activate the configuration
Important Notes
- Ensure your origin server is configured to accept requests with the
new.ex.comHost header—otherwise it might reject the request with a 403 or 404 error - Use Cloudflare's Preview feature in the Worker editor to test this before deploying: you can simulate a request with the
www.ex.comHost header and verify the modified request is sent correctly - This rewrite only affects the request sent to your origin; the client's original request (and the response sent back to the client) will not have their Host header altered—this is a server-side change only
内容的提问来源于stack exchange,提问作者javad
相关产品推荐
相关产品推荐

