Implement AWS WAF Rules

Learn how to implement AWS WAF rules for your web app in this hands-on tutorial. Understand core concepts, step-by-step configuration, practical walkthrough, and troubleshooting tips to protect your application.

Focus: implement aws waf rules for your web app

Sponsored

Picture this: you've just deployed your web app to AWS, and within hours you see a spike in traffic — but it's not customers. It's bots hammering your login endpoint, scraping your APIs, or flooding your site with requests that look like SQL injection attempts. Without protection, your app slows down, your costs climb, and you risk a security incident. That's the problem this lesson solves: how to implement AWS WAF rules for your web app so you can filter malicious traffic before it reaches your application.

The problem this lesson solves

Web applications are exposed to the internet 24/7, and attackers don't need a reason to probe them. Common threats include:

  • SQL injection (SQLi) and cross-site scripting (XSS) attempts embedded in URLs, headers, or bodies.
  • Distributed denial-of-service (DDoS) floods that exhaust your resources.
  • Credential stuffing where bots try many username/password combinations.
  • Scraping that steals your content or pricing data.

If you rely only on your application's code to handle these, you're doing too much work and putting your app at risk. AWS WAF (Web Application Firewall) sits in front of your application and filters traffic based on rules you define. This lesson teaches you to implement AWS WAF rules for your web app — protecting your app before requests even hit your compute.

Core concept / mental model

