萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 獲取當前完整 URL 的標準方法 (含 HTTPS/端口判斷)

核心代碼

<%
Function GetCurrentURL()
    Dim strURL, strProtocol, strServerName, strServerPort, strScriptName, strQueryString
    
    ' 1. 協議
    If LCase(Request.ServerVariables("HTTPS")) = "on" Then
        strProtocol = "https://"
    Else
        strProtocol = "https://"
    End If
    
    ' 2. 服務器名/地址
    strServerName = Request.ServerVariables("SERVER_NAME")
    
    ' 3. 端口 (非標準端口需顯示)
    strServerPort = Request.ServerVariables("SERVER_PORT")
    If strServerPort <> "80" And strServerPort <> "443" Then
        strServerName = strServerName & ":" & strServerPort
    End If
    
    ' 4. 腳本路徑
    strScriptName = Request.ServerVariables("SCRIPT_NAME")
    ' 或 URL 路徑 (含虛擬目錄): Request.ServerVariables("URL")
    
    ' 5. 查詢字符串
    strQueryString = Request.ServerVariables("QUERY_STRING")
    If strQueryString <> "" Then strQueryString = "?" & strQueryString
    
    ' 組合
    GetCurrentURL = strProtocol & strServerName & strScriptName & strQueryString
End Function

' 使用
Response.Write "當前完整 URL: " & GetCurrentURL()
%>

關鍵 ServerVariables 變量對照表

變量名含義示例
HTTPS是否 HTTPS 連接 ("on"/"off")"on"
SERVER_NAME服務器主機名/IP"www.example.com"
SERVER_PORT服務器端口"80", "443", "8080"
SCRIPT_NAME當前執行腳本的虛擬路徑"/app/page.asp"
URL請求的 URL 路徑 (含虛擬目錄,不含查詢串)"/app/page.asp"
QUERY_STRING查詢字符串 (不含 ?)"id=123&cat=5"
HTTP_HOSTHost Header 值 (含端口如果非標準)"www.example.com:8080"
REQUEST_URI完整請求 URI (Apache 常有,IIS 需 ISAPI Rewrite 支持)"/app/page.asp?id=123"

簡化版 (利用 HTTP_HOST)

<%
Function GetCurrentURLSimple()
    Dim protocol, host, url, query
    protocol = IIf(LCase(Request.ServerVariables("HTTPS")) = "on", "https://", "https://")
    host = Request.ServerVariables("HTTP_HOST") ' 已含端口(非標準)
    url = Request.ServerVariables("URL")        ' 或 SCRIPT_NAME
    query = Request.ServerVariables("QUERY_STRING")
    If query <> "" Then query = "?" & query
    GetCurrentURLSimple = protocol & host & url & query
End Function

' IIf 模擬 (VBScript 無三元運算符)
Function IIf(cond, trueVal, falseVal)
    If cond Then IIf = trueVal Else IIf = falseVal
End Function
%>

應用場景

  • 生成分享鏈接、郵件中的絕對鏈接。
  • 支付回調通知地址 (notify_url)。
  • OAuth 重定向 URI。
  • canonical 標簽、站點地圖生成。
  • 跨域配置、CORS Origin 驗證。

注意事項

  1. 反向代理/負載均衡器:可能隱藏真實客戶端 IP 和原始 Host。需配置代理轉發 X-Forwarded-Proto, X-Forwarded-Host, X-Forwarded-Port,並在 ASP 中優先讀取這些 Header (via Request.ServerVariables("HTTP_X_FORWARDED_PROTO") 等)。
  2. IIS 版本差異:舊版 IIS 可能不支持 HTTP_HOST,建議組合 SERVER_NAME + SERVER_PORT。
  3. URL 重寫:若使用 ISAPI_Rewrite / URL Rewrite Module,SCRIPT_NAME/URL 可能指向重寫後的內部路徑,HTTP_X_REWRITE_URL 可能保存原始 URL。

結語

通過 Request.ServerVariables 組合協議、主機、端口、路徑、查詢串,可在 ASP 中可靠構建當前完整 URL。封裝為通用函數並在項目中統一調用,能有效避免硬編碼 URL 帶來的部署遷移問題。

copyright © 萬盛學電腦網 all rights reserved