Cybersecurity

WAF vs Firewall vs Antivirus: What Protects What?

November 30, 2026 · 13 min read

WAF vs Firewall vs Antivirus: What Protects What?

WAF vs firewall is a question that usually comes up right after an incident or a security questionnaire: you already have a firewall and antivirus, so why is someone telling you that you also need a web application firewall? The short answer is that each tool watches a different layer. A network firewall decides which connections may reach which machines and ports. A web application firewall (WAF) reads the content of web requests and blocks attacks hidden inside normal-looking HTTPS traffic, such as SQL injection. Antivirus and endpoint protection watch files and processes on devices, catching malware that neither a firewall nor a WAF ever sees.

Knowing the difference matters because attackers now move faster than most patch cycles. In the first half of 2026, CrowdStrike found that 88% of exploitation using public proof-of-concept code happened within 48 hours of that code being released, and VulnCheck measured the median time from a vulnerability's publication to its exploitation falling from 120 days to 80, as The Register reported. This guide explains what each layer protects, where it runs and what it cannot do, maps common attacks to the right defence and includes tested configurations for a Linux firewall and nginx, plus a small script that shows how a WAF makes its decisions.

WAF vs Firewall vs Antivirus at a Glance

Network firewallWeb application firewallAntivirus and endpoint protection
ProtectsNetworks, servers and portsWebsites, web apps and APIsLaptops, servers and files
Looks atIP addresses, ports, protocols and connection stateThe content of HTTP and HTTPS requests and responsesFiles, processes and device behaviour
Network layerMainly layers 3 and 4; next-generation firewalls go furtherLayer 7, the application layerThe operating system
StopsAccess to services that should not be public, port scans, many network attacksSQL injection, cross-site scripting, path traversal, bad bots, credential stuffing, known exploitsMalware, ransomware, malicious documents and web shells
MissesAttacks hidden inside allowed web trafficMalware on devices and attacks on non-web servicesAttacks on your application's logic
ExamplesCloud security groups, ufw, nftables, hardware firewallsCloudflare, AWS WAF, Azure WAF, ModSecurity or Coraza with the OWASP Core Rule SetMicrosoft Defender, CrowdStrike Falcon, SentinelOne, ClamAV

What a Network Firewall Does

A network firewall filters traffic by source and destination address, port and protocol, and stateful firewalls also track connections so that replies to your own requests are allowed back in. The golden rule is default deny: block everything, then allow only what is needed. For a typical web server that means ports 80 and 443 open to the world, SSH open only to known addresses or a VPN, and databases never reachable from the internet.

Firewalls exist at several levels: hardware or virtual appliances at the edge of a network, security groups and network policies in cloud platforms, and host firewalls on each server, such as ufw, iptables and nftables on Linux. Next-generation firewalls add application awareness, intrusion prevention and sometimes TLS inspection, which blurs the line with other tools, but they are still not designed to understand the logic of your particular web application. On an Ubuntu server, ufw sets a sensible baseline in a few lines:

#!/usr/bin/env bash
# firewall.sh: a network firewall for a single web server with ufw (Ubuntu)
set -euo pipefail

ufw default deny incoming     # block everything that is not explicitly allowed
ufw default allow outgoing
ufw allow 80/tcp              # HTTP (redirects to HTTPS)
ufw allow 443/tcp             # HTTPS
ufw allow from 203.0.113.10 to any port 22 proto tcp   # SSH only from the office IP
ufw limit 22/tcp              # slow down brute-force attempts on SSH
ufw --force enable
ufw status verbose

The address 203.0.113.10 is reserved for documentation, so replace it with your office or VPN address, and keep a second session open while you test so that a mistake does not lock you out. Our Linux commands guide covers ufw and related tools.

Here is the limitation. Once port 443 is open, every request to your website passes straight through, including the one carrying a SQL injection payload. To a network firewall, an attack inside HTTPS looks like any other visit. That gap is exactly what a WAF fills.

What a Web Application Firewall Does

A WAF sits in front of a website or API, inspects HTTPS traffic and evaluates each request before it reaches your application. Typical protections include:

  • Attack detection rules, such as the OWASP Core Rule Set, used by ModSecurity, now an OWASP project, and by the newer Coraza engine.
  • Anomaly scoring, which adds up evidence from many rules and blocks only when a threshold is crossed, reducing false alarms.
  • Rate limiting and bot management to slow credential stuffing, scraping and brute-force logins.
  • Virtual patching: emergency rules that block attempts to exploit a newly published vulnerability before you can deploy the real fix.
  • API protection, such as schema validation and limits on request size.
  • Application-layer DDoS mitigation, especially when the WAF runs on a content delivery network.

Cloud and CDN WAFs, such as Cloudflare, AWS WAF and Azure Web Application Firewall, need no server changes and absorb traffic at the edge. Other WAFs run on a reverse proxy or load balancer in your own infrastructure, or inside the web server itself, which suits self-hosted PHP stacks. Whatever the product, the decision logic looks broadly like this simplified sketch:

