Exposing Azure Functions Securely: Master Path-Based Routing with Application Gateway + Video

Listen to this Post

Featured Image

Introduction:

Directly exposing Azure Function Apps to the internet introduces security risks such as DDoS attacks, unwanted traffic, and lack of centralized control. Azure Application Gateway acts as a reverse proxy and Layer‑7 load balancer, enabling path‑based routing, SSL termination, and Web Application Firewall (WAF) integration—transforming a raw function endpoint into a hardened, scalable entry point for production APIs.

Learning Objectives:

  • Understand why Azure Application Gateway is superior to directly exposing Function Apps.
  • Configure path‑based routing to map URL paths to different backend function apps.
  • Modify `host.json` to remove or change the default `/api` route prefix for clean routing.
  • Implement SSL termination, WAF policies, and production best practices for secure deployments.

You Should Know

  1. Why Direct Function Exposure is Risky – and How App Gateway Fixes It

Directly publishing an Azure Function with an HTTP trigger (e.g., `https://myfunc.azurewebsites.net/api/endpoint`) bypasses enterprise traffic management. You lose global rate limiting, IP whitelisting, and centralised certificate handling. Application Gateway adds a secure reverse proxy layer.

Step‑by‑step guide to compare both setups:

1. Check current function host settings (Azure CLI):

az functionapp show --1ame myFunctionApp --resource-group myRG --query "hostNames"

2. Test direct access (Linux/macOS):

curl -I https://myfunc.azurewebsites.net/api/hello

3. Deploy a basic Application Gateway (PowerShell):

New-AzApplicationGateway -1ame "myAppGateway" -ResourceGroupName "myRG" -Location "eastus"

What this does:

The gateway sits in front of your function, inspecting every request. All public traffic hits the gateway first; the function becomes internal, only accessible via the gateway’s backend pool.

2. Modifying the Default `/api` Route Using `host.json`

Azure Functions prepend `/api` to all HTTP triggers by default. For clean path‑based routing (e.g., `/sales/orders` → Sales Function, `/inventory` → Stock Function), you must remove or change this prefix.

Step‑by‑step to override `/api`:

  1. In your Function App’s root folder, create or edit host.json.

2. Add the `http` route prefix setting:

{
"version": "2.0",
"extensions": {
"http": {
"routePrefix": ""
}
}
}

Setting `”routePrefix”: “”` removes `/api` entirely. Use `”routePrefix”: “v1″` to change it to /v1.

3. Deploy the updated function:

func azure functionapp publish myFunctionApp

Verification:

Call the function directly (after deployment) using the new route – https://myfunc.azurewebsites.net/orders` – without/api`. This allows Application Gateway path rules like `/orders/` to map cleanly.

  1. Configuring Application Gateway Backend Pools, Listeners, and HTTP Settings

For path‑based routing, you need one backend pool per target function app, plus a listener that accepts traffic and routing rules that inspect URL paths.

