TroySteven
TroySteven

Reputation: 5157

Generic Web.Config Rewrite to remove query strings and add url seo slug

I have the following URL Rewrite I am trying to create.

<rule name="Imported Rule 3">
    <match url="^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)" ignoreCase="true" />
    <action type="Rewrite" url="/{R:0}/{R:1}.aspx?p={R:2}&title={R:3}" appendQueryString="true" />                  
</rule>

I want the following urls to rewrite to the following.

/Catalog/Product/1/Title-Description

To

/Catalog/Product.aspx?pid=1&title=Title-Description

And

/Events/Detail/1/Today
/Events/Detail.aspx?pid=1&title=Title-Description

Basically I want the write to be generic and apply to multiple scenarios. Anytime there is a url with 4 slashes, I want the rewrite rule to pick it up and convert it to the url.

So event a url of

1/1/1/1 would be valid.

Which would convert to

/1/1.aspx?pid=1&title=1

Just to give you an example.

I don't want to have to write a separate rewrite for each scenario.

However the above rewrite I wrote keeps throwing an error on the server and I can't seem to find out what is wrong with my syntax. The server gices a generic 500 error so I can't narrow it down.

I'm fairly certain the issue is with the action tag,

I've written it as

<action type="Rewrite" url="/{R:0}/{R:1}.aspx?p={R:2}&title={R:3}" appendQueryString="true" />     

and

<action type="Rewrite" url="/{R:1}/{R:2}.aspx?p={R:3}&title={R:4}" appendQueryString="true" />     

Neither option works.

Upvotes: 1

Views: 3306

Answers (1)

Marco Miltenburg
Marco Miltenburg

Reputation: 6138

I think there are a few problems. The first being the use of {R:0} as you already found out yourself. {R:0} matches the entire URL as {R:1}, {R:2}, etc. matches the fragments. So in this case you must use {R:1}, {R:2}, etc.

Another problem is that you might have made a mistake to use ?p={R:3} instead of ?pid={R:3}. Finally and probably the reason for the 500 error is that you have not properly XML encoded the ampersand in the &title which should be &amp;title.

I think the following should work:

<rule name="Imported Rule 3" stopProcessing="true">
    <match url="^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)" />
    <action type="Rewrite" url="/{R:1}/{R:2}.aspx?pid={R:3}&amp;title={R:4}" appendQueryString="false" />
</rule>

Upvotes: 2

Related Questions