Notes

Redirect a WordPress site using Cloudflare Workers and geolocation data

Edit on GitHub

WordPress
2 minutes

Basic worker

1addEventListener('fetch', (event) => {
2  event.respondWith(handleRequest(event.request))
3})
4
5async function handleRequest(request) {
6  return new Response('Hello worker!', {
7    headers: { 'content-type': 'text/plain' },
8  })
9}

Geolocation: Hello World

 1// Get all geolocation data fields and display them in HTML.
 2
 3addEventListener('fetch', (event) => {
 4  event.respondWith(handleRequest(event.request))
 5})
 6
 7async function handleRequest(request) {
 8  let html_content = ''
 9  let html_style = 'body{padding:6em; font-family: sans-serif;} h1{color:#f6821f}'
10
11  html_content += '<p> Colo: ' + request.cf.colo + '</p>'
12  html_content += '<p> Country: ' + request.cf.country + '</p>'
13  html_content += '<p> City: ' + request.cf.city + '</p>'
14  html_content += '<p> Continent: ' + request.cf.continent + '</p>'
15  html_content += '<p> Latitude: ' + request.cf.latitude + '</p>'
16  html_content += '<p> Longitude: ' + request.cf.longitude + '</p>'
17  html_content += '<p> PostalCode: ' + request.cf.postalCode + '</p>'
18  html_content += '<p> MetroCode: ' + request.cf.metroCode + '</p>'
19  html_content += '<p> Region: ' + request.cf.region + '</p>'
20  html_content += '<p> RegionCode: ' + request.cf.regionCode + '</p>'
21  html_content += '<p> Timezone: ' + request.cf.timezone + '</p>'
22
23  let html = `
24<!DOCTYPE html>
25<body>
26  <head>
27    <title> Geolocation: Hello World </title>
28    <style> ${html_style} </style>
29  </head>
30  <h1>Geolocation: Hello World!</h1>
31  <p>You now have access to geolocation data about where your user is visiting from.</p>
32  ${html_content}
33</body>`
34
35  return new Response(html, {
36    headers: {
37      'content-type': 'text/html;charset=UTF-8',
38    },
39  })
40}

Country code redirect

 1// Redirect a response based on the country code in the header of a visitor.
 2
 3/**
 4 * A map of the URLs to redirect to
 5 * @param {Object} countryMap
 6 */
 7const countryMap = {
 8  US: 'https://example.com/us',
 9  EU: 'https://eu.example.com/',
10}
11/**
12 * Returns a redirect determined by the country code
13 * @param {Request} request
14 */
15function redirect(request) {
16  // Use the cf object to obtain the country of the request
17  // more on the cf object: https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties
18  const country = request.cf.country
19
20  if (country != null && country in countryMap) {
21    const url = countryMap[country]
22    return Response.redirect(url)
23  } else {
24    return fetch(request)
25  }
26}
27
28addEventListener('fetch', (event) => {
29  event.respondWith(redirect(event.request))
30})