Reescritura de dirección url IIS Asp clásico

Código ASP clásico

Un programador ASP clásico puede generar algunas soluciones para optimizar un blog creado con ASP clásico y facilitar su indexación en los motores de búsqueda. La solución es combinar la potencia de ASP clásico con el módulo de reescritura de URL de IIS (IIS URL Rewrite) para generar dinámicamente archivos Robots.txt y Sitemap.xml.

Para poder escribir la sintaxis de los archivos Robots.txt y Sitemap.xml, empleamos los archivos Robots.asp y Sitemap.asp que generan la sintaxis correcta y las URL específicas para el dominio.

Para esta solución usamos ASP clásico para crear los archivos porque permite que el código se ejecute sin tener que cargar ningún framework adicional, lo cual incrementa notablemente su rendimiento. En caso de haber utilizado ASP.NET o PHP, requeriría una sobrecarga adicional que en realidad no es necesaria.

Este ejemplo esta creado específicamente para sitios con contenido estático. Para ello, el código analiza la estructura del directorio físico de las URL del sitio web y se especificó un intervalo semanal para que los motores de búsqueda vuelvan a visitar el sitio web.

Se necesitan 2 archivos de ASP clásico y uno web.config:

    Un archivo Robots.asp al que URL Rewrite enviará solicitudes de Robots.txt
    Un archivo Sitemap.asp al que URL Rewrite enviará solicitudes de Sitemap.xml
    Un archivo Web.config que contiene las reglas de reescritura de URL

Paso 1: creación del archivo Robots.asp

Debe guardar el siguiente ejemplo de código como Robots.asp en la raíz de su sitio web; esta página se ejecutará cada vez que alguien solicite el archivo Robots.txt para su sitio web. Este ejemplo es muy simple: busca el nombre de host solicitado y lo usa para crear dinámicamente la URL absoluta para el archivo Sitemap.xml del sitio web.


 

<%
    Option Explicit
    On Error Resume Next
    
    Dim strUrlRoot
    Dim strHttpHost
    Dim strUserAgent

    Response.Clear
    Response.Buffer = True
    Response.ContentType = "text/plain"
    Response.CacheControl = "public"

    Response.Write "# Robots.txt" & vbCrLf
    Response.Write "# For more information on this file see:" & vbCrLf
    Response.Write "# http://www.robotstxt.org/" & vbCrLf & vbCrLf

    strHttpHost = LCase(Request.ServerVariables("HTTP_HOST"))
    strUserAgent = LCase(Request.ServerVariables("HTTP_USER_AGENT"))
    strUrlRoot = "http://" & strHttpHost

    Response.Write "# Define the sitemap path" & vbCrLf
    Response.Write "Sitemap: " & strUrlRoot & "/sitemap.xml" & vbCrLf & vbCrLf

    Response.Write "# Make changes for all web spiders" & vbCrLf
    Response.Write "User-agent: *" & vbCrLf
    Response.Write "Allow: /" & vbCrLf
    Response.Write "Disallow: " & vbCrLf
    Response.End
%>


Paso 2: creación del archivo Sitemap.asp

El siguiente archivo de ejemplo también es bastante simple y guardaría este código como Sitemap.asp en la raíz de su sitio web. Hay una sección en el código donde recorre el sistema de archivos en busca de archivos con la extensión de archivo *.html y solo crea direcciones URL para esos archivos. Si desea que se incluyan otros archivos en sus resultados, o si desea cambiar el código de contenido estático a dinámico, aquí es donde deberá actualizar el archivo en consecuencia.

 