Think of AWS WAF as a bouncer at the door of your web app. The bouncer checks every guest (HTTP request) against a list of rules (the doorman's policy) before letting them in. If a request matches a rule that says "block," it's turned away; if it matches an "allow" rule, it passes through. If no rule matches, the default action applies (usually allow or block, depending on your setup).

Key components of AWS WAF:

  • Web ACL: The container that holds rules and is associated with your resource (CloudFront, Application Load Balancer, or API Gateway).
  • Rules: Each rule contains a statement (what to match) and an action (allow, block, or count).
  • Rule groups: A collection of rules that you can reuse across multiple web ACLs.
  • Managed rule groups: AWS-provided rule sets for common threats like SQLi, XSS, bad bots, and IP reputation lists.
  • IP sets: A list of IP addresses or CIDR ranges you can reference in rules.

A helpful metaphor: your web app is a VIP club. AWS WAF is the guest list and security team. You decide who gets in (allow rules), who's on the blacklist (block rules), and who gets watched (count rules for monitoring).

How it works step by step

Implementing AWS WAF rules for your web app follows a clear, logical sequence:

  1. Identify the resource to protect — Decide if you're protecting a CloudFront distribution, an Application Load Balancer (ALB), or an API Gateway endpoint. Each has its own integration points.
  2. Create a Web ACL — The Web ACL is the umbrella that holds your rules. You'll specify the AWS region (or CloudFront global) and associate it with your resource.
  3. Define rules — Start with AWS-managed rule groups, then add custom rules for your app's specific needs. For example, block requests from geo-locations you don't serve, or rate-limit login attempts.
  4. Associate the Web ACL — Attach it to the resource you chose in step 1. The association propagates quickly (usually under a minute).
  5. Test and monitor — Use the WAF console's Sampled requests feature to see what traffic is being allowed or blocked. Adjust rules as needed.

The cause-and-effect chain: you create a Web ACL with rules → you associate it with your resource → AWS WAF inspects every incoming request → it takes the action defined by the first matching rule → legitimate traffic proceeds, malicious traffic is halted.

Pro tip: Use the Count action during initial implementation. It logs what would have been blocked without affecting traffic, so you can validate rules before switching to Block.

Hands-on walkthrough

Let's implement AWS WAF rules for your web app using the AWS Management Console and CLI. We'll cover both a simple managed rule setup and a custom rate-based rule.

Step 1: Create a Web ACL (Console)

  1. Open the AWS WAF console.
  2. Choose Web ACLs in the left panel.
  3. Click Create web ACL.
  4. Enter a name like my-app-web-acl.
  5. For Resource type, choose Application Load Balancer (or CloudFront, depending on your app).
  6. Select the region where your ALB is deployed.
  7. Click Next until you reach the Add rules step.

Step 2: Add a managed rule group

In the Add rules step:

  1. Click Add rulesAdd managed rule groups.
  2. In the search, choose Core rule set (CRS) — this includes rules for SQLi, XSS, and common exploits.
  3. Also add Known bad inputs and AWS IP reputation list.
  4. For each group, you can leave the action as Count initially, or set to Block if confident.
  5. Click Add rule groups.

Step 3: Add a custom rule (rate-based)

To limit requests from a single IP:

  1. In the same Web ACL edit screen, click Add my own rules and rule groups.
  2. Choose Builder.
  3. For Rule type, select Rate-based rule.
  4. Name it rate-limit-login.
  5. Set the Rate limit to 100 (requests per 5-minute window).
  6. Optionally, set a scope-down statement to only rate-limit requests to /login.
  7. Action: Block.

Step 4: Associate the Web ACL

  1. After adding rules, click Next until you see the Review and create page.
  2. Confirm the rules, then click Create web ACL.
  3. In the console, select your Web ACL, go to Associated AWS resources, and click Add AWS resources. Choose your ALB (or CloudFront) and add it.

Step 5: Verify with a quick test

You can test using curl from your machine to see the blocking behavior. To do that, you'd need a rule based on your IP. But for a sanity check, look at the Sampled requests tab in the WAF console to see if traffic is being evaluated.

Here's a complete Python example using boto3 to create a Web ACL programmatically for an ALB:

import boto3

waf = boto3.client('wafv2', region_name='us-east-1')

alb_arn = 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/my-app/abcdef123456'

acl_name = 'my-app-web-acl'

u = 'urn:aws:iam::123456789012:role/WAF-Role'  # replace with your role ARN

try:
    resp = waf.create_web_acl(
        Name=acl_name,
        Scope='REGIONAL',
        DefaultAction={'Allow': {}},
        Rules=[
            {
                'Name': 'AWSManagedRulesCommonRuleSet',
                'Priority': 1,
                'Statement': {'ManagedRuleGroupStatement': {'VendorName': 'AWS', 'Name': 'AWSManagedRulesCommonRuleSet'}},
                'OverrideAction': {'Count': {}}
            }
        ],
        VisibilityConfig={
            'SampledRequestsEnabled': True,
            'CloudWatchMetricsEnabled': True,
            'MetricName': 'web_acl_metrics'
        }
    )
    print('Web ACL created:', resp['Summary']['ARN'])
    acl_arn = resp['Summary']['ARN']
    # Associate to ALB
    waf.associate_web_acl(
        WebACLArn=acl_arn,
        ResourceArn=alb_arn
    )
    print('Associated with ALB')
except Exception as e:
    print('Error:', e)

Expected output (if IAM permissions are correct):

Web ACL created: arn:aws:wafv2:us-east-1:123456789012:regional/webacl/my-app-web-acl/12345678-1234-1234-1234-123456789012
Associated with ALB

This script creates a Web ACL with the AWS Common Rule Set in count mode, then associates it with your ALB. From here you can manage rules via the console or CLI.

Step 6: Monitor with CloudWatch

WAF integrates with CloudWatch. You can view metrics like BlockedRequests and CountedRequests:

aws cloudwatch get-metric-statistics \
  --namespace AWS/WAFV2 \
  --metric-name BlockedRequests \
  --dimensions Name=WebACL,Value=my-app-web-acl \
  --start-time 2025-01-01T00:00:00Z \
  --end-time 2025-01-01T01:00:00Z \
  --period 3600 \
  --statistics Sum

This command returns the total blocked requests in the past hour—essential for verifying your rules are working.

Compare options / when to choose what

Option Best for Action Complexity Cost
AWS Managed Rules Quick start, common threats (SQLi, XSS, bad bots) Block/Count Low Per rule/month
Custom rules App-specific logic (e.g., block a specific country, rate limit /login) Block/Count Medium Same cost per rule
AWS WAF Security Automations Full-featured setup with logging, auto-blocking IPs Block, Count, Captcha High (CF templates) Higher (extra Lambda, S3)
Third-party WAF (e.g., Cloudflare, Imperva) If you already use a CDN or need advanced bot management Varies High (external) Varies, often lower latency

When to choose what:

  • Start with managed rules — they cover ~90% of common threats and require minimal configuration.
  • Add custom rules when you need to enforce application-specific policies, like blocking non-US traffic for a US-only service.
  • Use AWS WAF Security Automations if you need advanced features like IP reputation, automatic IP blocking, or integration with Lambda for custom logic.
  • Consider a third-party if you're already using a CDN with built-in WAF or need more sophisticated bot detection.

Pro tip: For a typical small-to-medium app, managed rules plus one or two custom rules is usually sufficient. Avoid over-engineering with 50 custom rules—maintenance and false positives increase rapidly.

Troubleshooting & edge cases

Common problems and fixes

  • Rule doesn't block as expected — Check the rule's action (maybe still set to Count). Verify your test IP isn't in an allowed list or that the scope-down statement doesn't exclude it.
  • False positives — Legit users blocked? Review the Sampled requests log and adjust rules. Use Count action first, then move to Block after tuning.
  • Web ACL not associating — Ensure the resource (e.g., ALB) is in the same region as the Web ACL (unless using CloudFront). Also check IAM permissions on the resource.
  • Performance impact — WAF introduces slight latency (usually <5ms). If you see a significant slowdown, verify you're not doing too many complex regex patterns.
  • Cost surprises — WAF charges per rule and per million requests. Monitor CloudWatch usage; use managed rules sparingly if cost is a concern.

Edge case: CloudFront vs. regional

If you use CloudFront, the Web ACL must be in the CLOUDFRONT scope (global). The console and CLI differ significantly. For example, to create a Web ACL for CloudFront:

resp = waf.create_web_acl(
    Name='cloudfront-acl',
    Scope='CLOUDFRONT',
    DefaultAction={'Allow': {}},
    Rules=[...],
)

And association is done via the API associate_web_acl with the CloudFront distribution ARN.

What you learned & what's next

You've now learned how to implement AWS WAF rules for your web app — from creating a Web ACL with managed rules, adding custom rate-based rules, associating it with your ALB or CloudFront, and monitoring via CloudWatch. You can explain the core idea of AWS WAF as a filtering gateway, and you've completed a practical exercise using both console and boto3.

You're now ready for the next lesson in this AWS Tutorial track, which likely covers AWS Shield Advanced for DDoS protection or AWS Network Firewall for deeper network-level security. These build on the same security mindset but at different layers of the stack.

Key takeaway: AWS WAF is your first line of defense against common web attacks. Start simple with managed rules, test with Count action, and only add custom rules when necessary. With that, your web app is already a much harder target.

Practice recap

Test your WAF implementation by temporarily setting your own IP as a block rule using a custom rule (action Block), then visit your site and confirm you get a 403 Forbidden response. After verifying, remove the rule. This validates your setup end-to-end without risking production traffic.

Common mistakes

  • Setting the action to Block immediately on managed rules without first using Count, which can break legitimate traffic if the rule has false positives.
  • Forgetting to associate the Web ACL to the resource — a Web ACL with no resource attached does nothing, and it's easy to miss in the console flow.
  • Using a regional Web ACL for a CloudFront distribution without specifying Scope='CLOUDFRONT', resulting in an invalid association error.
  • Overly aggressive rate-based rules (e.g., rate limit 5 requests per 5 minutes) that block real users, especially when browsing behind NAT proxies.
  • Ignoring CloudWatch metrics—without monitoring, you won't notice if a rule is silently blocking too much traffic or not blocking at all.

Variations

  1. Use AWS WAF Security Automations (a CloudFormation template) to deploy a complete solution with IP reputation lists, logging, and automatic blocking.
  2. Instead of the console, manage WAF entirely as code using AWS CDK or Terraform, enabling versioned, reviewable infrastructure.
  3. Implement a custom Lambda-based rule to inspect request body size or content-type and block or allow dynamically based on your app's logic.

Real-world use cases

  • A SaaS startup protects its ALB-backed API from SQL injection and XSS using AWS Managed Rules, blocking thousands of malicious requests daily.
  • An e-commerce site uses a rate-based rule to limit login attempts to 5 per minute per IP, stopping credential stuffing attacks from bots.
  • A media company with a CloudFront distribution geo-blocks countries where it doesn't have rights, using a custom rule with a geo-match statement.

Key takeaways

  • AWS WAF is a web application firewall that filters HTTP(S) traffic before it reaches your app, blocking common attacks like SQLi and XSS.
  • Start with AWS Managed Rules in Count mode, then switch to Block after validating with Sampled requests to minimize false positives.
  • Custom rules, like rate-based limits, are essential for app-specific threats such as credential stuffing.
  • Always associate your Web ACL with the target resource (ALB, CloudFront, or API Gateway) or it won't enforce anything.
  • Monitor WAF metrics in CloudWatch to measure blocked vs allowed traffic and adjust rules as attack patterns evolve.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.