Application Gateway with WAF (Layer 7)
-
Phase 0: Before you start
-
Phase 1: The foundation
-
Phase 2: Day-to-day operations
-
Phase 3: Enterprise architecture
-
Phase 4: Troubleshooting step by step
-
Phase 5: Final project and career
Azure Application Gateway is a Layer 7 load balancer for web traffic. Because it reads each HTTP request, it can route by URL path or host name, end TLS and rewrite headers, and with the WAF_v2 SKU it can block attacks like SQL injection and cross-site scripting using a Web Application Firewall (WAF).
The load balancer in Lesson 51 only saw IPs and ports. Application Gateway sees the request itself, and that’s why it’s the usual front door for business web apps that live in one region.
It’s also behind two errors that fill support queues: 502 Bad Gateway, and WAF 403 blocks on requests that look perfectly normal. You’ll cause both and fix both. The lab costs a bit more, so do it in one sitting.
| Time | You need | Cost | By the end you can |
|---|---|---|---|
| About 2 hours | A free account, law-saat in rg-saat-core, the CLI | About USD 1.20 if you finish and clean up within 2 hours: WAF_v2 is USD 0.504 per hour plus USD 0.0144 per capacity unit hour in Central India (Azure Retail Prices API, October 2026) | Deploy Application Gateway WAF_v2 with a WAF policy, read backend health and WAF logs, and fix a 502 and a false positive |
What it is, in one line
Application Gateway is a web traffic manager that reads every request, sends it to the right servers, and can block attacks with a built-in firewall.
In Simple Words
The receptionist who reads every letter
The load balancer in Lesson 51 was like a post office that sorts by address and nothing else. Application Gateway is more like a receptionist who opens every letter, so letters about “billing” go to the accounts team and letters about “jobs” go to HR. She also keeps a list of known tricks (hidden instructions, fake signatures, strange attachments), and anything like that goes straight in the bin, which is what the Web Application Firewall does.
Now and then she bins an honest letter that only looks suspicious, say a teacher’s letter that quotes a scam as an example. You don’t sack the receptionist for that; you tell her “letters to the teaching team may quote scams”, and that note is a WAF exclusion.
Engineer's View
What Application Gateway is made of
- SKUs: Standard_v2 and WAF_v2, both autoscaling and zone-redundant, plus a low-cost Basic SKU that has no WAF. The v1 SKUs are retired.
- Subnet: it needs a dedicated subnet, and Microsoft recommends /24 for v2. Nothing except application gateways can live in it.
- Listener: the frontend IP, port and protocol (plus an optional host name) that receives requests.
- Rule: links a listener to a backend pool and backend settings, and on v2 every rule needs a priority. Path-based rules can send /api and /images to different pools.
- Backend settings: the port, protocol, timeout and host name the gateway uses to talk to the servers. The default probe uses the same port.
- Backend health: when no server in the pool is healthy, users get 502 Bad Gateway.
- WAF policy: the Microsoft Default Rule Set (DRS 2.1) gives each request an anomaly score. In Prevention mode a high score returns 403, while Detection mode only logs it. You tune it with exclusions and custom rules.
How it works, step by step
Here’s what happens to a request in this lab:
- Your browser sends GET / to pip-agw on port 80 and the listener accepts it.
- The WAF policy inspects the URL, headers and body. Every rule that matches adds to an anomaly score, and if the score reaches the threshold, rule 949110 blocks the request with 403.
- If the request is clean, rule1 chooses the backend pool and settings.
- The gateway opens its own connection to vm-app1 on the settings port and forwards the request, adding an X-Forwarded-For header with your IP.
- The response comes back to you through the gateway.
Notice there are two separate connections here, browser to gateway and gateway to server. That’s why the server sees the gateway’s private IP, and why backend problems show up as a 502 instead of a timeout.
When something fails, the response code tells you where to look. A 403 from the gateway means WAF, a 502 means backend health, and a 4xx or 5xx from the app itself passes straight through.
Deploy Application Gateway WAF_v2 in front of a web server
Before you run any command, double-check it
Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.
Cost check: the gateway starts billing when it’s created in step 3, so keep going until you reach the clean-up step.
1Network and a backend server
Create a VNet with a gateway subnet and a private web subnet, plus one VM:
az group create --name rg-saat-l52 --location centralindia --tags course=saatvedha-azure lesson=52 -o none
az network vnet create --resource-group rg-saat-l52 --name vnet-l52 --address-prefixes 10.52.0.0/16 --subnet-name snet-agw --subnet-prefixes 10.52.0.0/24 -o none
az network vnet subnet create --resource-group rg-saat-l52 --vnet-name vnet-l52 --name snet-web --address-prefixes 10.52.1.0/24 --default-outbound-access false -o none
az vm create --resource-group rg-saat-l52 --name vm-app1 --image Canonical:ubuntu-24_04-lts:server:latest --size Standard_B1s --vnet-name vnet-l52 --subnet snet-web --private-ip-address 10.52.1.4 --public-ip-address '""' --nsg '""' --admin-username azureuser --generate-ssh-keys --tags course=saatvedha-azure lesson=52 -o noneStart a small web server. Ubuntu already ships with Python, so the private VM doesn’t need internet access for this:
az vm run-command invoke --resource-group rg-saat-l52 --name vm-app1 --command-id RunShellScript --scripts 'mkdir -p /srv/www; echo Hello from vm-app1 > /srv/www/index.html; systemd-run --unit web python3 -m http.server 80 --directory /srv/www; sleep 2; systemctl is-active web' --query "value[0].message" -o tsvYou should see:
[stdout]
active2Create a WAF policy in Prevention mode
Run this:
az network application-gateway waf-policy create --resource-group rg-saat-l52 --name wafp-saat --type Microsoft_DefaultRuleSet --version 2.1 --tags course=saatvedha-azure lesson=52 -o none
az network application-gateway waf-policy policy-setting update --resource-group rg-saat-l52 --policy-name wafp-saat --mode Prevention --state Enabled -o none3Create the application gateway (about 8 minutes)
Run this:
az network public-ip create --resource-group rg-saat-l52 --name pip-agw --sku Standard --zone 1 2 3 -o none
az network application-gateway create --resource-group rg-saat-l52 --name agw-saat --sku WAF_v2 --min-capacity 0 --max-capacity 2 --vnet-name vnet-l52 --subnet snet-agw --public-ip-address pip-agw --servers 10.52.1.4 --frontend-port 80 --http-settings-port 80 --http-settings-protocol Http --priority 100 --waf-policy wafp-saat --tags course=saatvedha-azure lesson=52 -o noneThe CLI creates a listener, a backend pool with 10.52.1.4, backend settings named appGatewayBackendHttpSettings, and a rule named rule1.
4Send logs to law-saat
Save the categories in a file, then create the diagnostic setting from it:
'[{"category":"ApplicationGatewayAccessLog","enabled":true},{"category":"ApplicationGatewayFirewallLog","enabled":true}]' | Set-Content C:\azure-lab\agwlogs.json
$agwId = az network application-gateway show --resource-group rg-saat-l52 --name agw-saat --query id -o tsv
$lawId = az monitor log-analytics workspace show --resource-group rg-saat-core --workspace-name law-saat --query id -o tsv
az monitor diagnostic-settings create --name agw-to-law --resource $agwId --workspace $lawId --export-to-resource-specific true --logs '@C:\azure-lab\agwlogs.json' -o none5Test a normal request and an attack
Run this:
$agwIp = az network public-ip show --resource-group rg-saat-l52 --name pip-agw --query ipAddress -o tsv
curl.exe -s http://$agwIp/
curl.exe -sI "http://$agwIp/?q=%3Cscript%3Ealert(1)%3C/script%3E"You should see something like this:
Hello from vm-app1
HTTP/1.1 403 Forbidden
Server: Microsoft-Azure-Application-Gateway/v2
Content-Type: text/htmlThe normal request got through to the VM, while the script in the query string was blocked by the WAF before the VM ever saw it.


