0

我使用 Cloudflare worker 将访问者重定向到正确的网站版本,如下所示:

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

  /**
   * Respond to the request
   * @param {Request} request
   */
  async function handleRequest(request) {
    country_code = request.headers.get('CF-IPCountry');
    var link;

  switch(request.headers.get('CF-IPCountry')) {
    case 'TW':  // Taiwan
    link = "https://www.website.com/twn";
        break;
    case 'TH':  // Thailand
    link = "https://www.website.com/tha";
        break;
    case 'GB':  // United Kingdom
    link = "https://www.website.com/gbr";
        break;
    case 'US':  // United States
    link = "https://www.website.com/us";
        break;
    default:
      link = "https://www.website.com/rotw" // Rest of the world
  }

  return new Response('', {
          status: 301,
          headers: {
            'Location': link
          }
        })
  }

问题是谷歌机器人被重定向到 website.com/us,因此我的谷歌入口将传入的访问者直接指向 /us 网站。有没有办法从国家重定向脚本中排除搜索机器人并将它们直接路由到 website.com 而不是 website.com/countrycode?

4

1 回答 1

3

你能做这样的事情吗。我没有测试过这个。

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

  /**
   * Respond to the request
   * @param {Request} request
   */
  async function handleRequest(request) {
    country_code = request.headers.get('CF-IPCountry');
    var link;

  let userAgent = request.headers.get('User-Agent') || ''
  if (userAgent.includes('Googlebot')) {
    return new Response('', {
          status: 301,
          headers: {
            'Location': "https://www.website.com/"
          }
        })
  }

  switch(request.headers.get('CF-IPCountry')) {
    case 'TW':  // Taiwan
    link = "https://www.website.com/twn";
        break;
    case 'TH':  // Thailand
    link = "https://www.website.com/tha";
        break;
    case 'GB':  // United Kingdom
    link = "https://www.website.com/gbr";
        break;
    case 'US':  // United States
    link = "https://www.website.com/us";
        break;
    default:
      link = "https://www.website.com/rotw" // Rest of the world
  }

  return new Response('', {
          status: 301,
          headers: {
            'Location': link
          }
        })
  }
于 2020-01-29T09:21:29.597 回答