Recently I was working on a smart 404 page with a redirect handler so that custom urls could be handled through a SharePoint list with RegEx.  For example would see the “.com/vanity1”, and look it up on the SharePoint list to redirect the client to the appropriate URL.

The site itself was set to anonymous, however some of the solution files were placed in the /_layouts/RedirectHandler directory and I kept getting a “401 Unauthorized” message when accessing the vanity urls (despite having the _layouts/RedirectHandler in the web.config like this:

  <location path="_layouts/RedirectHandler">
        <allow users="*" />

Turns out that even though the site is anonymous, the key here is that you cannot use the default LayoutsPageBase class for the page because it would trigger SharePoint to prompt anonymous users to log on.  For example, the %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS\login.aspx page that ships with Microsoft SharePoint Foundation 2010 inherits from an internal class named LoginPage, which itself inherits from UnsecuredLayoutsPageBase.

Instead, you need to use another class for your anonymous application page called UnsecuredLayoutsPageBase. You can find its MSDN reference at:

Your page class would look like this, and now everything works quite nicely without prompting anonymous users to login.

public partial class Handler : UnsecuredLayoutsPageBase
    protected override void OnPreRender(EventArgs e)