大型入口網站或多城市站點常需根據訪客 IP 所屬城市、IP 區段或特定 IP,自動導向對應的城市子站或個性化頁面。本文示範透過實作 IHttpModule 在管線早期攔截請求,結合純真 IP 資料庫 (QQWry.dat) 進行高效率 IP 歸屬查詢,並支援 Nginx 反向代理下的真實 IP 取得。
BeginRequest 事件,最早介入請求管線。HTTP_X_REAL_IP、HTTP_X_FORWARDED_FOR、HTTP_VIA 標頭 (Nginx/代理環境),最後回退 REMOTE_ADDR。QQWryLocator 讀取 qqwry.dat,毫秒級查詢城市資訊。Response.Redirect。WebsiteSkipHttpModule.csusing System;
using System.Web;
using System.Text.RegularExpressions;
using NetOpen_System.Component.QQWry; // 純真 IP 元件
namespace NetOpen_System.Component
{
public sealed class WebsiteSkipHttpModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.BeginRequest += Context_BeginRequest;
}
private void Context_BeginRequest(object sender, EventArgs e)
{
try
{
var request = HttpContext.Current.Request;
var response = HttpContext.Current.Response;
// 1. 取得真實客戶端 IP (支援 Nginx 反向代理)
string ip = GetClientRealIP(request);
// 2. 查詢 IP 所屬城市
string ipDataPath = request.ServerVariables["APPL_PHYSICAL_PATH"] + @"IpData\qqwry.dat";
var qqWry = new QQWryLocator(ipDataPath);
var ipLocation = qqWry.Query(ip);
string city = ipLocation.Country; // 純真資料庫中 Country 欄位通常儲存省份/城市
// 3. 排除特定 User-Agent (如爬蟲)
if (IsExcludedUserAgent(request.UserAgent))
return;
// 4. 套用導向規則
var config = WebsiteSkipConfiguration.GetConfig();
foreach (var rule in config.SkipedUrls.UrlList)
{
if (city.Contains(rule.IpCity)) // 城市符合
{
string currentUrl = request.Url.AbsoluteUri;
// 檢查來源 URL 條件與排除關鍵字
if (string.IsNullOrEmpty(rule.UrlFrom) ||
(currentUrl.Contains(rule.UrlFrom) && !currentUrl.Contains(rule.OutKeyWord)))
{
if (!string.IsNullOrEmpty(rule.UrlTo))
{
response.Redirect(rule.UrlTo, true);
break; // 導向後結束處理
}
}
}
}
}
catch (Exception ex)
{
// 記錄錯誤日誌,避免模組異常導致整站掛掉
// LogHelper.Error(ex);
}
}
private string GetClientRealIP(HttpRequest request)
{
string ip = string.Empty;
if (request.ServerVariables["HTTP_X_REAL_IP"] != null)
ip = request.ServerVariables["HTTP_X_REAL_IP"];
else if (request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(',')[0].Trim(); // 取第一個
else if (request.ServerVariables["HTTP_VIA"] != null)
ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"]; // 部分代理只設 VIA
else
ip = request.ServerVariables["REMOTE_ADDR"];
return ip;
}
private bool IsExcludedUserAgent(string userAgent)
{
if (string.IsNullOrEmpty(userAgent)) return false;
var excludeList = WebsiteSkipConfiguration.GetConfig().ExcludeUserAgents.ExcludeUserAgentList;
foreach (var ua in excludeList)
{
if (userAgent.Contains(ua.Keyword))
return true;
}
return false;
}
}
}
WebsiteSkip.config<configuration>
<configSections>
<section name="WebsiteSkip" type="NetOpen_System.Component.WebsiteSkipConfiguration, NetOpen_System" />
</configSections>
<WebsiteSkip>
<ExcludeUserAgents>
<add keyword="Baiduspider" />
<add keyword="Googlebot" />
<add keyword="360Spider" />
</ExcludeUserAgents>
<SkipedUrls>
<add IpCity="北京" UrlFrom="https://www.example.com/" UrlTo="https://bj.example.com/" OutKeyWord="bj.example.com" />
<add IpCity="上海" UrlFrom="https://www.example.com/" UrlTo="https://sh.example.com/" OutKeyWord="sh.example.com" />
</SkipedUrls>
</WebsiteSkip>
</configuration>
<system.webServer>
<modules>
<add name="WebsiteSkipModule" type="NetOpen_System.Component.WebsiteSkipHttpModule, NetOpen_System" />
</modules>
</system.webServer>
<!-- IIS 6 / Classic 模式 -->
<system.web>
<httpModules>
<add name="WebsiteSkipModule" type="NetOpen_System.Component.WebsiteSkipHttpModule, NetOpen_System" />
</httpModules>
</system.web>
qqwry.dat 替換,確保 IP 歸屬準確性。IHttpContextAccessor 取得請求,配合 IP2Location、MaxMind GeoIP2 等 NuGet 套件查詢。透過 IHttpModule 攔截 `BeginRequest`,結合高效能的純真 IP 資料庫與靈活的規則配置,即可實現企業級的 IP 導向功能。注意代理環境下的真實 IP 取得、爬蟲排除與模組效能優化,是生產環境穩定運行的關鍵。