Reputation: 2893
I have a asp.net app (IIS7), and I want block access to it using external server IP. I only want to allow access using my domain.
For example, my domain is domain.com and IP 161.0.0.1 and I want to block the access to http://161.0.0.1/webapp/
I prefer do it using web.config
Thx in advance,
Upvotes: 1
Views: 4594
Reputation: 88092
In IIS you configure exactly what IP / DNS name combination you want the site to respond to. You can easily force it to only respond on a particular IP.
For IIS 7:
Now your site wil only respond to that particular domain name and won't respond via IP address only.
If your site uses an SSL certificate then see the following question which talks about how to configure IIS to force the hostname to be used:
https://serverfault.com/questions/96810/iis7-cant-set-host-name-on-site-with-ssl-cert-and-port-443
which links to:
http://www.sslshopper.com/article-ssl-host-headers-in-iis-7.html
This link is even better for doing it entirely through the UI: http://blog.armgasys.com/?p=80
Upvotes: 3
Reputation: 4402
OK so if you want the Site to be accessible via DNS name but not via IP, the only way to distinguish that is to examine the requested host name in the header. There are two ways to do that I know of:
1) Configure Bindings dialog in IIS Manager. This is the easiest to set up but doesn't work for HTTPS. Just put www.domain.com into the hostname field and requests to the IP will be rejected. For HTTPS if your security certificate is for a specific hostname, the user will get a security warning if they try to connect via IP, but typically they can override the warning (depending on browser settings).
Edit: Chris Lively has linked to a way to make this method work for HTTPS bindings as well, see his answer for more information.
2) Alternately you can examine the header in code. Here is an example of an IHttpModule
which accomplishes what you want. It is also a drop-in solution that is configured in web.config.
Code:
Public Class HostNameCheck
Implements IHttpModule
Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
End Sub
Public Sub Init(context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
AddHandler context.BeginRequest, AddressOf context_BeginRequest
End Sub
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim objApp As HttpApplication = DirectCast(sender, HttpApplication)
If objApp.Request.Url.Host <> ConfigurationManager.AppSettings("AcceptedHostName") Then
objApp.Response.Clear()
objApp.Response.StatusCode = 403
objApp.Response.SubStatusCode = 6
objApp.Response.Flush()
End If
End Sub
End Class
Web.config:
<configuration>
<appSettings>
<add key="AcceptedHostName" value="www.domain.com"/>
</appSettings>
<system.webServer>
<modules>
<add name="HostNameCheck" type="HostNameCheck"/>
</modules>
</system.webServer>
</configuration>
Upvotes: 2