Regex to match file extension while ignoring query string

1.3k views Asked by At

I'd like to build a IIS url rewrite rule that matches several file extensions but ignore the query string.

Samples:

/hello.html // Match
/test?qs=world.html // Should not match
/test?qs=world.html&qs2=x // Should not match

Here is what I was using that does not work correctly:

<add matchType="Pattern" input="{HTTP_URL}" pattern=".+\.(js|css|less|html|eot|svg|ttf|woff|json|xml)$" negate="true" /> <!--Any url with a dot for file extension-->
3

There are 3 answers

1
karthik manchala On BEST ANSWER

Use \w+ instead of .+ .................(\w is equivalent to [a-zA-Z0-9_]):

<add matchType="Pattern" input="{HTTP_URL}" pattern="\w+\.(js|css|less|html|eot|svg|ttf|woff|json|xml)$" negate="true" /> <!--Any url with a dot for file extension-->

If you want to allow other characters (non included in \w) and still ignore query string you can use [^?]+ instead of .+

0
Hugo Ferreira On

see if this works for you:

I write it in javascript, (I don't know IIS) but the regex is always similar

    /^.*\/[\w]+\.[\w]{2,4}$/.test('/test?qs=world.html') // return false
/^.*\/[\w]+\.[\w]{2,4}$/.test('/world.html') // return true

maybe it work as:

    <add matchType="Pattern" input="{HTTP_URL}" pattern="^.*\/[\w]+\.[\w]{2,4}$" negate="true" />

but I put the extension as a generic way. if you want to make a whitebox test for extension, you may replace it to:

^.*\/[\w]+\.(js|css|less|html|eot|svg|ttf|woff|json|xml)$
0
Shlomo On

I assume this will work in IIS: ^[^?]*$ will match any string not containing a ?.