求助:如何基于IP地址实现网站按地域跳转至对应语言域名
Got it, let's walk through exactly how to build this geolocation-based redirect for your personal site. You’re already on the right track with ip-api.com—we’ll turn that API into a working solution step by step.
1. 前端JavaScript实现(快速上手,适合静态站点)
This is the easiest way to get started if you’re working with a static HTML/CSS/JS site. We’ll fetch the visitor’s location data, check if they’re in Estonia, and redirect accordingly. We’ll also add safeguards to avoid infinite loops.
Here’s the full code you can drop into your main page’s <script> tag:
// Define your target domains first const estonianDomain = 'et.domain.ee'; const englishDomain = 'en.domain.ee'; const currentHost = window.location.hostname; // Skip redirect if we're already on one of the target domains if (currentHost === estonianDomain || currentHost === englishDomain) { return; } // Fetch geolocation data from ip-api.com fetch('https://ip-api.com/json') // Use HTTPS to avoid mixed-content issues on secure sites .then(response => response.json()) .then(data => { // Check the country code (Estonia's code is "EE") if (data.countryCode === 'EE') { window.location.href = `https://${estonianDomain}`; } else { window.location.href = `https://${englishDomain}`; } }) .catch(error => { // Fallback to English if the API call fails (e.g., network issues) console.error('Failed to fetch location data:', error); window.location.href = `https://${englishDomain}`; });
Key notes for this approach:
- HTTPS matters: If your main site uses HTTPS, make sure to call
https://ip-api.com/json(not HTTP) to avoid browser mixed-content errors. - Rate limits: ip-api’s free tier allows up to 45 requests per minute per IP, which is more than enough for a personal site.
- Fallback plan: The
catchblock ensures visitors still get a working site even if the API is down.
2. 后端实现(更可靠,适合动态站点)
If you’re using a backend framework (like Node.js, PHP, or Python), this approach is better—it’s more secure, avoids frontend API limits, and gets a more accurate visitor IP.
Here’s an example with Node.js/Express:
const express = require('express'); const app = express(); const fetch = require('node-fetch'); app.get('/', async (req, res) => { // Get the visitor's IP address from the request const visitorIp = req.ip; try { // Fetch location data using the visitor's IP const apiResponse = await fetch(`https://ip-api.com/json/${visitorIp}`); const locationData = await apiResponse.json(); // Redirect based on country code if (locationData.countryCode === 'EE') { res.redirect(302, 'https://et.domain.ee'); // 302 is temporary redirect (good for localization) } else { res.redirect(302, 'https://en.domain.ee'); } } catch (error) { console.error('Location lookup failed:', error); res.redirect(302, 'https://en.domain.ee'); } }); app.listen(3000, () => { console.log('Server running on port 3000'); });
For PHP, the logic is similar—you’d use file_get_contents() or cURL to call the API, then check the country code before redirecting with header("Location: ...").
3. Critical Extra: Add a Manual Language Switch
IP geolocation isn’t 100% perfect (e.g., someone traveling in Estonia might prefer English). Always add a manual switch link on both domains:
<p>Language Switch: <a href="https://et.domain.ee">Eesti keel</a> | <a href="https://en.domain.ee">English</a></p>
Final Checks
- Make sure both
et.domain.eeanden.domain.eeare properly configured in your DNS settings and point to the correct site versions. - Test the redirects using a VPN or proxy to simulate visitors from Estonia and other countries.
内容的提问来源于stack exchange,提问作者Dexx

