I suppose the best solution for this would be a http module.
The simplest implementation of it is posted below. useUnsecureConnection
variable contains the value indicating whether moving away is required (should be calculated by yourself).
public class SecurityModule : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(application_BeginRequest);
}
#endregion
#region Events Handling
protected void application_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = ((HttpApplication)(sender));
HttpRequest request = application.Request;
HttpResponse response = application.Response;
// here should be you condition to determine
// whether to move away from secure page or not
bool useUnsecureConnection = true;
if (useUnsecureConnection && request.IsSecureConnection)
{
string absoluteUri = request.Url.AbsoluteUri;
response.Redirect(absoluteUri.Replace("https://", "http://"), true);
}
}
#endregion
}
And and of course don't forget to register module in your web.config:
<httpModules>
<!--Used to redirect secure connections to the unsecure ones
if necessary-->
<add name="Security"
type="{YourNamespace}.Handlers.SecurityModule,
{YourAssembly}" />
...
</httpModules>
</system.web>
BTW, for localhost
the condition may looks like:
useUnsecureConnection = request.IsLocal;
which will be true
if the IP address of the request originator is 127.0.0.1
or if the IP address of the request is the same as the server's IP address.