
How to set up a firewall for a WordPress website?
- Sajjad
- WordPress, Security
- 12 Sep, 2026
To set up a firewall for a WordPress website, choose at least one web application firewall (WAF) layer: a plugin-based firewall like Wordfence that runs on your server, or a cloud firewall like Cloudflare or Sucuri that filters traffic before it reaches your host. If you manage your own server, add a network firewall such as UFW to close unused ports. Then tune the rules, test your site, and keep the firewall updated.
A firewall is one of the most effective ways to stop common WordPress attacks, including brute-force logins, SQL injection attempts, and exploits targeting vulnerable plugins. This guide explains the different types of firewalls, how to set up each one step by step, which WordPress-specific rules are worth adding, and how to avoid locking yourself out along the way.
What Is a WordPress Firewall?
A firewall inspects incoming traffic and blocks anything that looks malicious. For WordPress sites, there are two main kinds:
- Network firewalls control which ports and IP addresses can connect to your server at all. For a web server, you usually allow only SSH, HTTP, and HTTPS.
- Web application firewalls (WAFs) inspect HTTP requests themselves. They look at URLs, query strings, form data, and headers for attack patterns like
' OR 1=1 --or<script>payloads, and block requests that match known exploits.
Most WordPress attacks happen over normal web traffic on ports 80 and 443, so a WAF is the most important layer for a typical site. A network firewall matters if you run your own VPS or dedicated server.
Types of Web Application Firewalls
Plugin-Based (Endpoint) WAF
A plugin WAF runs inside your WordPress installation. Wordfence is the best-known example, and others like All-In-One Security (AIOS), Solid Security, Shield Security, and MalCare include firewall features.
Pros: Easy to install, understands WordPress context (logged-in users, plugins, capabilities), no DNS changes.
Cons: Every request still reaches your server and consumes resources. Can't absorb large traffic floods.
Cloud-Based (DNS-Level) WAF
A cloud WAF sits in front of your server as a reverse proxy. You route traffic through the provider by changing your DNS. Cloudflare and Sucuri are the most common choices for WordPress.
Pros: Blocks attacks before they reach your server, mitigates DDoS attacks, often includes a CDN that improves speed.
Cons: Requires DNS changes, advanced features usually need a paid plan, and attackers can bypass it if they discover your server's real IP.
Server-Level WAF
Some hosts run a WAF at the web server level, such as ModSecurity with the OWASP Core Rule Set, or Imunify360. Managed WordPress hosts often include this by default.
Pros: No setup for you if your host provides it, low overhead.
Cons: You usually have little control over the rules on shared hosting.
For most sites, a cloud WAF plus a plugin for login security and scanning, or a plugin WAF on its own for smaller sites, is a solid starting point. Check what your host already provides before adding more.
Option 1: Set Up a Plugin Firewall With Wordfence
Wordfence is a good default because its free version includes a capable endpoint firewall.
-
Back up your site: Take a full backup of files and the database before changing security settings.
-
Install Wordfence: Go to Plugins > Add New Plugin, search for Wordfence Security, then install and activate it.
-
Complete the setup: Enter an email for alerts and decide whether to use the free or premium version.
-
Optimize the firewall: Go to Wordfence > Firewall. You'll see a prompt to enable Extended Protection. Click Optimize the Wordfence Firewall. Wordfence will detect your server configuration and suggest a method, typically modifying
.htaccess,.user.ini, orphp.inito setauto_prepend_file. This makes the firewall load before WordPress, so it can block attacks against vulnerable plugins before their code runs. -
Download the backup it offers: Wordfence offers to download a copy of the file it's about to change. Keep it in case you need to revert.
-
Start in Learning Mode: New installations start in Learning Mode for about a week. During this time, Wordfence learns normal traffic patterns to reduce false positives. Use your site normally, including admin tasks, form submissions, and checkout if you run a store.
-
Switch to Enabled and Protecting: After the learning period, set the firewall status to Enabled and Protecting.
-
Configure brute-force protection: Under Wordfence > All Options > Brute Force Protection, set sensible lockout limits and enable immediate lockout for invalid usernames if you don't have many users mistyping.
-
Enable rate limiting: Under Rate Limiting, throttle or block crawlers and humans that make excessive requests. Start with moderate settings and tighten gradually.
If Wordfence's extended protection is enabled on an Apache server, you'll see something like this added to .htaccess:
# Wordfence WAF
<IfModule mod_php.c>
php_value auto_prepend_file '/var/www/example.com/public_html/wordfence-waf.php'
</IfModule>
# END Wordfence WAF
On Nginx with PHP-FPM, Wordfence uses a .user.ini file instead, which PHP reads automatically:
; Wordfence WAF
auto_prepend_file = '/var/www/example.com/public_html/wordfence-waf.php'
; END Wordfence WAF
PHP caches .user.ini files for a few minutes by default, so it can take a short time before the firewall shows as optimized.
Option 2: Set Up a Cloud Firewall With Cloudflare
Cloudflare's free plan includes DDoS protection, a CDN, and custom firewall rules. Paid plans add managed WAF rulesets, including WordPress-specific rules.
Connect Your Domain
- Create an account: Sign up at Cloudflare and add your domain.
- Review DNS records: Cloudflare scans your existing records. Check that your A, AAAA, CNAME, and MX records are correct. Make sure mail records stay unproxied (grey cloud).
- Proxy your website records: Set the orange cloud on the records for your root domain and
www. - Change nameservers: Update your domain's nameservers at your registrar to the ones Cloudflare provides. Propagation usually takes minutes to a few hours.
- Set SSL mode: Under SSL/TLS > Overview, use Full (strict) if your server has a valid certificate. Avoid Flexible, which can cause redirect loops with WordPress and leaves traffic between Cloudflare and your server unencrypted.
Add WordPress-Specific Custom Rules
Go to Security > WAF > Custom rules and create rules like these. The expressions use Cloudflare's rule language.
Challenge logins from outside your country (only if all your admins are in one country):
(http.request.uri.path eq "/wp-login.php" and ip.src.country ne "GB")
Set the action to Managed Challenge. Replace GB with your country code.
Block direct access to XML-RPC (if you don't use Jetpack, the WordPress mobile app, or other XML-RPC clients):
(http.request.uri.path eq "/xmlrpc.php")
Set the action to Block.
Protect the admin area while allowing AJAX requests that front-end features rely on:
(starts_with(http.request.uri.path, "/wp-admin/") and not http.request.uri.path eq "/wp-admin/admin-ajax.php" and not ip.src in {203.0.113.10})
Set the action to Managed Challenge, and replace the example IP with your own static IP if you have one. If you don't have a static IP, skip the IP condition.
Enable Managed Rules and Rate Limiting
- Managed rules: On paid plans, enable the Cloudflare Managed Ruleset and the OWASP Core Ruleset under Security > WAF > Managed rules. The Cloudflare set includes WordPress-specific protections.
- Rate limiting: Create a rate limiting rule for
/wp-login.phpso that IPs sending too many POST requests in a short time are blocked or challenged.
Restore Real Visitor IPs
Behind Cloudflare, your server sees Cloudflare's IP addresses rather than visitors'. Security plugins need the real IP to block attackers correctly. In Wordfence, go to All Options > General Wordfence Options > How does Wordfence get IPs and choose the Cloudflare option. On Nginx, you can use the real_ip module with Cloudflare's published IP ranges.
Option 3: Set Up a Cloud Firewall With Sucuri
Sucuri's Website Firewall is a paid service that includes a WAF, CDN, DDoS mitigation, and virtual patching.
- Sign up for a plan: Choose a plan that includes the firewall.
- Add your site: Enter your domain in the Sucuri dashboard. Sucuri detects your hosting IP.
- Update DNS: Point your domain's A record to the IP Sucuri provides, or change nameservers if you prefer.
- Configure SSL: Enable HTTPS on the firewall so visitors connect securely to Sucuri's edge.
- Adjust settings: Enable options such as protecting the admin area, blocking XML-RPC, and caching levels.
- Install the Sucuri plugin (optional): It lets you clear the firewall cache and view settings from your dashboard.
Protect Your Origin Server
A cloud WAF only helps if attackers can't reach your server directly. If someone finds your origin IP through old DNS records or email headers, they can bypass the firewall.
To prevent this, allow web traffic only from your firewall provider's IP ranges. On Nginx, you can restrict access in your server block like this (use the current ranges your provider publishes):
# Example ranges only - replace with your provider's published list
allow 173.245.48.0/20;
allow 103.21.244.0/22;
deny all;
Some hosts let you do this at the network level instead, and Cloudflare also offers Authenticated Origin Pulls and Cloudflare Tunnel as alternatives. Test on staging first, because incorrect ranges will make your site unreachable.
Option 4: Add a Server Network Firewall
If you run WordPress on your own VPS, add a network firewall to close everything except the ports you need. On Ubuntu and Debian, UFW is the simplest option.
Warning: Enabling a firewall on a remote server can lock you out if SSH isn't allowed first. Keep your current SSH session open, open a second session to test, and know how to access your provider's web console in an emergency.
# Allow SSH first (use your custom port if you changed it)
sudo ufw allow OpenSSH
# Allow web traffic
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# Set sensible defaults
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Enable and verify
sudo ufw enable
sudo ufw status verbose
On RHEL, Rocky, or AlmaLinux, use firewalld instead, with commands like sudo firewall-cmd --permanent --add-service=https followed by sudo firewall-cmd --reload. Our dedicated UFW guide covers this topic in more depth.
Add WordPress-Specific Server Rules
Whichever WAF you use, a few server-level rules add useful defense in depth. On Apache 2.4, you can block direct web access to sensitive files with .htaccess:
# Block access to wp-config.php
<Files wp-config.php>
Require all denied
</Files>
# Block XML-RPC if you don't use it
<Files xmlrpc.php>
Require all denied
</Files>
On Nginx, the equivalent rules go inside your server block:
location = /wp-config.php {
deny all;
}
location = /xmlrpc.php {
deny all;
}
Run sudo nginx -t before reloading to catch syntax errors. Only block XML-RPC if you're sure nothing on your site depends on it.
Test and Tune Your Firewall
After setup, verify that everything works:
- Browse your site as a visitor: Check key pages, forms, search, and checkout.
- Log in and perform admin tasks: Edit posts, upload media, update plugins, and use the Site Editor.
- Test integrations: Payment gateways, webhooks, the REST API, and third-party services (like email marketing tools) sometimes get blocked.
- Review firewall logs: Look at blocked requests in Wordfence's Live Traffic, Cloudflare's Security Events, or Sucuri's audit logs. Check for false positives.
- Allowlist carefully: If a legitimate request is blocked, create an exception for that specific path or parameter rather than disabling whole rule groups.
Keep Your Firewall Effective
- Update firewall rules: Premium plans often deliver new rules in real time. Free plans may lag behind, so updating plugins promptly still matters.
- Review logs regularly: Weekly is a good rhythm for busy sites.
- Revisit rules after changes: New plugins, integrations, or site features can require rule adjustments.
- Don't rely on the firewall alone: A firewall reduces risk but doesn't replace updates, strong passwords, 2FA, and backups.
What to Do If You Lock Yourself Out
It happens. Here's how to recover:
- Wordfence lockout: Use the unlock email link from the lockout page, or temporarily disable the plugin by renaming
wp-content/plugins/wordfencevia SFTP. If the WAF still loads, remove theauto_prepend_filelines from.htaccessor.user.ini. - Cloudflare rule blocks you: Log in to Cloudflare and pause or edit the rule under Security > WAF.
- UFW blocks SSH: Use your hosting provider's web console to log in and run
sudo ufw allow OpenSSH.
FAQ: WordPress Firewalls
Yes, for most sites it's one of the most valuable security layers. A web application firewall blocks common attacks like brute-force logins and plugin exploits before they succeed, which reduces the risk from vulnerabilities you haven't patched yet.
A cloud firewall blocks attacks before they reach your server and helps with traffic spikes, while a plugin firewall understands WordPress context better. Many sites use a cloud firewall with a security plugin for layered protection.
It provides DDoS protection, a CDN, and a limited number of custom rules, which helps a lot. Managed WAF rulesets require a paid plan, so pair the free plan with a security plugin like Wordfence for fuller coverage.
A cloud firewall often speeds your site up because of caching and filtered traffic. A plugin firewall adds a small amount of processing to each request, which is usually minor on decent hosting.
Yes. Configure Wordfence to read the real visitor IP from Cloudflare's headers under its general options, so it blocks attackers rather than Cloudflare's own servers.
Learning Mode lets the Wordfence firewall observe normal traffic on your site for about a week before it starts blocking. This helps avoid false positives that could break legitimate features.
If nothing on your site uses XML-RPC, blocking it removes a common brute-force target. Jetpack, the WordPress mobile app, and some remote publishing tools rely on it, so check before blocking.
Conclusion
Setting up a firewall for WordPress comes down to choosing the right layers for your site. A plugin WAF like Wordfence is quick to install and understands WordPress deeply. A cloud WAF like Cloudflare or Sucuri stops attacks before they reach your server and improves performance. If you manage your own server, a network firewall like UFW closes the doors you don't need open.
Whichever approach you choose, start carefully, test thoroughly, and review logs to catch false positives. Protect your origin server when using a cloud WAF, keep your firewall rules up to date, and remember that a firewall works best alongside regular updates, strong authentication, and reliable backups.


