Search code examples
asp.nethttp-redirectiisweb-confighttp-status-code-301

ASP.NET 301 redirect if contains last folder


I need to make a 301 redirect for all old links that contain (/CID-VALUE), e.g. www.example.com/folder1/folder2/CID-1234. These link could have been on any folder so I need something that catches all instances of CID- and the carried value and go to the replaced link with something like ?cid=VALUE instead.

I'm working in ASP with VB.NET so use a web.config file.

Here's the code I currently use for 301 redirects

<rule name="Redirect" stopProcessing="true">
    <match url="^example(.*)" />
    <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    </conditions>
    <action type="Redirect" url="/newexample/{R:1}" />
</rule>

Solution

  • Your old URL structure is /folder1/folder2/CID-1234 and I assume that folder1 and folder2 are examples and are variable.

    <rule name="redirect-to-cid-page" stopProcessing="true">
        <match url="^([_0-9a-zA-Z\-]+)/([_0-9a-zA-Z\-]+)/([_0-9a-zA-Z\-]+)$" />
        <action type="Redirect" url="/new-cid-page.aspx?id={R:3}" statusCode="301" />
    </rule>
    

    So the rule above matches:

    • folder1 to {R:1} with the expresssion ([_0-9a-zA-Z\-]+)
    • folder2 to {R:2} with the expresssion ([_0-9a-zA-Z\-]+)
    • CID number to {R:3} with the expresssion ([_0-9a-zA-Z\-]+)

    For folder1, folder2 and the CID number I assume that they contain latin letters in any case and numbers.