Regex To The Rescue For Shorter URLs

Date Published: 05 November 2003

Regex To The Rescue For Shorter URLs

I’ve been redesigning off and on for the last several months, and I made a few more changes this morning. The big one that is noticeable to the general public is the URLs. Instead of having to link to articles via a viewer ASPX page and a series of querystring values, it is now sufficient to simply append the article ID to the end of the domain name (after a slash), like so: (article ID 1, which is my Excel Reports in ASP article).

The nice thing about this is that it uses Context.RewritePath, so there is no Response.Redirect and the user never sees the actual URL of the page handling the request. The regex I’m using is here:

The actual code looks like this:

string originalUrl = Request.Url.ToString();
// Check for article shortcuts (e.g. )
string newUrl = AspAlliance.Web.Core.HttpRedirect.GetRedirect(originalUrl);
if(newUrl != originalUrl)
System.Uri myUri = new System.Uri(newUrl);

// GetRedirect:

System.Text.RegularExpressions.Regex regex =
new System.Text.RegularExpressions.Regex(@”.com/(d+)$”,
(System.Text.RegularExpressions.RegexOptions.Compiled |
System.Text.RegularExpressions.MatchCollection matches = regex.Matches(badRequest);
if(matches.Count > 0)
string id = matches[0].Value.Replace(“.com/”, “”);
int aId;
aId = Int32.Parse(id);
return “” + id;
return badRequest;
Steve Smith

About Ardalis

Software Architect

Steve is an experienced software architect and trainer, focusing on code quality and Domain-Driven Design with .NET.