简体   繁体   中英

Redirect from one domain to another in cloudflare workers does not work

I need to configure that requests that match the domain1.com/test/ / pattern be serviced by the domain2.com application. Tried to configure it as follows. Created a worker, added code

'''

const redirectMap = new Map([
  ['/test1', 'domain2.com'],
])

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

async function handleRequest(request) {
  let requestURL = new URL(request.url)
  let path       = requestURL.pathname.split('/redirect')[1]
    let location   = redirectMap.get(path)

  if (location) {
    return Response.redirect(location, 301)
  }
  
  return fetch(request)
}

'''

After that in the domain settings, I added a worker and specified the site domain1.com/test/*. But it did not work. Help please. Uses instructions https://www.cloudsavvyit.com/3660/how-to-create-a-cloudflare-worker-to-redirect-requests/

You have 2 options to add redirects in Cloudflare: Page Rules and Workers.

In both cases source domain's DNS records must be proxied (orange cloud ON).

Workers

  1. Open the source domain page in Cloudflare dashboard.

  2. Go to the Workers tab.

  3. Manage Workers -> Create a Worker

  4. Add the following code. On matching paths it will redirect a visitor to the target URL. If there's no match request will be sent to the origin (source-domain.com).

const redirectHttpCode = 301
const redirectMap = new Map([
  ['/redirecting-path', 'https://target-domain.com'],
])

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

/**
 * Respond to the request
 * @param {Request} request
 */
async function handleRequest(request) {
  const url = new URL(request.url)
  const { pathname } = url

  const targetUrl = redirectMap.get(pathname)
  if (targetUrl) {
    return Response.redirect(targetUrl, redirectHttpCode)
  }

  return fetch(request)
}
  1. Go back to the Workers tab of your source domain -> Add route . Set Route to *.source-domain.com/* (if you're going to match multiple redirect paths) or *.source-domain.com/redirecting-path (if there's just one). Select the worker you created in step 4. Save .

在此处输入图片说明

Page Rules

If you're not forced to use Workers for redirection, you can leverage Cloudflare's Page Rules feature which is an easier code-free way to do it.

  1. Open the source domain page in Cloudflare dashboard.

  2. Go to the Page Rules tab.

  3. Create a new page rule. Enter source domain in the URL match field. You can add path if needed. Choose 301 or 302 HTTP code - whichever makes sense in your case. Here's an example redirect configuration:

在此处输入图片说明

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