Step‑by‑step using Azure CLI:

  1. Create backend pools (replace `FUNC_APP_ID` with your function app resource ID):
    az network application-gateway address-pool create \
    --gateway-1ame myAppGateway --resource-group myRG --1ame pool-orders \
    --servers myordersfunc.azurewebsites.net</li>
    </ol>
    
    az network application-gateway address-pool create \
    --gateway-1ame myAppGateway --resource-group myRG --1ame pool-inventory \
    --servers myinventoryfunc.azurewebsites.net
    
    1. Create HTTP settings (disable “pick hostname from backend” to preserve routing):
      az network application-gateway http-settings create \
      --gateway-1ame myAppGateway --resource-group myRG --1ame func-http \
      --port 443 --protocol Https --cookie-based-affinity Disabled \
      --host-1ame-from-backend-pool false
      

    3. Add a listener (port 443, SSL required):

    az network application-gateway frontend-port create -g myRG --gateway-1ame myAppGateway -1 httpsPort --port 443
    az network application-gateway http-listener create --1ame func-listener --frontend-ip ag-public-ip \
    --frontend-port httpsPort --gateway-1ame myAppGateway -g myRG --ssl-certificate myCert
    

    Why this matters:

    Backend pools point to the function’s `.azurewebsites.net` URL. Disabling host‑name‑from‑backend‑pool forces the gateway to send the original host header, preventing routing conflicts.

    4. Implementing Path‑Based Routing Rules

    Path‑based routing evaluates the incoming URL path and forwards the request to the correct backend pool. You also define a default path (e.g., /) for unmatched routes.

    Step‑by‑step rule creation:

    1. Define path rules (CLI uses a JSON file; alternatively use PowerShell):
      // pathRules.json
      {
      "paths": {
      "/orders/": "pool-orders",
      "/inventory/": "pool-inventory"
      }
      }
      

    2. Create the path rule map and attach to the listener:

      $pathRule1 = New-AzApplicationGatewayPathRuleConfig -1ame "ordersRule" -Paths "/orders/" -BackendAddressPool $poolOrders -BackendHttpSettings $httpSetting
      $pathRule2 = New-AzApplicationGatewayPathRuleConfig -1ame "inventoryRule" -Paths "/inventory/" -BackendAddressPool $poolInventory -BackendHttpSettings $httpSetting
      $urlPathMap = New-AzApplicationGatewayUrlPathMapConfig -1ame "funcPathMap" -PathRules $pathRule1, $pathRule2 -DefaultBackendAddressPool $defaultPool -DefaultBackendHttpSettings $httpSetting
      

    3. Associate the URL path map with the listener and update the gateway:

      $listener.UrlPathMaps = $urlPathMap
      Set-AzApplicationGateway -ApplicationGateway $appGw
      

    Testing the routing:

    From any machine, run:

    curl -k https://your-gateway-ip/orders/123
    curl -k https://your-gateway-ip/inventory/stock
    

    Each request reaches the correct function app.

    5. Hardening with SSL Termination and WAF

    Application Gateway can offload SSL – decrypt traffic at the gateway, inspect it (WAF), then re‑encrypt to the backend function. Functions support HTTPS natively, but you can keep the gateway‑to‑function traffic HTTP if the function is VNet‑injected, reducing latency.

    Step‑by‑step WAF enablement:

    1. Create a WAF policy (Prevention mode blocks attacks):
      az network application-gateway waf-policy create -g myRG --1ame myWAFPolicy --mode Prevention --rule-set-version 3.0
      

    2. Attach WAF to the gateway (must be a WAF SKU gateway):

      az network application-gateway waf-policy update -g myRG --policy-1ame myWAFPolicy --resource-group myRG --gateway-1ame myAppGateway
      

    3. Custom rule example – block requests missing the `X-API-Key` header:

      az network application-gateway waf-policy custom-rule create --policy-1ame myWAFPolicy --1ame RequireApiKey -g myRG --priority 10 --rule-type MatchRule --match-variables RequestHeaders,Api-Key --operator Contains --action Block
      

    Benefit:

    You get OWASP top‑10 protection, geo‑filtering, and bot mitigation without modifying your function’s code.

    6. End‑to‑End Request Flow and Troubleshooting Commands

    Flow:

    Internet → Gateway Listener (SSL termination) → Path‑based routing evaluation → Appropriate Backend Pool → Azure Function (internal or public). Response travels back through the gateway.

    Troubleshooting commands (Linux/Windows):

    • Check gateway backend health:
      az network application-gateway show-backend-health --gateway-1ame myAppGateway -g myRG
      

    • View access logs (Enable diagnostic settings for gateway):

      Get-AzApplicationGatewayAccessLog -ResourceGroupName myRG -1ame myAppGateway -StartTime (Get-Date).AddHours(-1)
      

    • Test path routing manually with curl and verbose output:

      curl -v -k https://gateway-dns/orders/test --resolve gateway-dns:443:gateway-ip
      

    • Windows PowerShell equivalent:

      Invoke-WebRequest -Uri "https://gateway-dns/orders/test" -Method GET -Verbose
      

    Common issues:

    404 from function – check that `host.json` route prefix is empty. 502 Bad Gateway – verify backend pools use HTTPS and the function’s SSL certificate is trusted.

    7. Production Best Practices and Deployment Considerations

    • Use Private Endpoints for Functions – Inject both the function app and Application Gateway into the same VNet. Then set backend target to the private IP of the function.
    • Health probes – Functions may return 401 for unauthenticated probes; create a custom probe that accepts 200/401 as healthy.
    • Rate limiting – Leverage Application Gateway’s WAF policy with rate‑limit rules (e.g., 100 requests per 5 minutes per IP).
    • Cost management – Gateway V1 is cheaper but V2 (autoscaling) is recommended for production. One gateway can front dozens of function apps using distinct path prefixes.
    • CI/CD integration – Use Bicep or Terraform to deploy gateway + path rules + function settings together. Example Terraform snippet:
    resource "azurerm_application_gateway" "main" {
    name = "func-gateway"
    sku {
    name = "WAF_v2"
    tier = "WAF_v2"
    }
    url_path_map {
    name = "funcPathMap"
    default_backend_address_pool_name = "defaultPool"
    path_rule {
    name = "orders"
    paths = ["/orders/"]
    backend_address_pool_name = "poolOrders"
    }
    }
    }
    

    What Undercode Say:

    • Key Takeaway 1: Exposing Azure Functions directly is convenient but dangerous; Application Gateway with path‑based routing gives you enterprise‑grade security (WAF, SSL, throttling) without rewriting function code.
    • Key Takeaway 2: Modifying `host.json` to remove `/api` is critical for clean URL mapping – most teams overlook this and end up with broken path rules.
    • Key Takeaway 3: Always test backend health and enable diagnostic logs; a silent failure in path rules can lead to traffic being sent to the wrong function or the default backend.

    Analysis (10 lines):

    This architecture bridges the gap between serverless simplicity and traditional network security. By placing Application Gateway in front, organisations can enforce uniform policies (rate limiting, geo‑blocking) across multiple functions while keeping each function’s code stateless and simple. The path‑based routing approach aligns with microservices patterns – each function owns a URL prefix. However, latency increases slightly due to the extra hop, and misconfigured host headers or SSL re‑encryption can cause mysterious 502 errors. The biggest hidden risk is function cold starts combined with gateway timeouts; tune the function’s `functionTimeout` and gateway’s `idleTimeout` in httpSettings. Finally, use infrastructure‑as‑code to version both the gateway rules and the function’s `host.json` together – manual drift between them is a frequent production incident.

    Prediction:

    • -1: As serverless adoption grows, attackers will increasingly target misconfigured path‑based routing rules – for example, by discovering `/admin` paths that bypass WAF rules due to case‑insensitivity gaps or unpatched routing logic.
    • +1: Microsoft will likely release native “API Gateway as a service” for Azure Functions, integrating path routing, JWT validation, and rate limiting directly into the Functions runtime – reducing the need for separate Application Gateway instances for smaller workloads.
    • -1: The complexity of managing TLS certificates, backend health probes, and custom error pages across multiple functions may drive teams back to “direct exposure with API Management,” creating a fragmented security landscape.
    • +1: Deep integration between Application Gateway’s WAF and Azure Functions’ DDoS protection will become automated – future releases could auto‑learn normal traffic patterns and generate custom rules to block anomalies without manual intervention.

    ▶️ Related Video (88% Match):

    🎯Let’s Practice For Free:

    🎓 Live Courses & Certifications:

    Join Undercode Academy for Verified Certifications

    🚀 Request a Custom Project:

    Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
    [email protected]
    💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands

    IT/Security Reporter URL:

    Reported By: Gowtham K – Hackers Feeds
    Extra Hub: Undercode MoN
    Basic Verification: Pass ✅

    🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]

    💬 Whatsapp | 💬 Telegram

    📢 Follow UndercodeTesting & Stay Tuned:

    𝕏 formerly Twitter 🐦 | @ Threads | 🔗 Linkedin | 🦋BlueSky