If you've stumbled upon this post, it most likely means that you're trying to use the rewrite/redirect features of IIS to redirect all the HTTP requests coming to your website to HTTPS/SSL. Since you are here we'll also took for granted that you're working with the IIS URL Rewrite module (in case you don't know what it is or if you need help installing it, check out this other post).
To get straight to the point, here's the rewrite rule you're probably looking for:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<system.webServer> <rewrite> <rules> <rule name="Redirect to HTTPS" enabled="true" stopProcessing="true"> <match url="(.*)" /> <conditions logicalGrouping="MatchAll" trackAllCaptures="false"> <add input="{HTTPS}" pattern="off" /> </conditions> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Found" /> </rule> </rules> </rewrite> </system.webServer> |
Now, what if we want to keep one or more folders (and all their contents) accessible through HTTP?
Here's a nice way to create an exception to the above rule adding a single additional line:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<system.webServer> <rewrite> <rules> <rule name="Redirect to HTTPS except /nossl/ folder" enabled="true" stopProcessing="true"> <match url="(.*)" /> <conditions logicalGrouping="MatchAll" trackAllCaptures="false"> <add input="{REQUEST_URI}" pattern="^nossl/.*" negate="true" /> <add input="{HTTPS}" pattern="off" /> </conditions> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Found" /> </rule> </rules> </rewrite> </system.webServer> |
As we can see, we took advantage of the negate="true" attribute to create an excluding input pattern, which - if matched - will prevent that rule from triggering: therefore, all the pages included in that folder will be accessible without SSL. Needless to say, you can add multiple input patterns to exclude additional folders from the HTTP-to-HTTPS mandatory redirect as well.
Pretty neat, right?
For additional info, check out the following IIS URL Rewrite Module resources by Microsoft:
- Using URL Rewrite Module 2.0 (including docs, guides, tutorials & samples)
- URL Rewrite Module - Video Walkthrough
- URL Rewrite Module - Community Forum
- URL Rewrite Module - Download Page
That's it for now: I hope that this could help other IIS administrators that are struggling against this issue!
This doesn’t work. Internal Server error with in the applicationHost file, works fine when it’s not.
Hi there, we tested the code on IIS 7, 8, 8.5 and 10 and it works without issues.
Be sure to write the “excluding” line just like it’s shown:
Should be pattern not url for the add input. Had the same issue with 500 errors when written the other way, i.e.:
Yes, the proper string to add is the following one:
We fixed the code accordingly.