✅ Checkpoint: agw-saat serves the page through pip-agw, blocks a cross-site scripting attempt with 403, and sends logs to law-saat.
Break It, Then Fix It
Keep the gateway running for both breaks, and clean up afterwards.
1Break it: 502 after an app change
The app team moves the web server to port 8080 and doesn’t tell anyone:
az vm run-command invoke --resource-group rg-saat-l52 --name vm-app1 --command-id RunShellScript --scripts 'systemctl stop web; systemd-run --unit web8080 python3 -m http.server 8080 --directory /srv/www; sleep 2; systemctl is-active web8080' --query "value[0].message" -o tsv
curl.exe -sI http://$agwIp/After about a minute you should see something like this:
HTTP/1.1 502 Bad Gateway
Server: Microsoft-Azure-Application-Gateway/v2Now ask the gateway why:
az network application-gateway show-backend-health --resource-group rg-saat-l52 --name agw-saat --query "backendAddressPools[0].backendHttpSettingsCollection[0].servers[].{address:address, health:health, log:healthProbeLog}" -o jsonYou should see something like this:
[
{
"address": "10.52.1.4",
"health": "Unhealthy",
"log": "Cannot connect to backend server. Check whether any NSG/UDR/Firewall is blocking access to the server. Check if application is running on correct port."
}
]A 502 is the gateway telling you “I have no healthy server to send this to”. The backend health log points at the port, and sure enough, on the VM the app now listens on 8080 while the backend settings still use 80.
To fix it, point the backend settings at the new port, then check health and the site:
az network application-gateway http-settings update --resource-group rg-saat-l52 --gateway-name agw-saat --name appGatewayBackendHttpSettings --port 8080 -o none
az network application-gateway show-backend-health --resource-group rg-saat-l52 --name agw-saat --query "backendAddressPools[0].backendHttpSettingsCollection[0].servers[].{address:address, health:health, log:healthProbeLog}" -o json
curl.exe -s http://$agwIp/Health shows Healthy, and the page says Hello from vm-app1 again.
2Break it: the WAF blocks a real user
Say a SQL course on your site lets students submit code, and a student sends a perfectly normal SQL homework answer:
curl.exe -sI "http://$agwIp/submit?code=SELECT+name+FROM+students+UNION+SELECT+name+FROM+teachers"You should see this:
HTTP/1.1 403 Forbidden
Server: Microsoft-Azure-Application-Gateway/v2This is a false positive. The WAF is doing its job, but on this site SQL in the code field is expected. Find out which rules fired, and give the logs 5 to 10 minutes to arrive:
$ws = az monitor log-analytics workspace show --resource-group rg-saat-core --workspace-name law-saat --query customerId -o tsv
az monitor log-analytics query --workspace $ws --analytics-query "AGWFirewallLogs | where TimeGenerated > ago(30m) and RequestUri has 'submit' | project RuleId, Action, Message | take 10" -o tableYou should see something like this (rule numbers can differ):
Action Message RuleId
-------- ----------------------------------------------- --------
Matched SQL Injection Attack Detected via libinjection 942100
Matched Detects MySQL comment-/space-obfuscated ... 942190
Blocked Mandatory rule. Cannot be disabled. Inbound ... 949110Rule 949110 only adds up the score, and the real triggers are the Matched SQLI rules. Don’t switch the whole WAF to Detection; exclude just the code parameter, and only from those rules:
To fix it, add a per-rule exclusion with the rule IDs from your log, wait a minute and try again:
az network application-gateway waf-policy managed-rule exclusion rule-set add --resource-group rg-saat-l52 --policy-name wafp-saat --type Microsoft_DefaultRuleSet --version 2.1 --group-name SQLI --rule-ids 942100 942190 --match-variable RequestArgNames --match-operator Equals --selector code -o none
curl.exe -sI "http://$agwIp/submit?code=SELECT+name+FROM+students+UNION+SELECT+name+FROM+teachers"
curl.exe -sI "http://$agwIp/?q=%3Cscript%3Ealert(1)%3C/script%3E"You should see something like this:
HTTP/1.0 404 File not found
Server: SimpleHTTP/0.6 Python/3.12.3
HTTP/1.1 403 Forbidden
Server: Microsoft-Azure-Application-Gateway/v2The homework request now gets past the WAF to the VM, which answers 404 because the lab server has no /submit page (in a real app, that’s where the form handler would run). The script attack is still blocked, because the exclusion only covers SQLI rules on one field.

