Search code examples
c#regexurl-rewritingiis-10

Regex Match URL/Domain/Filename For IIS10


I have had a look at this link but it doesn't cover my requirements.

I am looking to create a regex for IIS10 that matches certain critea and if it doesn't then do something with the URL Rewrite like redirect to the home page.

My attempt at this rule:

(https?:\/\/example\.com).*?(\/)?([Dd]?efault\.aspx)?

I would like for it to be able to check against the following URL's:

Good URL's:

https://example.com/default.aspx
https://example.com

Bad URL's:

http://example.com/default.aspx
http://example.com/directory/somepagename.aspx
http://example.com/ 
http://example.com 
http://example.com/ADirectory/default.aspx
http://www.example.com/default.aspx
http://www.example.com/
http://www.example.com
https://www.example.com/default.aspx
https://www.example.com/
https://www.example.com

So, any URL which is HTTP is rejected. Any URL with HTTPS which matches one of the two GOOD URL's is fine. Any HTTPS url that has a sub-directory is a BAD URL. Any URL that has WWW in the domain name should be rejected (including HTTPS). Match Case = No (Case Insensitive).

Maybe in a few months, I will replace the IIS10 rule and use it in a C# handler.

Much Appreciated


Solution

  • Don't make the s? optional if you don't want to match only http. Instead of using .*? which can match a /, you can use a negated character class matching any char except the forward slash [^/]* not allowing a subfolder

    If you don't want to allow a trailing slash, you can include it in the last optional group, and if you want to match the whole string you can use anchors ^ and $

    ^(https://example\.com)[^/]*(/?[Dd]?efault\.aspx)?$
    

    See a regex demo