Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIS7 URL Rewriting Module Replace

I really like the IIS7 URL rewriting module and so far, it worked great for me.

There is one thing that I'm not sure how to do: I would like to permanently redirect all URLs that have encoded spaces (%20) in them to a URL that has the spaces replaced with a dash (-).

So this:

http://www.test.com/About%20Our%20Mission.aspx

should be redirected to this:

http://www.test.com/About-Our-Mission.aspx

Is that even possible with only regular expressions?

like image 249
Stefan Avatar asked Dec 29 '22 21:12

Stefan


2 Answers

There's no way to do directly what you want.

You might settle for something like this:

^(.*)%20(.*)%20(.*)%20(.*)  replaced by:  {R:1}-{R:2}-{R:3}-{R:4}
^(.*)%20(.*)%20(.*)         replaced by:  {R:1}-{R:2}-{R:3}
^(.*)%20(.*)                replaced by:  {R:1}-{R:2}
like image 158
Jeremy Stein Avatar answered Jan 03 '23 11:01

Jeremy Stein


One of then nice things about .aspx is how easy it is to rewrite URLs with real code. Just add a little search and replace code to your web site's Global.asax file:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    string path = HttpContext.Current.Request.Path;
    // Search and replace, RegEx, etc.
    HttpContext.Current.RewritePath(path);
}

On IIS7, you have to add some entries in web.config to handle rewriting non .aspx URLs:

<system.webServer>
    <handlers>
        <clear/>
        <add name="Brands1" path="Brands/*.html" verb="*" type="ASP.global_asax" resourceType="Unspecified"/>
        <add name="Brands2" path="Brands/\?*.html" verb="*" type="ASP.global_asax" resourceType="Unspecified"/>
        <!-- ... -->

The IIS7 URL rewriting module is great, but just because you have a hammer...

like image 37
P.J. Tezza Avatar answered Jan 03 '23 11:01

P.J. Tezza