3Clean up (the gateway bills by the hour)
Delete the diagnostic setting first, then the resource group:
az monitor diagnostic-settings delete --name agw-to-law --resource $agwId
az group delete --name rg-saat-l52 --yes
az resource list --tag lesson=52 -o tableThe last command should print nothing.
✅ Checkpoint: You fixed a 502 with backend health and a WAF false positive with a narrow exclusion, and nothing from this lab is left.
This happened at work
The password reset page that stopped working
An online learning company had run its WAF in Detection mode for a month with “no problems in the logs”, so one Friday they switched it to Prevention. By Saturday users couldn’t reset their passwords, because the gateway was returning 403 for every reset request.
The reset link carried a long random token in the URL, and some tokens happened to contain character patterns that matched SQL injection rules. So some users got blocked and the rest were fine. Nobody had read the Detection logs; the team had only counted errors from the app, and in Detection mode there weren’t any.
What they changed: now, before any switch to Prevention, they query AGWFirewallLogs for Matched rules by URL over two weeks and add narrow exclusions first. The reset token parameter got its own per-rule exclusion, and an alert fires when 403s from the gateway climb above normal.
Common mistakes and troubleshooting
| Mistake | What you see | What to do |
|---|---|---|
| App port changed, settings not | 502, backend Unhealthy | Match backend settings and probe to the app port. |
| NSG or UDR blocks the gateway subnet | 502 or failed deployment | Allow the gateway subnet to reach backends; follow subnet rules. |
| Turning the whole WAF to Detection to stop a false positive | Attacks get through | Add a per-rule exclusion for the one field. |
| Switching to Prevention without reading logs | Sudden 403s for real users | Review Matched rules in Detection mode first. |
| Wrong host header to the backend | Backend returns 404 or wrong site | Set the host name in backend settings or the probe. |
| Backend timeout too short | Slow pages return 502 or 504 | Raise the backend settings timeout. |
Interview questions
Click a question to open it. Each one is worded the way an interviewer would ask it, and underneath you’ll find why they ask it and one way you could answer in your own words.
Fresher level
1. What is Application Gateway?
Why they ask this: The basic concept.
How you might answer: It’s a regional Layer 7 load balancer for HTTP and HTTPS. It can route by path or host, end TLS, rewrite headers and run a Web Application Firewall.
2. Load Balancer or Application Gateway?
Why they ask this: Basic comparison.
How you might answer: Load Balancer works at Layer 4 for any TCP or UDP traffic, while Application Gateway is Layer 7 for web traffic, with URL routing and WAF.
3. What does a 502 from Application Gateway mean?
Why they ask this: A daily support question.
How you might answer: It means the gateway couldn’t get a valid response from any backend. Usually the backends are unhealthy, unreachable or too slow.
2–5 years experience
4. How do you troubleshoot a 502?
Why they ask this: A real troubleshooting path.
How you might answer: I’d start with backend health and its probe log, then the port, protocol and host name in the backend settings. After that, NSGs and UDRs on both subnets, DNS if the backends are FQDNs, certificates if they’re HTTPS, and the timeout.
5. What is the difference between Detection and Prevention mode?
Why they ask this: WAF basics.
How you might answer: Detection logs the matches but doesn’t block anything. Prevention blocks any request whose anomaly score reaches the threshold and returns 403.
6. A WAF blocks a legitimate request. What do you do?
Why they ask this: They want a safe fix.
How you might answer: I’d find the matching rule IDs in the firewall logs and confirm it really is a false positive. Then I’d add the narrowest exclusion or custom rule I can, scoped to that field and those rules. I’d never disable the WAF globally.
Senior level
7. Application Gateway or Front Door?
Why they ask this: They want architecture.
How you might answer: Application Gateway is regional and sits inside your VNet, so it suits private backends and internal apps. Front Door is global, at the edge, with caching and global failover. A lot of designs put Front Door in front of Application Gateway or private origins.
8. How do you handle TLS end to end?
Why they ask this: Security depth.
How you might answer: I’d terminate TLS at the gateway with a certificate from Key Vault, then use TLS again to the backend with trusted root or well-known CAs and matching host names, and set a minimum TLS policy.
9. How do you roll out WAF safely for 50 apps?
Why they ask this: Operations at scale.
How you might answer: I’d start with a base WAF policy plus per-site or per-URI policies, run Detection first and review the logs, and keep the exclusions in code. Only then switch to Prevention, with alerts on spikes in blocked requests and a rollback plan ready.
Quick quiz
Q1. Users get 502 from the gateway. First thing to check?
- WAF mode
- Backend health
- DNS zone
- Pricing tier
Show answer
B — 502 means no healthy backend answered.
Q2. Which rule ID shows the total anomaly score blocked the request?
- 942100
- 949110
- 920350
- 100
Show answer
B — 949110 blocks once the score threshold is reached.
Q3. Best fix for a false positive on one form field?
- Switch to Detection
- Per-rule exclusion for that field
- Delete the WAF policy
- Use Load Balancer
Show answer
B — Keep protection, narrow the exclusion.
Q4. Which SKU includes the WAF?
- Basic
- WAF_v2
- Standard_v2
- Standard
Show answer
B — WAF_v2 includes the firewall.
Q5. Why does the backend see the gateway’s IP?
- NAT on the VM
- The gateway opens its own connection
- DNS
- Peering
Show answer
B — It’s a reverse proxy; the client IP is in X-Forwarded-For.
Quick recap
You’ve run a real web front door with a firewall, and you can now tell a backend problem from a WAF problem at a glance.
- Application Gateway works at Layer 7 and is a reverse proxy.
- 502 means backend health; read the probe log.
- 403 from the gateway means WAF; read AGWFirewallLogs.
- Fix false positives with narrow, per-rule exclusions.
- WAF_v2 bills hourly; delete lab gateways the same day.
Next lesson
Lesson 53: Traffic Manager: DNS-based global routing → You route users to the closest healthy region with DNS and watch failover happen.
Further reading: Azure Application Gateway
Want to go deeper into Azure Application Gateway? See Microsoft’s What is Azure Application Gateway? and WAF exclusion lists. You can also see the full plan for this course on the Azure Cloud Administration course page.
