简体   繁体   中英

How to resolve redirect 301 using Cloudflare worker

When trying to fetch URL-A in Cloudflare like

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


async function handleRequest(request) {
  return fetch(request);
}

I'm getting the following response:

301 Moved Permanently location: URL-B

Can I resolve it in Cloudflare by making an additional fetch to URL-B instead of returning 301 response to the user?

Sounds possible, but didn't manage to find where I can get response's location attribute for URL-B.

How can I get the location of URL-B from URL-A's 301 response? (Already tried to console.log all knowns response attributes)

In the Worker, before sending the outbound request, you can specify that redirects should be followed.

Here's an example showing how to set that:

async function handleRequest(incomingRequest) {
    const outgoingRequest = new Request(
        incomingRequest.url,
        new Request(incomingRequest, {
            redirect: 'follow'
        })
    );

    return await fetch(outgoingRequest);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM