常用 ServerVariables 對照表
| 變數 | 範例值 | 說明 |
| SERVER_NAME | www.example.com | 主機名 (不含埠號) |
| SERVER_PORT | 80 | 埠號 |
| SCRIPT_NAME | /folder/page.asp | 虛擬路徑 (含檔名) |
| PATH_INFO | /folder/page.asp | 同 SCRIPT_NAME (IIS 版本差異) |
| QUERY_STRING | id=123&cat=5 | 查詢字串 (不含 ?) |
| HTTP_HOST | www.example.com:8080 | Host 標頭 (含埠號,含 www) |
| URL | /folder/page.asp | 同 SCRIPT_NAME (已淘汰) |
通用函式:取得完絕對 URL
Function GetFullURL(Optional includeQuery = True)
Dim protocol, host, port, path, qs
protocol = "http"
If Request.ServerVariables("HTTPS") = "on" Then protocol = "https"
host = Request.ServerVariables("SERVER_NAME")
port = Request.ServerVariables("SERVER_PORT")
If (protocol = "http" And port <> "80") Or (protocol = "https" And port <> "443") Then
host = host & ":" & port
End If
path = Request.ServerVariables("SCRIPT_NAME")
qs = ""
If includeQuery And Request.QueryString <> "" Then qs = "?" & Request.QueryString
GetFullURL = protocol & "://" & host & path & qs
End Function
通用函式:取得當前頁面基礎路徑 (不含查詢字串)
Function GetBaseURL()
GetBaseURL = GetFullURL(False)
End Function
通用函式:重建查詢字串 (可排除/修改特定參數)
Function BuildQueryString(excludeParams, replaceParams)
' excludeParams: 逗號分隔要排除的參數名,如 "page,sessionid"
' replaceParams: Dictionary 物件,指定要覆蓋/新增的參數
Dim dict, key, item, arrExclude, i, result
Set dict = Server.CreateObject("Scripting.Dictionary")
dict.CompareMode = 1 ' 二進位比較
' 載入現有 QueryString
For Each key In Request.QueryString
dict(key) = Request.QueryString(key)
Next
' 排除參數
If excludeParams <> "" Then
arrExclude = Split(excludeParams, ",")
For i = 0 To UBound(arrExclude)
dict.Remove Trim(arrExclude(i))
Next
End If
' 覆蓋/新增參數
If IsObject(replaceParams) Then
For Each key In replaceParams
dict(key) = replaceParams(key)
Next
End If
' 組裝
result = ""
For Each key In dict.Keys
If result <> "" Then result = result & "&"
result = result & Server.URLEncode(key) & "=" & Server.URLEncode(dict(key))
Next
If result <> "" Then result = "?" & result
BuildQueryString = result
End Function
使用範例
<%
' 1. 完整 URL
Response.Write "完整 URL: " & GetFullURL() & "
"
' 2. 分頁導航:保留其他參數,只換 page
Dim pageLinks, i
pageLinks = ""
For i = 1 To 10
pageLinks = pageLinks & "" & i & " "
Next
Response.Write "分頁: " & pageLinks & "
"
' 3. 表單重導時保留 returnUrl
Response.Redirect "login.asp" & BuildQueryString("", CreateDict("returnUrl", GetFullURL()))
Function CreateDict(key, val)
Dim d: Set d = Server.CreateObject("Scripting.Dictionary")
d.Add key, val
Set CreateDict = d
End Function
%>
安全提醒
- 輸出 URL 至 HTML 時務必
Server.HTMLEncode,防 XSS。
- 重導時驗證
returnUrl 為同網域,防開放式重導向攻擊。