You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:基于访客IP地域实现主站到指定子域名的重定向

Got it, let's tackle this problem since your server doesn't have GeoIP installed—no worries, we have solid workarounds that don't require server-side extensions. Below are three reliable approaches sorted by ease of implementation and reliability:

方案1:前端JavaScript重定向(最快上手)

This method works entirely in the browser, no backend config needed. We'll use a free IP geolocation API to detect the visitor's region, then redirect accordingly.

Add this code to the <head> section of your main site (mysite.com)—place it early to minimize load time before redirect:

document.addEventListener('DOMContentLoaded', function() {
  // Fetch geolocation data from a free API
  fetch('https://ip-api.com/json/')
    .then(response => response.json())
    .then(data => {
      let targetDomain = 'mysite.com'; // Fallback to main site
      
      // Check region
      if (data.countryCode === 'US') {
        targetDomain = 'us.mysite.com';
      } else if (data.continentCode === 'EU') {
        targetDomain = 'eu.mysite.com';
      }
      
      // Avoid infinite redirect loops
      const currentDomain = window.location.hostname;
      if (currentDomain !== targetDomain) {
        // Preserve the current page path and query parameters
        const redirectUrl = `https://${targetDomain}${window.location.pathname}${window.location.search}`;
        window.location.replace(redirectUrl);
      }
    })
    .catch(error => {
      // If API fails, stay on main site
      console.error('Geolocation lookup failed:', error);
    });
});

Notes:

  • The API used here has free limits for non-commercial use—adjust if you need higher throughput.
  • Add a <noscript> tag for users who disable JavaScript:
    <noscript>
      <p>Please enable JavaScript to access the region-specific version of our site, or visit <a href="https://mysite.com">our main site</a>.</p>
    </noscript>
    
方案2:后端PHP重定向(works even with JS disabled)

If you have PHP support on your server, this method handles redirects before the page loads, making it more reliable for users with JS turned off.

Place this code at the very top of your index.php file (or a global include file):

<?php
// Prevent loop redirects by checking current domain
$currentHost = $_SERVER['HTTP_HOST'];
$validHosts = ['mysite.com', 'us.mysite.com', 'eu.mysite.com'];

if (!in_array($currentHost, $validHosts)) {
    header('Location: https://mysite.com' . $_SERVER['REQUEST_URI']);
    exit;
}

// Skip redirect if already on a target subdomain
if ($currentHost === 'us.mysite.com' || $currentHost === 'eu.mysite.com') {
    exit;
}

// Fetch geolocation data
$userIp = $_SERVER['REMOTE_ADDR'];
$apiResponse = file_get_contents("https://ip-api.com/json/{$userIp}");
$geoData = json_decode($apiResponse, true);

$targetHost = 'mysite.com';
if ($geoData && isset($geoData['countryCode'])) {
    if ($geoData['countryCode'] === 'US') {
        $targetHost = 'us.mysite.com';
    } elseif (isset($geoData['continentCode']) && $geoData['continentCode'] === 'EU') {
        $targetHost = 'eu.mysite.com';
    }
}

// Execute redirect
if ($targetHost !== $currentHost) {
    header("Location: https://{$targetHost}{$_SERVER['REQUEST_URI']}");
    exit;
}
?>

Notes:

  • If file_get_contents is disabled on your server, replace it with a cURL call:
    $ch = curl_init("https://ip-api.com/json/{$userIp}");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $apiResponse = curl_exec($ch);
    curl_close($ch);
    
  • Add caching (e.g., via sessions or file storage) to reduce API calls and improve speed.
方案3:CDN-powered redirects(most reliable & scalable)

If you use a CDN like Cloudflare, CloudFront, or Fastly, they include built-in geolocation tools that don't rely on your server's setup. This is the best option for high-traffic sites.

Example with Cloudflare Workers:

Create a new Worker and deploy this code:

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

async function handleRequest(request) {
  const url = new URL(request.url);
  const currentHost = url.hostname;
  
  // Skip redirect if already on target subdomain
  if (currentHost === 'us.mysite.com' || currentHost === 'eu.mysite.com') {
    return fetch(request);
  }
  
  // Get geolocation data from Cloudflare's request headers
  const countryCode = request.headers.get('cf-ipcountry');
  const continentCode = request.headers.get('cf-ipcontinent');
  
  let targetHost = 'mysite.com';
  if (countryCode === 'US') {
    targetHost = 'us.mysite.com';
  } else if (continentCode === 'EU') {
    targetHost = 'eu.mysite.com';
  }
  
  // Redirect to the correct subdomain
  url.hostname = targetHost;
  return Response.redirect(url.toString(), 302); // Use 301 for permanent redirects
}

Alternatively, use Cloudflare's Page Rules (no code needed) to set up region-based redirects via their dashboard.


Final Tips:

  • Use 302 Temporary Redirect if you might adjust your region rules later; use 301 Permanent Redirect only if the rules are fixed (it's cached by browsers).
  • Test with a VPN to simulate visitors from different regions.

内容的提问来源于stack exchange,提问作者user1812111

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:46:53