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).
Open the source domain page in Cloudflare dashboard.
Go to the Workers
tab.
Manage Workers
->
Create a Worker
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)
}
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
.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.
Open the source domain page in Cloudflare dashboard.
Go to the Page Rules
tab.
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.