57

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.example.com/Category/CategoryName/3916" httpResponseStatus="Permanent" />
    </system.webServer>
</location>

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.

1

3 Answers 3

63
  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://example.com/services" httpResponseStatus="Permanent" />
         </system.webServer>
       </location>
       <location path="products.htm">
         <system.webServer>
           <httpRedirect enabled="true" destination="http://example.com/products" httpResponseStatus="Permanent" />
         </system.webServer>
       </location>
     </configuration>
    

You may add as many location paths as necessary.

5
  • 1
    I like the IIS URL Rewrite Module 2.0 (iis.net/download/urlrewrite) a lot to these kind of rewrites.
    – Styxxy
    May 1, 2012 at 15:31
  • 1
    @mug4n Do you need to keep the old pages (services.htm) in place for this to work or can you completely remove then from your project?
    – Dhaust
    Jun 5, 2012 at 1:02
  • yes it does work with aspx files. See here for sample codes: stackoverflow.com/questions/7325831/…
    – MUG4N
    Jul 21, 2012 at 9:46
  • 1
    Differences httpRedirect with URL REWRITE iis.net/download/urlrewrite ?
    – Kiquenet
    Sep 5, 2019 at 15:49
  • What files should be kept in the "old" application in IIS in order for Redirection to keep working. My app is kind of big do I need to keep it as is or can I delete binaries etc?
    – Jimi
    Nov 9, 2020 at 13:21
28

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>
5
  • 1
    Actually, I'm trying to do the opposite (make category.aspx?cid=1234 redirect to category/categoryname/1234). Would it be the same thing? And what does the {R:2} do?
    – Pear Berry
    May 2, 2012 at 13:14
  • @PearBerry I know this is late, but yes you could do that in a similar manner. {R:2} refers to the second capture group (([_0-9a-z-]+)) and takes whatever was captured there and puts it after the equals sign in the rewritten url. Jul 29, 2015 at 20:51
  • I had similar situation, but just stop the request for certain fail. This answer works for me: <rule enabled="true" name="Remove Configurations"> <match ignoreCase="true" url="configs.json"/> <action statusCode="404" type="AbortRequest" /> </rule>
    – mihkov
    Nov 25, 2016 at 9:57
  • What if I have 2 parameters to pass ? How should I pass in url of action type="Redirect" <action type="Redirect" url="/Home/givershare?cid={C:1}&uid={C:1}"/> I tried this but it is not allowing "&" Please help Aug 31, 2017 at 14:34
  • @ShalinJirawla In an XML file you need to escape the ampersand. Use &amp;.
    – vcsjones
    Aug 31, 2017 at 14:42
-2

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;
        }
    }
}
2
  • This is definnetly a web config.... Are you aware that IIS does not have to host .NET application to begin with? Thus your C# solution completely misses the question. If the IIS is used to host static content there is no .NET application running. Dec 29, 2020 at 19:57
  • I was interested in to give a programmatic way to do the same as a previous solution, just that. Also, a similar approach can be found in: learn.microsoft.com/en-us/iis/configuration/system.webserver/…, I don't think I am missing the question.
    – jjroman
    Dec 30, 2020 at 0:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.