Redirecting HTTP to HTTPS using IIS
I setup my first SSL secure site yesterday and found something interesting. There doesn't appear to be a built in IIS function for redirecting from http:// to https://
Why is that? That seems like something that would come in handy.
Anyways, after a little Google searching and experimenting, I came up with a method that I think works relatively well. If anyone has a better method of doing this, by all means let me know.
Start by creating a new ASP file and insert the following.
<%
Response.Buffer = True
If (Request.ServerVariables("HTTPS") = "off") Then
sQ = Request.ServerVariables("QUERY_STRING")
sURL = "https" & Right(sQ, (Len(sQ)-8))
Response.redirect(sURL)
End if
%>
Save this file as sslredirect.asp and place it in a folder named SSL inside your website.
- Open the IIS console
- Select your website
- Right click on this new SSL folder and click Properties.
- Under the Application settings section, click Create.
- Click the Directory Security tab, and then click Edit under Authentication and access control.
- Make sure Enable anonymous access is checked, and then click OK.
- Under Secure communications, click Edit.
- Make sure the Require secure channel (SSL) check box is NOT checked, and then click OK two times to close the window.
You've just ensured that SSL is removed from this folder so it'll run the script using anonymous access and plain old http.
Now you need to enable SSL for the rest of the site and setup the redirect.
- Right click on the root website folder and click Properties.
- Click the Directory Security tab.
- Under Secure Communications, click Edit.
- Click to select the Require secure channel (SSL) check box, and then click OK.
- Click the Custom Errors tab, and then double-click 403.4
- In the Message Type list, click URL.
- In the URL box, type /SSL/sslredirect.asp, and then click OK two times to close the window.
Now... here's what happens. With SSL enabled, anytime you attempt to access a page via http, the server generates a 403.4 error. IIS is now configured to run your sslredirect.asp page every time this error occurs. The error page will include a querystring which contains the error number and the page causing the error, I.e. "403;http://www.whatever.com". Our ASP file uses a simple script to just trim off the beginning part (430;http), add the necessary "https", and redirect to whatever page the user requested using SSL. Voila!