我來為您提供幾個免費的解決方案來實現地理位置偵測和重定向功能:
方案一:使用 Cloudflare Workers(推薦)
優點:
- 完全免費(每天10萬次請求)
- 速度快、效能好
- 內建地理位置偵測
實作步驟:
- 註冊 Cloudflare 帳號並添加您的網域
- 建立一個 Worker 腳本:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
const country = request.cf.country
// 如果是根網域訪問
if (url.pathname === '/' || url.pathname === '') {
// 台灣用戶
if (country === 'TW') {
return Response.redirect('https://www.gloleadership.org/zh/', 302)
}
// 非台灣用戶
else {
return Response.redirect('https://www.gloleadership.org/us/', 302)
}
}
// 其他路徑正常訪問
return fetch(request)
}
方案二:使用 IPinfo.io API + JavaScript
優點:
- 免費方案每月5萬次請求
- 簡單易用
- 不需要後端伺服器
實作代碼(加入 Webflow 自訂代碼區塊):
<script>
// 只在首頁執行重定向
if (window.location.pathname === '/' || window.location.pathname === '') {
// 檢查是否已經重定向過(避免無限迴圈)
if (!sessionStorage.getItem('geoRedirected')) {
fetch('https://ipinfo.io/json?token=YOUR_FREE_TOKEN')
.then(response => response.json())
.then(data => {
sessionStorage.setItem('geoRedirected', 'true');
if (data.country === 'TW') {
window.location.href = 'https://www.gloleadership.org/zh/';
} else {
window.location.href = 'https://www.gloleadership.org/us/';
}
})
.catch(err => {
// 發生錯誤時預設導向美國版本
window.location.href = 'https://www.gloleadership.org/us/';
});
}
}
</script>
方案三:使用 ipapi.co 免費 API
優點:
- 完全免費,每月3萬次請求
- 不需要註冊即可使用
實作代碼:
<script>
if (window.location.pathname === '/' || window.location.pathname === '') {
if (!sessionStorage.getItem('geoRedirected')) {
fetch('https://ipapi.co/json/')
.then(response => response.json())
.then(data => {
sessionStorage.setItem('geoRedirected', 'true');
if (data.country_code === 'TW') {
window.location.href = 'https://www.gloleadership.org/zh/';
} else {
window.location.href = 'https://www.gloleadership.org/us/';
}
})
.catch(err => {
window.location.href = 'https://www.gloleadership.org/us/';
});
}
}
</script>
方案四:使用 Netlify 重定向規則
如果您願意將網站部署到 Netlify(免費):
_redirects 檔案配置:
/ /zh/ 302 Country=tw
/ /us/ 302
在 Webflow 中實施的步驟:
- 進入 Webflow 專案設定
- 找到 Custom Code 區塊
- 在 Head Code 或 Footer Code 中加入上述 JavaScript
- 發布網站
額外建議:
1. 添加語言切換按鈕
<div class="language-switcher">
<a href="/zh/">繁體中文</a>
<a href="/us/">English</a>
</div>
2. 使用 Cookie 記住用戶選擇
// 設置 cookie
function setLanguageCookie(lang) {
document.cookie = `preferred_lang=${lang};path=/;max-age=31536000`;
}
// 讀取 cookie
function getLanguageCookie() {
const match = document.cookie.match(/preferred_lang=([^;]+)/);
return match ? match[1] : null;
}
3. SEO 優化考量
在每個語言版本的頁面 <head> 中加入:
<link rel="alternate" hreflang="zh-TW" href="https://www.gloleadership.org/zh/" />
<link rel="alternate" hreflang="en-US" href="https://www.gloleadership.org/us/" />
<link rel="alternate" hreflang="x-default" href="https://www.gloleadership.org/us/" />
推薦方案:
對於您的需求,我最推薦方案一(Cloudflare Workers),因為:
- 完全免費且配額充足
- 效能最好(在 CDN 層級處理)
- 最可靠(不依賴第三方 API)
- 易於管理和修改
如果您需要更詳細的實施指導,請告訴我您選擇哪個方案,我可以提供更具體的步驟說明!