Search code examples
asp.net-mvcignoreroute

How do I block requests for all *.php, *.cgi, etc. pages from inside an ASP.NET MVC 1.0 app hosted in IIS7?


I'd like to block requests to any .php or .cgi regardless of the pathing information.

For example, when the following url is used:

http://mysite/Admin/Scripts/Setup.php

It matches an existing route:

routeCollection.MapRoute("Admin", "admin/{controller}/{action}/{uid}/{*pathInfo}", new { controller = "Admin", action = "Index", uid = "" });

However there is no controller for scripts so MVC throws the following:

The IControllerFactory '' did not return a controller for a controller named 'scripts'.

What I'd really prefer is that the request is simply met with a hard fail before MVC ever got to the controller.

I know that I can do this by hooking the Application_BeginRequest in the Global.asax and throwing a new HttpException(404, "Not Found") but that's not quite the elegant solution I'm looking for.

I was really hoping that this would work:

routeCollection.IgnoreRoute("{resource}.php/{*pathInfo}");

But it doesn't.

NOTE: Sean Lynch's answer works great but I still would really like a System.Web.Routing or System.Web.Mvc based solution. That way I can allow my users to add their own exclusions at runtime.


Solution

  • If you hosting provider supports the IIS7 URL Rewrite module then you could check out this link:

    http://learn.iis.net/page.aspx/499/request-blocking---rule-template/

    Update here is what you would put into your web.config in the system.webserver section:

    <system.webServer>
        <rewrite>
            <rules>
                <rule name="RequestBlockingRule1" patternSyntax="Wildcard">
                    <match url="*" />
                    <conditions>
                        <add input="{URL}" pattern="*.php*" />
                    </conditions>
                    <action type="CustomResponse" statusCode="403" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>