// mini-waf.mjs: how a web application firewall decides, and why tuning matters
const RULES = [
  { id: "SQLI-1", score: 5, test: /('|%27)\s*(or|and)\s+\d+=\d+|union\s+select/i },
  { id: "XSS-1", score: 5, test: /<script\b|on(error|load)\s*=|javascript:/i },
  { id: "TRAVERSAL-1", score: 5, test: /\.\.\/|%2e%2e%2f/i },
  { id: "SCANNER-UA", score: 3, test: /sqlmap|nikto|masscan/i, field: "userAgent" },
];
const THRESHOLD = 5; // anomaly scoring: block when the total reaches the threshold

function inspect(req) {
  const hits = RULES.filter((r) => r.test.test(r.field === "userAgent" ? req.userAgent : decodeURIComponent(req.url + " " + (req.body ?? ""))));
  const score = hits.reduce((s, r) => s + r.score, 0);
  return { action: score >= THRESHOLD ? "BLOCK" : "allow", score, rules: hits.map((h) => h.id) };
}

const requests = [
  { name: "normal search", url: "/search?q=red+shoes", userAgent: "Mozilla/5.0" },
  { name: "SQL injection", url: "/products?id=1' OR 1=1 --", userAgent: "Mozilla/5.0" },
  { name: "path traversal", url: "/download?file=../../etc/passwd", userAgent: "Mozilla/5.0" },
  { name: "scanner", url: "/", userAgent: "sqlmap/1.9" },
  { name: "developer blog post about XSS", url: "/admin/posts", body: "Never put <script> tags in user input", userAgent: "Mozilla/5.0" },
];
for (const r of requests) {
  const v = inspect(r);
  console.log(`${r.name.padEnd(30)} ${v.action.padEnd(5)} score=${v.score} ${v.rules.join(",")}`);
}

Running it prints:

normal search                  allow score=0
SQL injection                  BLOCK score=5 SQLI-1
path traversal                 BLOCK score=5 TRAVERSAL-1
scanner                        allow score=3 SCANNER-UA
developer blog post about XSS  BLOCK score=5 XSS-1

Look at the last line. A developer saving a blog post about cross-site scripting is blocked, because the article text looks like an attack. This is the false-positive problem every WAF faces, and it is why real deployments start in detection-only mode, review the logs, add narrow exclusions for legitimate traffic and only then switch to blocking. The Core Rule Set calls its strictness setting the paranoia level: higher levels catch more attacks but also block more genuine requests. Notice too that the scanner was only logged, not blocked, because one weak signal did not cross the threshold.

A Lightweight First Line in nginx

Even without a full WAF, your web server can reject a lot of junk cheaply. This nginx configuration for a PHP site rate-limits each client, applies a much stricter limit to the login page, caps upload size, hides the server version, refuses to serve version control folders and environment files, which attackers scan for constantly, and never executes PHP from the uploads folder:

# nginx.conf: application-layer protections for a PHP site (a lightweight first line, not a full WAF)
events {}

http {
    # Rate limits per client IP: 10 requests per second in general, 5 per minute for login
    limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;

    server {
        listen 80;                          # TLS settings omitted for brevity: serve HTTPS in production
        server_name example.com;
        root /var/www/example/public;       # only the public folder is reachable from the web
        index index.php;
        client_max_body_size 2m;            # reject oversized uploads early
        server_tokens off;                  # do not advertise the nginx version

        # Never serve secrets or version control folders
        location ~ /\.(git|env|svn) {
            return 404;
        }

        # Never execute PHP files from the uploads folder
        location ~* ^/uploads/.*\.php$ {
            return 403;
        }

        location = /login.php {
            limit_req zone=login burst=3 nodelay;
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.4-fpm.sock;   # adjust to your PHP version
        }

        location ~ \.php$ {
            limit_req zone=general burst=20 nodelay;
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.4-fpm.sock;
        }

        location / {
            limit_req zone=general burst=20 nodelay;
            try_files $uri $uri/ /index.php?$query_string;
        }
    }
}

It is not a WAF, because it does not inspect request content for attack patterns. Think of it as the doorman who turns away obvious trouble, while the WAF is the guard who checks every bag. Our comparison of nginx vs Apache covers the web server side in more depth.

What Antivirus and Endpoint Protection Do

Antivirus software scans files for known malware, while modern endpoint detection and response (EDR) tools also watch process behaviour, so they can spot ransomware encrypting files or a script launching a reverse shell, and let your team isolate a machine remotely. Laptops need this because most malware arrives through people: a phishing attachment, a fake software update or a malicious download, the tricks described in our guide to social engineering attacks. Servers benefit too, because compromised web servers often end up hosting web shells, cryptocurrency miners or backdoors hidden among PHP files.

For websites, the most practical uses are scanning user uploads with an engine such as ClamAV before storing them, running file integrity monitoring so that you know when PHP files change unexpectedly, and keeping endpoint protection on every machine that has access to production. None of this stops an attacker who abuses your application's own features, and none of it replaces backups: our guide to ransomware protection covers that side.

What Protects What: Common Attacks Mapped

ThreatMain defensive layerWhat fixes it at the source
SQL injectionWAFParameterised queries, as explained in our SQL injection guide
Cross-site scriptingWAFOutput encoding and a content security policy; see cross-site scripting
Brute force on SSH or databasesNetwork firewallKey-based login, no public database ports
Credential stuffing on a login formWAF rate limits and bot rulesTwo-factor authentication and breached-password checks
Malware from a phishing emailAntivirus and EDREmail filtering and staff awareness
Malicious file uploadUpload scanning and web server rulesStrict type checks and storage outside the web root
Newly disclosed flaw in a pluginWAF virtual patchUpdating the plugin as soon as a fix exists
Large DDoS attackCDN, WAF and your provider's network protectionCapacity planning and caching

Why a WAF Is Not a Substitute for Secure Code

Framing the choice as WAF vs firewall can hide the option that matters most: fixing the code. A WAF buys time; it does not remove the vulnerability. Determined attackers look for encodings and edge cases that slip past generic rules, and business logic flaws such as one customer viewing another customer's orders look like perfectly normal requests. Treat virtual patching as a bridge: apply the rule within hours, then ship the real fix, prioritising flaws that are known to be exploited and reachable from the internet, as our guide to AI vulnerability management describes. Regular scanning and independent testing then confirm that the fixes hold; see penetration testing vs vulnerability scanning for how the two fit together.

Protecting a PHP Website: A Practical Stack

  1. Run a supported PHP version. According to the official supported versions page, PHP 8.2 stops receiving security fixes on 31 December 2026, so plan an upgrade to 8.4 or later if you are still on it.
  2. Keep the CMS, plugins and Composer packages updated, and run composer audit in your deployment pipeline to catch known vulnerable dependencies.
  3. Use prepared statements through PDO for every database query.
  4. Lock down the server with a default-deny firewall, SSH keys and no public database ports.
  5. Put a WAF in front, using a cloud WAF or ModSecurity or Coraza with the Core Rule Set, which offers rule exclusion plugins for popular applications such as WordPress.
  6. Protect uploads: validate file types, store files outside the web root where possible, scan them and never execute PHP from upload folders.
  7. Monitor and back up: file integrity monitoring, centralised logs and tested off-site backups.

Our checklist on how to protect a website from hackers expands on each step.

Choosing and Tuning a WAF

  • Start in detection mode for one to two weeks, then switch to blocking once false positives are under control.
  • Prefer managed rules that update automatically, so new virtual patches arrive without manual work.
  • Protect APIs as well as pages, including mobile app back ends and webhooks.
  • Send WAF logs to the same place as your application logs, so that blocked attacks can be correlated with other events.
  • Check performance: edge WAFs often add very little latency and can even speed sites up through caching, while badly tuned on-server rules can slow heavy pages.
  • Budget realistically: cloud WAFs range from free tiers with basic rules to enterprise plans with bot management and dedicated support, so match the plan to your risk.

Frequently Asked Questions

What is the difference between a WAF and a firewall?

A network firewall controls which connections can reach which systems, based on addresses, ports and protocols. A WAF inspects the content of web requests and blocks application attacks such as SQL injection and cross-site scripting.

Do I need a WAF if I already have a firewall?

If you run a public website, web app or API, a WAF adds protection a firewall cannot provide, because the firewall must allow web traffic through and cannot see attacks inside it.

Is antivirus enough to protect a website?

No. Antivirus protects devices from malware, but it does not inspect web requests or stop attacks on your application's code and logic.

Can a WAF stop all SQL injection attacks?

It stops most common attempts, but skilled attackers can sometimes bypass generic rules. Parameterised queries in your code are the real fix, with the WAF as an extra layer.

Does a WAF slow down a website?

Usually only slightly. Cloud WAFs on a CDN often add negligible delay and may improve speed through caching, while on-server WAFs need tuning on high-traffic sites.

Do small websites need a WAF?

Small sites are attacked constantly by automated tools, and many run plugins with known vulnerabilities. A free or low-cost cloud WAF is a sensible, inexpensive layer for most of them.

Get Layered Protection for Your Website

Whether you are deciding on a WAF vs firewall set-up for a new site or tuning both on an existing one, we build and harden PHP and JavaScript websites, configure firewalls and WAFs, tune rules to avoid blocking real customers and fix vulnerabilities at the source. Contact our team for a security review of your site.

Want this built for you?

Our team offers Website Deploy On Vercel — get a free quote.

View Services