在web.config文件中设置重定向

57

我试图将一些不友好的URL重定向为更具描述性的URL。这些URL以.aspx?cid=3916结尾,其中最后几位数字对于每个类别名称页面都是不同的。我想将其重定向到Category/CategoryName/3916。我在web.config文件中尝试了以下代码:

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

但是由于它不仅仅以扩展名结束,所以它没有工作。有没有简单的方法使其工作?我正在使用 IIS 7.5。


此选项需要IIS7 https://blogs.msdn.microsoft.com/kaushal/2013/05/22/http-to-https-redirects-on-iis-7-x-and-higher/。 - nu everest
3个回答

63
  1. 旧页面所在的目录中打开web.config

  2. 然后添加旧位置路径和新目标的代码,如下:

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

您可以添加尽可能多的位置路径。


1
我非常喜欢IIS URL Rewrite Module 2.0(http://www.iis.net/download/urlrewrite)来进行这种重写。 - Styxxy
1
@mug4n,你需要保留旧页面(services.htm)才能使其正常工作,还是可以完全从项目中删除它们? - Dhaust
是的,它可以与aspx文件一起使用。请参见此处的示例代码:https://dev59.com/rGw05IYBdhLWcg3wSABH - MUG4N
1
差异:httpRedirect 与 URL REWRITE http://www.iis.net/download/urlrewrite? - Kiquenet
在IIS中,“旧”应用程序需要保留哪些文件才能使重定向继续工作?我的应用程序有点大,我需要保留原样还是可以删除二进制文件等? - Jimi

28

你可能想要查看类似 URL Rewrite 这样的东西,将 URL 重写为更友好的用户形式,而不是使用简单的 httpRedirect。然后,您可以制定这样的规则:

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

1
实际上,我正在尝试做相反的事情(使category.aspx?cid=1234重定向到category/categoryname/1234)。这会是同样的事情吗?{R:2}是什么意思? - Pear Berry
@PearBerry,我知道有些晚了,但是你可以用类似的方式来实现。{R:2}指的是第二个捕获组(([_0-9a-z-]+))并将其捕获的内容放在重写后URL的等号后面。 - Dan Oberlam
我曾经遇到过类似的情况,但只是针对某些失败的请求停止了请求。以下答案对我有用: - mihkov
如果我有两个参数要传递怎么办? 如何在url中传递action type="Redirect" <action type="Redirect" url="/Home/givershare?cid={C:1}&uid={C:1}"/> 我尝试了这个,但它不允许"&" 请帮忙 - Shalin Jirawla
在 XML 文件中需要转义 '&' 符号。 - vcsjones

-2

如果您需要在多个网站中添加HTTP重定向,可以将其用作C#控制台程序:

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

这明显是一个Web配置文件...你知道IIS不一定要托管.NET应用程序吗?因此,你的C#解决方案完全没有回答问题。如果IIS用于托管静态内容,则没有运行任何.NET应用程序。 - Luk Deathrage Prochzka
我对提供编程方式来完成与先前解决方案相同的操作很感兴趣,仅此而已。此外,在https://learn.microsoft.com/en-us/iis/configuration/system.webserver/httpredirect/中可以找到类似的方法,我认为我没有错过问题。 - jjroman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接