首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 基於 UrlRewrite 實現防盜鏈:配置檔、Global.asax 與 IIS 設定完整教學

     編輯:ASP.NET 基礎

核心原理

在 Application_BeginRequest 攔截請求,依 Referer、Cookie、登入狀態判斷是否允許下載;不允許時用 Context.RewritePath 導向驗證頁或錯誤頁。配合 IIS 將目標副檔名(如 .rar、.zip)對應到 aspnet_isapi.dll,讓靜態檔案也經過 ASP.NET 管線。

1. 配置檔 DownLoad.config

<?xml version="1.0" encoding="utf-8"?>
<DownLoad>
  <CheckType>3</CheckType> <!-- 1=Referer, 2=Cookie, 3=兩者皆驗 -->
  <CookiesName>AuthToken</CookiesName>
  <UrlPattern><![CDATA[//(.+?)/.rar]]></UrlPattern>
  <UrlReplace><![CDATA[/Error/Unauthorized.aspx?file=$1.rar]]></UrlReplace>
  <AllowHost><![CDATA[example.com|partner.com]]></AllowHost>
</DownLoad>

2. Global.asax 攔截邏輯

void Application_BeginRequest(object sender, EventArgs e)
{
    var configPath = ConfigurationManager.AppSettings["DownLoadConfig"];
    if (string.IsNullOrEmpty(configPath)) return;

    var doc = new XmlDocument();
    doc.Load(Server.MapPath(configPath));

    int checkType = int.Parse(doc.SelectSingleNode("DownLoad/CheckType")?.InnerText ?? "1");
    string cookieName = doc.SelectSingleNode("DownLoad/CookiesName")?.InnerText ?? "AuthToken";
    string allowHosts = doc.SelectSingleNode("DownLoad/AllowHost")?.InnerText ?? "";
    string urlPattern = doc.SelectSingleNode("DownLoad/UrlPattern")?.InnerText ?? "";
    string urlReplace = doc.SelectSingleNode("DownLoad/UrlReplace")?.InnerText ?? "";

    bool allowReferer = false;
    if (Request.UrlReferrer != null)
    {
        string refererHost = Request.UrlReferrer.Host.ToLower();
        allowReferer = allowHosts.Split('|').Any(h => h.Equals(refererHost, StringComparison.OrdinalIgnoreCase));
    }

    bool allowCookie = !string.IsNullOrEmpty(Request.Cookies[cookieName]?.Value);

    bool allow = checkType switch
    {
        1 => allowReferer,
        2 => allowCookie,
        3 => allowReferer && allowCookie,
        _ => false
    };

    if (!allow && Regex.IsMatch(Request.RawUrl, urlPattern, RegexOptions.IgnoreCase))
    {
        string newUrl = Regex.Replace(Request.RawUrl, urlPattern, urlReplace, RegexOptions.IgnoreCase);
        Context.RewritePath(newUrl);
    }
}

3. Web.config 註冊配置路徑

<appSettings>
  <add key="DownLoadConfig" value="~/DownLoad.config" />
</appSettings>

4. IIS 設定(關鍵步驟)

IIS 6 / 7 經典模式

  1. 網站 → 屬性 → 主目錄 → 設定 → 對應。
  2. 新增:副檔名 .rar,執行檔 C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll(依實際 .NET 版本)。
  3. 取消勾選「確認檔案是否存在」。

IIS 7+ 整合模式

<system.webServer>
  <handlers>
    <add name="StaticFileRewrite" path="*.rar" verb="*"
         type="System.Web.HttpApplication" preCondition="integratedMode" />
  </handlers>
</system.webServer>

5. 效能與安全補強

  • 簽名 URL: 產生帶時效、防篡改的下載連結(如 /download/file.rar?token=xxx&exp=timestamp),不依賴 Referer(易偽造)。
  • 輸出檔案: 使用 Response.TransmitFile 或 FileStream 分塊傳輸,支援斷點續傳。
  • 記錄稽核: 記錄 IP、User-Agent、Referer、下載結果,異常告警。

現代化替代方案

ASP.NET Core 可用 Middleware + PhysicalFileProvider + Signed URL 實現更簡潔、高效能的防盜鏈,無需 IIS 特殊映射。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved