2008-10-13 53 views

回答

1

這可以通過正則表達式來解決。

由於HTTP_HOST服務器變量只能包含有效的主機名,所以我們不需要關心驗證這個字符串,只能找出它的結構。因此,正則表達式保持相當簡單,但在更廣泛的環境下無法可靠地工作。

結構分別爲第三級,第二級和第一級(頂級)域的3.2.1

頂級域名可以有2個字母(如.com.de)或概念上的組合,如.co.uk。這不是技術上的 TLD了,但我認爲你並不是真的有興趣將co作爲許多英國主機名的第二級域名。

因此,我們必須

  • 可選:在啓動(子域),一個點的各種事情= ^(.*?)\.?
  • 要求:中間一塊(二級域名),一個點= (\w+)\.
  • 需要:短位(或兩個短位)結尾= (\w{2,}(?:\.\w{2})?)$

這三樣東西將在組1,2被捕獲,和3

Dim re, matches, match 

Set re = New RegExp 

re.Pattern = "^(.*?)\.?(\w+)\.(\w{2,}(?:\.\w{2})?)$" 

Set matches = re.Execute(Request.ServerVariables("HTTP_HOST")) 

If matches.Count = 1 Then 
    Set match = matches(0) 

    ' assuming "images.res.somedomain.co.uk" 
    Response.Write match.SubMatches(0) & "<br>" ' will be "images.res" 
    Response.Write match.SubMatches(1) & "<br>" ' will be "somedomain" 
    Response.Write match.SubMatches(2) & "<br>" ' will be "co.uk" 

    ' assuming "somedomain.com" 
    Response.Write match.SubMatches(0) & "<br>" ' will be "" 
    Response.Write match.SubMatches(1) & "<br>" ' will be "somedomain" 
    Response.Write match.SubMatches(2) & "<br>" ' will be "com" 
Else 
    ' You have an IP address in HTTP_HOST 
End If 
+0

HTPT_HOST頭不應該包含子域。這是無稽之談。要解析子域名,他需要使用SERVER_NAME標頭。 鑑於網址:http://cdn.domain.co.uk,HTTP_HOST應返回「domain.co.uk」,而SERVER_NAME應返回「cdn.domain.co.uk」 – defeated 2008-10-17 00:12:39

+0

當然,HTTP_HOST包含子域。去看看它。 – Tomalak 2008-10-17 05:53:34

1
If Len(strHostDomain) > 0 Then  
    aryDomain = Split(strHostDomain,".") 

    If uBound(aryDomain) >= 1 Then 
     str2ndLevel = aryDomain(uBound(aryDomain)-1) 
     strTopLevel = aryDomain(uBound(aryDomain))   
     strDomainOnly = str2ndLevel & "." & strTopLevel 
    End If 
End If 

適用於我所需要的,但它不處理.co.uk或其他域,其中有兩個部分的頂級預期。

-1

由於HTTP_HOST頭只返回域(不包括任何的子域),你應該能夠做到以下幾點:

'example: sample.com 
'example: sample.co.uk 
host = split(request.serverVariables("HTTP_HOST"), ".") 
host(0) = "" 'clear the "sample" part 

extension = join(host, ".") 'put it back together, ".com" or ".co.uk" 
0

剛纔檢查區域上的區別了我租serverspace兩者HTTP_HOST並且server_name報告包含子域的域名。

相關問題