2012-05-01 40 views
40

Estoy tratando de redirigir algunas URL poco amigables con otras más descriptivas. Estas URL terminan en .aspx?cid=3916 con los últimos dígitos siendo diferentes para cada página de nombre de categoría. Quiero que redirija a Category/CategoryName/3916. He intentado esto en el archivo web.config:Configuración de la redirección en el archivo web.config

<location path="Category.aspx?cid=3916"> 
<system.webServer> 
    <httpRedirect enabled="true" destination="http://www.site.com/Category/CategoryName/3916" httpResponseStatus="Permanent" /> 
</system.webServer> 

pero ya que no terminó con sólo la extensión, no funcionó. ¿Hay alguna manera fácil de hacer que esto funcione? Estoy usando IIS 7.5.

+0

Esta opción requiere IIS7 https://blogs.msdn.microsoft.com/kaushal/2013/05/22/http-to-https-redirects-on-iis-7-x-and-higher/ –

Respuesta

44
  1. web.config abierto en el directorio donde las viejas páginas residen
  2. A continuación, agregue código para la antigua ruta de ubicación y nuevo destino de la siguiente manera:

    <configuration> 
        <location path="services.htm"> 
        <system.webServer> 
         <httpRedirect enabled="true" destination="http://domain.com/services" httpResponseStatus="Permanent" /> 
        </system.webServer> 
        </location> 
        <location path="products.htm"> 
        <system.webServer> 
         <httpRedirect enabled="true" destination="http://domain.com/products" httpResponseStatus="Permanent" /> 
        </system.webServer> 
        </location> 
    </configuration> 
    

Usted puede agregue tantas rutas de ubicación como sea necesario.

+0

Me gusta el IIS URL Rewrite Module 2.0 (http://www.iis.net/download/urlrewrite) mucho a este tipo de reescrituras. – Styxxy

+0

@ mug4n ¿Necesita mantener las páginas anteriores (services.htm) en su lugar para que esto funcione o puede eliminarlas por completo de su proyecto? – Dhaust

+0

sí, puede eliminar los archivos del proyecto anterior – MUG4N

21

Es probable que desee ver algo como URL Rewrite para reescribir las URL a las más amigables en lugar de utilizar un simple httpRedirect. A continuación, puede hacer una regla como la siguiente:

<system.webServer> 
    <rewrite> 
    <rules> 
     <rule name="Rewrite to Category"> 
     <match url="^Category/([_0-9a-z-]+)/([_0-9a-z-]+)" /> 
     <action type="Rewrite" url="category.aspx?cid={R:2}" /> 
     </rule> 
    </rules> 
    </rewrite> 
</system.webServer> 
+0

En realidad, estoy tratando de hacer lo contrario (make category.aspx? cid = 1234 redirigir a categoría/nombre de categoría/1234). ¿Sería lo mismo? ¿Y qué hace el {R: 2}? –

+0

@PearBerry Sé que esto es tarde, pero sí podrías hacer eso de manera similar. '{R: 2}' se refiere al segundo grupo de captura ('([_0-9a-z -] +)') y toma lo que fue capturado allí y lo coloca después del signo igual en la url reescrita. – Dannnno

+0

Tuve una situación similar, pero simplemente detuve la solicitud de falla cierta. Esta respuesta funciona para mí: ' ' – mihkov

0

En caso de que es necesario agregar la redirección HTTP en muchos sitios, se podría utilizar como AC# programa de consola:

class Program 
{ 
    static int Main(string[] args) 
    { 
     if (args.Length < 3) 
     { 
      Console.WriteLine("Please enter an argument: for example insert-redirect ./web.config http://stackoverflow.com"); 
      return 1; 
     } 

     if (args.Length == 3) 
     { 
      if (args[0].ToLower() == "-insert-redirect") 
      { 
       var path = args[1]; 
       var value = args[2]; 

       if (InsertRedirect(path, value)) 
        Console.WriteLine("Redirect added."); 
       return 0; 
      } 
     } 

     Console.WriteLine("Wrong parameters."); 
     return 1; 

    } 

    static bool InsertRedirect(string path, string value) 
    { 
     try 
     { 
      XmlDocument doc = new XmlDocument(); 

      doc.Load(path); 

      // This should find the appSettings node (should be only one): 
      XmlNode nodeAppSettings = doc.SelectSingleNode("//system.webServer"); 

      var existNode = nodeAppSettings.SelectSingleNode("httpRedirect"); 
      if (existNode != null) 
       return false; 

      // Create new <add> node 
      XmlNode nodeNewKey = doc.CreateElement("httpRedirect"); 

      XmlAttribute attributeEnable = doc.CreateAttribute("enabled"); 
      XmlAttribute attributeDestination = doc.CreateAttribute("destination"); 
      //XmlAttribute attributeResponseStatus = doc.CreateAttribute("httpResponseStatus"); 

      // Assign values to both - the key and the value attributes: 

      attributeEnable.Value = "true"; 
      attributeDestination.Value = value; 
      //attributeResponseStatus.Value = "Permanent"; 

      // Add both attributes to the newly created node: 
      nodeNewKey.Attributes.Append(attributeEnable); 
      nodeNewKey.Attributes.Append(attributeDestination); 
      //nodeNewKey.Attributes.Append(attributeResponseStatus); 

      // Add the node under the 
      nodeAppSettings.AppendChild(nodeNewKey); 
      doc.Save(path); 

      return true; 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine($"Exception adding redirect: {e.Message}"); 
      return false; 
     } 
    } 
} 
Cuestiones relacionadas