Setting up redirect in web.config file

asp.netWeb ConfigHttp Redirect

asp.net Problem Overview


I'm trying to redirect some unfriendly urls with more descriptive ones. These urls end in .aspx?cid=3916 with the last digits being different for each category name page. I want it to instead redirect to Category/CategoryName/3916. I tried this in the web.config file:

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

but since it didn't end with just the extension, it didn't work. Is there an easy way to get this to work? I'm using IIS 7.5.

asp.net Solutions


Solution 1 - asp.net

  1. Open web.config in the directory where the old pages reside

  2. Then add code for the old location path and new destination as follows:

     <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>
    

You may add as many location paths as necessary.

Solution 2 - asp.net

You probably want to look at something like URL Rewrite to rewrite URLs to more user friendly ones rather than using a simple httpRedirect. You could then make a rule like this:

<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>

Solution 3 - asp.net

In case that you need to add the http redirect in many sites, you could use it as a c# console program:

   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;
        }
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPear BerryView Question on Stackoverflow
Solution 1 - asp.netMUG4NView Answer on Stackoverflow
Solution 2 - asp.netvcsjonesView Answer on Stackoverflow
Solution 3 - asp.netjjromanView Answer on Stackoverflow