<%
    Option Explicit
    On Error Resume Next
    
    Response.Clear
    Response.Buffer = True
    Response.AddHeader "Connection", "Keep-Alive"
    Response.CacheControl = "public"
    
    Dim strFolderArray, lngFolderArray
    Dim strUrlRoot, strPhysicalRoot, strFormat
    Dim strUrlRelative, strExt

    Dim objFSO, objFolder, objFile

    strPhysicalRoot = Server.MapPath("/")
    Set objFSO = Server.CreateObject("Scripting.Filesystemobject")
    
    strUrlRoot = "http://" & Request.ServerVariables("HTTP_HOST")
    
    ' Check for XML or TXT format.
    If UCase(Trim(Request("format")))="XML" Then
        strFormat = "XML"
        Response.ContentType = "text/xml"
    Else
        strFormat = "TXT"
        Response.ContentType = "text/plain"
    End If

    ' Add the UTF-8 Byte Order Mark.
    Response.Write Chr(CByte("&hEF"))
    Response.Write Chr(CByte("&hBB"))
    Response.Write Chr(CByte("&hBF"))
    
    If strFormat = "XML" Then
        Response.Write "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbCrLf
        Response.Write "<urlset xmlns=""http://www.sitemaps.org/schemas/sitemap/0.9"">" & vbCrLf
    End if
    
    ' Always output the root of the website.
    Call WriteUrl(strUrlRoot,Now,"weekly",strFormat)

    ' --------------------------------------------------
    ' This following section contains the logic to parse
    ' the directory tree and return URLs based on the
    ' static *.html files that it locates. This is where
    ' you would change the code for dynamic content.
    ' -------------------------------------------------- 
    strFolderArray = GetFolderTree(strPhysicalRoot)

    For lngFolderArray = 1 to UBound(strFolderArray)
        strUrlRelative = Replace(Mid(strFolderArray(lngFolderArray),Len(strPhysicalRoot)+1),"\","/")
        Set objFolder = objFSO.GetFolder(Server.MapPath("." & strUrlRelative))
        For Each objFile in objFolder.Files
            strExt = objFSO.GetExtensionName(objFile.Name)
            If StrComp(strExt,"html",vbTextCompare)=0 Then
                If StrComp(Left(objFile.Name,6),"google",vbTextCompare)<>0 Then
                    Call WriteUrl(strUrlRoot & strUrlRelative & "/" & objFile.Name, objFile.DateLastModified, "weekly", strFormat)
                End If
            End If
        Next
    Next

    ' --------------------------------------------------
    ' End of file system loop.
    ' --------------------------------------------------     
    If strFormat = "XML" Then
        Response.Write "</urlset>"
    End If
    
    Response.End

    ' ======================================================================
    '
    ' Outputs a sitemap URL to the client in XML or TXT format.
    ' 
    ' tmpStrFreq = always|hourly|daily|weekly|monthly|yearly|never 
    ' tmpStrFormat = TXT|XML
    '
    ' ======================================================================

    Sub WriteUrl(tmpStrUrl,tmpLastModified,tmpStrFreq,tmpStrFormat)
        On Error Resume Next
        Dim tmpDate : tmpDate = CDate(tmpLastModified)
        ' Check if the request is for XML or TXT and return the appropriate syntax.
        If tmpStrFormat = "XML" Then
            Response.Write " <url>" & vbCrLf
            Response.Write " <loc>" & Server.HtmlEncode(tmpStrUrl) & "</loc>" & vbCrLf
            Response.Write " <lastmod>" & Year(tmpLastModified) & "-" & Right("0" & Month(tmpLastModified),2) & "-" & Right("0" & Day(tmpLastModified),2) & "</lastmod>" & vbCrLf
            Response.Write " <changefreq>" & tmpStrFreq & "</changefreq>" & vbCrLf
            Response.Write " </url>" & vbCrLf
        Else
            Response.Write tmpStrUrl & vbCrLf
        End If
    End Sub

    ' ======================================================================
    '
    ' Returns a string array of folders under a root path
    '
    ' ======================================================================

    Function GetFolderTree(strBaseFolder)
        Dim tmpFolderCount,tmpBaseCount
        Dim tmpFolders()
        Dim tmpFSO,tmpFolder,tmpSubFolder
        ' Define the initial values for the folder counters.
        tmpFolderCount = 1
        tmpBaseCount = 0
        ' Dimension an array to hold the folder names.
        ReDim tmpFolders(1)
        ' Store the root folder in the array.
        tmpFolders(tmpFolderCount) = strBaseFolder
        ' Create file system object.
        Set tmpFSO = Server.CreateObject("Scripting.Filesystemobject")
        ' Loop while we still have folders to process.
        While tmpFolderCount <> tmpBaseCount
            ' Set up a folder object to a base folder.
            Set tmpFolder = tmpFSO.GetFolder(tmpFolders(tmpBaseCount+1))
              ' Loop through the collection of subfolders for the base folder.
            For Each tmpSubFolder In tmpFolder.SubFolders
                ' Increment the folder count.
                tmpFolderCount = tmpFolderCount + 1
                ' Increase the array size
                ReDim Preserve tmpFolders(tmpFolderCount)
                ' Store the folder name in the array.
                tmpFolders(tmpFolderCount) = tmpSubFolder.Path
            Next
            ' Increment the base folder counter.
            tmpBaseCount = tmpBaseCount + 1
        Wend
        GetFolderTree = tmpFolders
    End Function
%>

 

En los ejemplos anteriores utilizamos 2 funciones:

La función GetFolderTree() devuelve una matriz de cadenas de todas las carpetas que se encuentran en una carpeta raíz; podría eliminar esa función si estuviera generando todas sus URL dinámicamente.

La función WriteUrl() genera una entrada para el archivo del mapa del sitio en formato XML o TXT, según el tipo de archivo que esté en uso. También le permite especificar la frecuencia con la que se debe indexar la URL específica (siempre, cada hora, diariamente, semanalmente, mensualmente, anualmente o nunca).

Paso 3: creación del archivo Web.config

El último paso es agregar las reglas de reescritura de URL al archivo Web.config en la raíz de su sitio web. El siguiente ejemplo es un archivo Web.config completo, pero puede fusionar las reglas en su archivo Web.config existente si ya ha creado uno para su sitio web.

Estas reglas son bastante simples, reescriben todas las solicitudes entrantes de Robots.txt a Robots.asp, reescriben todas las solicitudes de Sitemap.xml a Sitemap.asp?format=XML y las solicitudes de Sitemap.txt a Sitemap.asp?format= TXT; esto permite que funcionen las solicitudes de mapas de sitio basados ??en texto y XML, aunque el archivo Robots.txt contenga la ruta al archivo XML.

La última parte de la sintaxis de reescritura de URL devuelve errores HTTP 404 si alguien intenta enviar solicitudes directas para los archivos Robots.asp o Sitemap.asp; esto no es absolutamente necesario, pero es una capa adicional de seguridad ocultar la tecnología empleada.

 

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rewriteMaps>
        <clear />
        <rewriteMap name="Static URL Rewrites">
          <add key="/robots.txt" value="/robots.asp" />
          <add key="/sitemap.xml" value="/sitemap.asp?format=XML" />
          <add key="/sitemap.txt" value="/sitemap.asp?format=TXT" />
        </rewriteMap>
        <rewriteMap name="Static URL Failures">
          <add key="/robots.asp" value="/" />
          <add key="/sitemap.asp" value="/" />
        </rewriteMap>
      </rewriteMaps>
      <rules>
        <clear />
        <rule name="Static URL Rewrites" patternSyntax="ECMAScript" stopProcessing="true">
          <match url=".*" ignoreCase="true" negate="false" />
          <conditions>
            <add input="{Static URL Rewrites:{REQUEST_URI}}" pattern="(.+)" />
          </conditions>
          <action type="Rewrite" url="{C:1}" appendQueryString="false" redirectType="Temporary" />
        </rule>
        <rule name="Static URL Failures" patternSyntax="ECMAScript" stopProcessing="true">
          <match url=".*" ignoreCase="true" negate="false" />
          <conditions>
            <add input="{Static URL Failures:{REQUEST_URI}}" pattern="(.+)" />
          </conditions>
          <action type="CustomResponse" statusCode="404" subStatusCode="0" />
        </rule>
        <rule name="Prevent rewriting for static files" patternSyntax="Wildcard" stopProcessing="true">
          <match url="*" />
          <conditions>
             <add input="{REQUEST_FILENAME}" matchType="IsFile" />
          </conditions>
          <action type="None" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

 

 

tags: url amigables asp, asp visual studio, asp clasico, cadenas en asp, asp cadenas, url amigable, friendly url, crear url amigables, recortar url google, asp clasico ejemplos, asp classic