How to block access to URL-path using Azure App Gateway

Sometimes we need to restrict access to some URL-path of a Web application from Internet while allow to access the whole web site. This kind of restriction might be relevant for example for a administrative user interface or a special API that should not be accessed from Internet.

There is no access to the restricted URL-path from Internet, requests will be responded with 403 HTTP “forbidden”. While /api/protected remains open from a dedicated VNet.

Link to GitHub repository

To implement the solution wee need the following components:

  1. An Azure Application Gateway in front of the application.
  2. A VNet integrated with the application. The URL-path restricted from the Internet will be available from this VNet.

Application Gateway configuration

Application gateway must be configured with path-base routing.

A /api/protected route permanently redirects to

This path should not have a connected controller. It is just an artificial path to terminate the request.

Application configuration for ASP.NET core 3.1

There is a URL-rewrite functionality for ASP.NET core URL Rewriting Middleware in ASP.NET Core. Use AddRedirect() method to respond with 443 code to all requests coming to ~/forbidden URL-path.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 var options = new RewriteOptions().AddRedirect("^forbidden*", "$1", 443);

Application configuration for classic ASP.NET

Application must be configured to use IIS URL rewrite module. The only change we need in web.config file is to add rewrite section inside system.webServer section:

        <rule name="Forbidden response" stopProcessing="true">
          <match url="^forbidden*" />
          <action type="CustomResponse" statusCode="403" statusReason="This call is not allowed." />

When any HTTP-request comes to ~/forbidden IIS will immediately response with 443 forbidden status. URL Rewrite Module Configuration Reference

Thus when a request comes through the App Gateway to /api/protected the gateway redirects it to And IIS responses with 443 status on this request.

Azure Web Service configuration

In order to allow access to our application only through application gateway Access Restriction must be configured.

For calls from Internet we should allow access from a VNet where the gateway is placed.

For calls to /api/protected we can gave an access from another dedicated VNet.