代码之家  ›  专栏  ›  技术社区  ›  Brian Boatright

从VBScript中的HTTP_主机变量提取二级域的最佳方法

  •  2
  • Brian Boatright  · 技术社区  · 17 年前

    我只需要从request.servervariables(“HTTP_主机”)中提取域的第二级部分,最好的方法是什么?

    4 回复  |  直到 17 年前
        1
  •  1
  •   Tomalak    8 年前

    自从 HTTP_HOST 服务器变量只能包含有效的主机名,我们不需要关心 验证 字符串,只是为了找出它的结构。因此,regex保持相当简单,但在更广泛的上下文中无法可靠地工作。

    结构是 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
    
        2
  •  1
  •   Brian Boatright    17 年前
    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
    

        3
  •  0
  •   Haakon    16 年前

    刚刚检查了我租用的serverspace的子域上的差异,http_主机和server_名称都报告了包含子域的域名。

        4
  •  -1
  •   defeated    17 年前

    由于HTTP_主机头仅返回域(不包括任何子域),因此您应该能够执行以下操作:

    '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"
    
    推荐文章