Skip to content

How to Secure an Ubuntu Server for WordPress on Hetzner in 12 Steps (2026)

Summarize with AI

Updated November 2026. Covers Ubuntu 26.04 LTS with PHP 8.5, Apache, MariaDB and CrowdSec. No affiliate links in this guide: Hetzner, Cloudflare and CrowdSec pay me nothing.

Hetzner hands you a clean Ubuntu server. Making it safe is your job.

The defaults help a little. A Hetzner Cloud Firewall with no inbound rules drops all inbound traffic, and an SSH key can only be added while you create the server, not later in the console. Everything after that, from SSH settings to the PHP pool, is up to you.

Most Linux hardening checklists treat every server the same. A WordPress site behind Cloudflare has its own weak spots: the real visitor IP hidden behind Cloudflare, PHP running with too many rights, and a database listening on a port nobody needs. This guide is built around one Hetzner server, one WordPress site, Cloudflare in front and CrowdSec watching the logs, in the order I would set up a new server today.

My own site runs on a single Hetzner box with this stack: Apache, PHP-FPM, MariaDB and Redis on the same machine, nftables as the host firewall, CrowdSec with its firewall bouncer, ModSecurity with the OWASP Core Rule Set, and Cloudflare in front with Authenticated Origin Pulls. Where my setup differs from what I recommend for a new server, I say so.

If a menu in the Hetzner or Cloudflare dashboard doesn't match what you see, they have probably renamed it. Tell me in the comments and I'll update the guide.

My recommended setup:

  • Ubuntu 26.04 LTS on a Hetzner Cloud server, with Hetzner backups on
  • SSH with keys only, no root login, reachable from your IP only
  • nftables with a default drop policy, plus the Hetzner Cloud Firewall
  • Automatic security updates, with a reboot at a quiet hour
  • One PHP-FPM pool per site, running as its own Linux user
  • MariaDB on a Unix socket with no network port
  • Cloudflare proxy with Full (strict) TLS and Authenticated Origin Pulls
  • CrowdSec with the nftables bouncer and the Apache module

How the layers fit together

A request to your site passes seven layers before it reaches the database. Each one stops a different kind of problem, and each one assumes the layer above it could fail.

The seven layers a request passes on its way to WordPress1VisitorBrowser, search bot or attack scanner2CloudflareProxy, TLS and edge WAF.Hides the real server IP3Hetzner Cloud FirewallPorts 80 and 443 from Cloudflare only.SSH from your own IP only4nftables + CrowdSec bouncerSame rules again, on the server.Drops IPs that CrowdSec banned5ApacheAccepts only Cloudflare's client certificate.WAF: ModSecurity or CrowdSec AppSec6PHP-FPM poolOwn Linux user, open_basedir,no shell functions7MariaDBListens on a Unix socket only.No network port at all
The path of one request in this setup, from visitor to database

Layers 2 to 4 decide who can connect at all. Layer 5 inspects what they send. Layers 6 and 7 limit the damage if WordPress or a plugin gets exploited anyway.

What you need

  • A Hetzner account and a payment method
  • A domain with its DNS managed in Cloudflare (the free plan is enough)
  • A terminal with OpenSSH: macOS, Linux, or Windows 11 with the built-in ssh client
  • A fixed IP address you connect from. A VPN with a dedicated IP works too.

About that last point: my SSH allowlist holds a NordVPN dedicated IP, so I can reach the server from any network without opening SSH to the world. If you go that way, my NordVPN settings guide covers the app side. When the dedicated IP changes, update the allowlist in both firewalls before you disconnect, or you will need the Hetzner web console to get back in.

Step 1: Prepare the Hetzner project, SSH key and firewall

Do this before you create the server. The SSH key in particular can't be added through the console afterwards.

On your own computer, create an Ed25519 key. Ed25519 is a modern key type that is short and fast, and it is the first host key type in Mozilla's OpenSSH guidelines.

ssh-keygen -t ed25519 -C "hetzner-wordpress" -f ~/.ssh/hetzner_wp

Protect the key with a passphrase when it asks. Then, in the Hetzner Console, open your project and go to Security > SSH keys > Add SSH key. Paste the content of ~/.ssh/hetzner_wp.pub (the .pub file, never the private one).

Next, go to Firewalls > Create Firewall and add these inbound rules:

ProtocolPortSourceWhy
TCP22Your IP onlySSH for the first login. You change the port in step 4.
TCP80Cloudflare IPv4 and IPv6 rangesHTTP, only from Cloudflare
TCP443Cloudflare IPv4 and IPv6 rangesHTTPS, only from Cloudflare
ICMP-AnyPing, useful for monitoring. Optional.

Copy the ranges from cloudflare.com/ips. Hetzner lets you paste several addresses into one rule, separated by commas or spaces, and allows up to 500 effective rules, so the full Cloudflare list fits. Leave outbound rules empty: the server needs to reach update mirrors, CrowdSec and WordPress.org.

If this breaks something: a Hetzner firewall with no inbound rules blocks everything, including you. You can always log in through the browser console in the Hetzner Console, which works even when SSH doesn't.

Step 2: Create the server

Go to Servers > Add server and work through the form from top to bottom:

  • Location: the region closest to your readers. For a European audience, any of the EU locations.
  • Image: Ubuntu 26.04. If your project still lists only 24.04, every step below works the same, but PHP will be 8.3 instead of 8.5.
  • Type: shared vCPU is fine for a small blog. My site runs on a dedicated-vCPU CCX plan, so other customers' load on the same host can't slow it down.
  • Networking: keep public IPv4 and IPv6 on
  • SSH keys: tick the key from step 1
  • Firewalls: tick the firewall from step 1
  • Backups: tick it. Hetzner takes one backup per day and keeps seven slots, deleting the oldest when all are used.
  • Name: something you will recognise in logs, like wp-prod-01

Why Ubuntu 26.04? It is a long-term support (LTS) release, and its own repositories carry PHP 8.5 and MariaDB 11.8. You can confirm this on the server with apt policy php mariadb-server. WordPress 7.0 recommends PHP 8.4 or 8.5 and MariaDB 10.11, 11.4 or 11.8 for new installs, so the stock packages already match. That means no third-party PHP repository to trust and keep track of.

Cloud-config (the optional box for a first-boot script) can stay empty. Doing the steps by hand once teaches you where everything lives.

Step 3: First login, updates and an admin user

Hetzner shows the server's IP once it is running. Log in as root with your new key:

ssh -i ~/.ssh/hetzner_wp root@YOUR_SERVER_IP

Update everything first, set the time zone (logs are easier to read in your own time) and give the server a proper name:

apt update && apt full-upgrade -y
timedatectl set-timezone Europe/Riga
hostnamectl set-hostname wp-prod-01
reboot

Then create a normal user for daily work and give it sudo rights. I use deploy in this guide; pick your own name.

adduser deploy
usermod -aG sudo deploy
rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy

The rsync line copies root's authorised key to the new user. Now open a second terminal and test it, without closing the root session:

ssh -i ~/.ssh/hetzner_wp deploy@YOUR_SERVER_IP
sudo whoami   # should print: root

Keep a working session open during every SSH change in this guide.

Step 4: Lock down SSH

On Ubuntu, /etc/ssh/sshd_config loads every file in /etc/ssh/sshd_config.d/ first, and for most settings OpenSSH keeps the first value it reads. Ubuntu cloud images often have a 50-cloud-init.conf there, so give yours a lower number to load first:

sudo nano /etc/ssh/sshd_config.d/10-hardening.conf
# Pick your own high port and write it down
Port 49222

PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
AllowUsers deploy

MaxAuthTries 3
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2

X11Forwarding no
AllowAgentForwarding no
AllowTcpForwarding no
PermitTunnel no
PermitUserEnvironment no
LogLevel VERBOSE

The idea behind this file: only one user, only keys, only from your IP, and no extra doors such as port forwarding or X11. UseDNS stays at its default of no, because a reverse DNS lookup on every login adds delay and protects little on a server that only accepts keys from one IP.

LogLevel VERBOSE: ON - it logs the fingerprint of the key used for each login, so you can tell which of your keys was used if one ever leaks.

Port change: DEPENDS - a new port won't stop a real attacker, but it removes most of the brute-force noise from your logs. Since SSH is already limited to your IP, I treat it as log hygiene, nothing more.

Before you restart anything, add the new port to the Hetzner firewall (TCP 49222, source: your IP). Then check the config and apply it:

sudo sshd -t
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket

The daemon-reload line matters. Ubuntu starts SSH through systemd socket activation, and a port change has no effect until systemd regenerates the socket. Restarting ssh.service alone leaves SSH on port 22, which confused many people after the 24.04 release.

Test from the second terminal with ssh -p 49222 -i ~/.ssh/hetzner_wp deploy@YOUR_SERVER_IP. When it works, remove the port 22 rule from the Hetzner firewall.

If this breaks something: use the Hetzner web console, delete 10-hardening.conf, and run the three commands above again.

Step 5: Add a host firewall with nftables

The Hetzner firewall sits in front of the server. nftables is the firewall inside it, built into the Linux kernel. Running both sounds like overkill until the day someone edits the Hetzner rules in a hurry.

I use nftables directly instead of UFW. UFW is a friendlier front end, but CrowdSec's bouncer and my own blocklists both manage nftables sets, and one tool in one place is easier to debug. If UFW is active, turn it off first:

sudo ufw disable 2>/dev/null
sudo apt install -y nftables
sudo cp /etc/nftables.conf /root/nftables.conf.bak

Replace /etc/nftables.conf with this. Fill the two Cloudflare sets with the current ranges from cloudflare.com/ips (the ones shown are only the first entry of each list):

#!/usr/sbin/nft -f
flush ruleset

define ADMIN_IP = 203.0.113.10
define SSH_PORT = 49222

table inet filter {
  set cloudflare_v4 {
    type ipv4_addr; flags interval
    elements = { 173.245.48.0/20 }   # add all IPv4 ranges here
  }
  set cloudflare_v6 {
    type ipv6_addr; flags interval
    elements = { 2400:cb00::/32 }    # add all IPv6 ranges here
  }

  chain input {
    type filter hook input priority 0; policy drop;

    iif lo accept
    ct state established,related accept
    ct state invalid drop

    ip protocol icmp icmp type echo-request limit rate 5/second accept
    ip6 nexthdr icmpv6 accept

    ip saddr $ADMIN_IP tcp dport $SSH_PORT accept
    ip saddr @cloudflare_v4 tcp dport { 80, 443 } accept
    ip6 saddr @cloudflare_v6 tcp dport { 80, 443 } accept

    counter drop
  }

  chain forward {
    type filter hook forward priority 0; policy drop;
  }

  chain output {
    type filter hook output priority 0; policy accept;
  }
}

The ICMPv6 line accepts all ICMPv6 on purpose: IPv6 needs it for neighbour discovery, and blocking it breaks the connection in ways that are slow to diagnose. Check the file, load it and make it start at boot:

sudo nft -c -f /etc/nftables.conf   # syntax check only
sudo systemctl enable --now nftables
sudo nft list ruleset

Cloudflare changes its ranges rarely, but it does change them. On my server a small cron job pulls the list and rebuilds the sets, and a second one refreshes Apache's trusted proxy list from step 10. If you skip that, put a reminder in your calendar.

If this breaks something: sudo nft flush ruleset removes every rule until the next reboot. Run it from the web console, never over the SSH session you are trying to save.

Step 6: Turn on automatic security updates

Ubuntu Server already does most of this. The unattended-upgrades package is installed by default and installs security updates once a day. Check that it runs:

systemctl status unattended-upgrades
sudo unattended-upgrade --dry-run --debug | tail -20

What it doesn't do by default is reboot. Kernel and OpenSSL fixes need one, so I recommend letting the server restart itself at a quiet hour. Open /etc/apt/apt.conf.d/50unattended-upgrades and set:

Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "04:30";
Unattended-Upgrade::Remove-Unused-Dependencies "true";

Automatic reboot: ON for a single blog server, where a minute of downtime at 04:30 costs nothing. Turn it off if the server runs something that must not restart unattended.

One exception on my own server: I hold the database packages with apt-mark hold and update them by hand. A database restart in the middle of a busy hour is the one update I want to watch. For a quiet new site I wouldn't bother.

Automatic updates cover the operating system only. WordPress, plugins and themes need their own update routine. My note on the CISA exploited vulnerabilities list explains how I decide what to patch first.

Step 7: Install the web server, PHP and the database

Install the web stack from Ubuntu's own repositories. The php-* names are meta packages that point to the release's default PHP version, so the same line works on 24.04 and 26.04:

sudo apt install -y apache2 mariadb-server \
  php-fpm php-mysql php-curl php-gd php-intl php-mbstring \
  php-xml php-zip php-imagick
php -v   # 8.5.x on Ubuntu 26.04

Don't install libapache2-mod-php: it runs PHP inside Apache as one shared user, which is exactly what step 8 avoids. Connect Apache to PHP-FPM and load the modules you need later:

sudo a2enmod proxy_fcgi setenvif rewrite headers ssl remoteip
sudo a2dismod -f autoindex status
sudo systemctl restart apache2

autoindex lists folder contents when there is no index file, and status exposes a server status page. Neither belongs on a public server. Then hide version numbers in /etc/apache2/conf-available/security.conf:

ServerTokens Prod
ServerSignature Off
TraceEnable Off

Next, MariaDB. Run the hardening script and answer yes to removing anonymous users, the test database and remote root login:

sudo mariadb-secure-installation

WordPress and MariaDB live on the same server, so the database needs no network port at all. Create /etc/mysql/mariadb.conf.d/60-hardening.cnf:

[mysqld]
skip-networking
local-infile = 0

skip-networking makes MariaDB listen on its Unix socket only. A socket is a file on disk, so nothing on the internet can even attempt a login. Restart it and create the WordPress database with a user that can only touch that one database:

sudo systemctl restart mariadb
sudo mariadb <<'SQL'
CREATE DATABASE wp_example CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'wp_example'@'localhost' IDENTIFIED BY 'USE-A-LONG-RANDOM-PASSWORD';
GRANT ALL PRIVILEGES ON wp_example.* TO 'wp_example'@'localhost';
FLUSH PRIVILEGES;
SQL

WordPress Site Health checks your database version against its recommended minimum, which was raised to MariaDB 10.11 in July 2026. The 11.8 package on Ubuntu 26.04 is well above it.

Step 8: Give WordPress its own PHP-FPM pool and safe PHP settings

A PHP-FPM pool is a group of PHP worker processes with its own settings. Ubuntu ships one pool called www that runs as www-data, the same user as Apache. If a plugin gets exploited, the attacker then has the same rights as your web server.

My own server still runs its site as www-data, because it grew from an older layout. On a new server I would start with a separate user per site, so that is what I show here:

sudo useradd --system --home /var/www/example.com --shell /usr/sbin/nologin wp_example
sudo mkdir -p /var/www/example.com/{public_html,tmp,logs}
sudo chown -R wp_example:www-data /var/www/example.com
sudo chmod 2750 /var/www/example.com

Create the pool file /etc/php/8.5/fpm/pool.d/example.conf:

[example]
user = wp_example
group = wp_example

listen = /run/php/example.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

pm = dynamic
pm.max_children = 10
pm.start_servers = 2
pm.min_spare_servers = 2
pm.max_spare_servers = 4
pm.max_requests = 500

security.limit_extensions = .php

php_admin_value[open_basedir] = /var/www/example.com:/usr/share/php:/run/mysqld
php_admin_value[upload_tmp_dir] = /var/www/example.com/tmp
php_admin_value[sys_temp_dir] = /var/www/example.com/tmp
php_admin_value[session.save_path] = /var/www/example.com/tmp
php_admin_value[disable_functions] = exec,passthru,shell_exec,system,proc_open,popen,pcntl_exec
php_admin_flag[allow_url_include] = off
php_admin_flag[display_errors] = off
php_admin_flag[log_errors] = on
php_admin_value[error_log] = /var/www/example.com/logs/php-error.log

php_admin_value[memory_limit] = 256M
php_admin_value[upload_max_filesize] = 64M
php_admin_value[post_max_size] = 64M
php_admin_value[max_execution_time] = 60

What the security lines do:

SettingValueWhy
open_basedirthe site folderPHP can't read files outside it, such as /etc/passwd or another site
disable_functionsexec, system and similara web shell can't run Linux commands
security.limit_extensions.phpan uploaded image.jpg with PHP inside is never executed
display_errorsofferrors go to the log, not to visitors, so file paths stay private
tmp and session pathsthe site's own tmpuploads and sessions stay inside open_basedir, away from other users
memory_limit256Ma runaway plugin can't eat all the RAM

disable_functions: ON, with one caveat. A few backup and image plugins call exec. If one breaks, check the PHP log before you remove anything from the list, and remove only the one function it needs. WP-CLI is not affected, because it runs through the PHP command line, which has its own php.ini.

On the memory limit: my site runs Elementor and sits at 512M. It used to be -1, meaning no limit at all, until I set a cap in October 2026. Start at 256M and raise it only when the PHP log asks for more.

Then set three values in /etc/php/8.5/fpm/php.ini, because they apply to the whole PHP-FPM service:

expose_php = Off
opcache.memory_consumption = 256
opcache.max_accelerated_files = 60000

expose_php = Off removes the PHP version from response headers. The OPcache values keep compiled PHP in memory, which matters for speed with large plugins. Disable the default pool and its global Apache handler so nothing runs as www-data by accident, then test and restart:

sudo mv /etc/php/8.5/fpm/pool.d/www.conf /etc/php/8.5/fpm/pool.d/www.conf.disabled
sudo a2disconf php8.5-fpm   # global handler that points to the www pool
sudo php-fpm8.5 -t && sudo systemctl restart php8.5-fpm

If this breaks something: Ubuntu's AppArmor (a kernel feature that limits what each program may touch) can block PHP-FPM from paths it doesn't expect. On my server, the PHP-FPM profile needed an extra rule before PHP could reach the MariaDB socket. Look for denials with journalctl -k | grep DENIED and add the missing path to /etc/apparmor.d/local/php-fpm instead of turning AppArmor off.

Step 9: Install WordPress with WP-CLI and harden wp-config.php

WP-CLI is the official command line tool for WordPress. It installs and updates sites without a browser, and it is the safest way to run WordPress tasks as the site user:

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
php wp-cli.phar --info
sudo install -m 755 wp-cli.phar /usr/local/bin/wp

Download WordPress and create the config as wp_example, never as root. Files created by root can't be updated by WordPress later, and you will chase permission errors for weeks.

cd /var/www/example.com/public_html
sudo -u wp_example wp core download
sudo -u wp_example wp config create --dbname=wp_example --dbuser=wp_example \
  --dbpass='USE-A-LONG-RANDOM-PASSWORD' --dbhost=localhost
sudo -u wp_example wp core install --url=https://example.com --title="Example" \
  --admin_user=pick-a-name --admin_email=you@example.com

Leave out --admin_password and WP-CLI generates a strong one and prints it once. Don't call the admin user admin. Then add these lines to wp-config.php, above the "That's all, stop editing" comment:

define( 'DISALLOW_FILE_EDIT', true );
define( 'FORCE_SSL_ADMIN', true );
define( 'WP_DEBUG', false );
define( 'DISABLE_WP_CRON', true );

DISALLOW_FILE_EDIT: ON - it removes the theme and plugin code editor from the dashboard. If someone steals an admin login, that editor is the fastest way to plant code.

DISABLE_WP_CRON: ON - WordPress normally runs its scheduled tasks when a visitor loads a page. Behind a page cache that is unreliable. Run it from the system cron as the site user instead (sudo crontab -e):

*/5 * * * * /usr/sbin/runuser -u wp_example -- /usr/bin/php /var/www/example.com/public_html/wp-cron.php >/dev/null 2>&1

I use runuser instead of sudo in cron because my server logs every sudo session, and a cron job every five minutes would fill that log with noise.

Finally, set the file permissions. PHP writes as the owner, Apache reads static files through the www-data group, and the 2 in 2750 (the setgid bit) makes new uploads inherit that group. wp-config.php holds the database password, so only the owner may read it:

cd /var/www/example.com/public_html
sudo find . -type d -exec chmod 2750 {} \;
sudo find . -type f -exec chmod 640 {} \;
sudo chmod 600 wp-config.php

An extra step I use on my own server: the database password and salts live in a separate file under /etc/wordpress/, owned by root and readable by the site's group, and wp-config.php only includes it. A backup of the webroot then contains no secrets.

Step 10: Put Cloudflare in front and accept only Cloudflare

In Cloudflare, point your domain's A and AAAA records to the server IPs with the proxy turned on (the orange cloud). Then make these changes in the Cloudflare dashboard:

  • In SSL/TLS > Overview, set the mode to Full (strict).
  • In SSL/TLS > Origin Server, create an Origin Certificate and save the certificate and key on the server in /etc/ssl/cloudflare/.
  • On the same page, turn on Authenticated Origin Pulls.
  • Download Cloudflare's origin pull CA certificate from the AOP setup page into the same folder.

Authenticated Origin Pulls (AOP) means Cloudflare shows a client certificate every time it connects to your server, and Apache refuses any connection without it. Someone who finds your server's real IP and connects to it directly gets a TLS error instead of your site. Here is the virtual host, with the PHP pool from step 8:

<VirtualHost *:443>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html

    SSLEngine on
    SSLCertificateFile    /etc/ssl/cloudflare/example.com.pem
    SSLCertificateKeyFile /etc/ssl/cloudflare/example.com.key

    # Authenticated Origin Pulls
    SSLVerifyClient require
    SSLVerifyDepth 1
    SSLCACertificateFile /etc/ssl/cloudflare/authenticated_origin_pull_ca.pem

    <FilesMatch "\.php$">
        SetHandler "proxy:unix:/run/php/example.sock|fcgi://localhost"
    </FilesMatch>

    <Directory /var/www/example.com/public_html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # Never run PHP from the uploads folder
    <Directory /var/www/example.com/public_html/wp-content/uploads>
        <FilesMatch "\.php$">
            Require all denied
        </FilesMatch>
    </Directory>

    # XML-RPC is a favourite brute-force target
    <Files xmlrpc.php>
        Require all denied
    </Files>

    ErrorLog  /var/www/example.com/logs/error.log
    CustomLog /var/www/example.com/logs/access.log combined
</VirtualHost>

The three SSL... lines under the AOP comment are the Apache example from Cloudflare's own docs. There is a limit: the global AOP certificate is not exclusive to your account. Any Cloudflare customer who points a domain at your IP also passes the check. Zone-level AOP with your own certificate closes that gap, and it is worth the extra ten minutes once everything else works.

Blocking xmlrpc.php breaks the Jetpack plugin and some mobile apps. If you use either, leave that block out and let CrowdSec watch the file instead.

Behind Cloudflare, every request in your Apache log comes from a Cloudflare IP. CrowdSec reads those logs, so without a fix it bans Cloudflare's own addresses. Apache's mod_remoteip fixes this by reading the visitor's real IP from Cloudflare's header, but only for requests that really come from Cloudflare. Create /etc/apache2/conf-available/cloudflare-remoteip.conf:

RemoteIPHeader CF-Connecting-IP
RemoteIPTrustedProxyList /etc/apache2/cloudflare-ips.txt
LogFormat "%a %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined

Put the same Cloudflare ranges from step 5 into /etc/apache2/cloudflare-ips.txt, one per line. The LogFormat line changes %h to %a, so the log shows the real client IP. Enable everything and test:

sudo a2enconf cloudflare-remoteip security
sudo a2ensite example.com
sudo apache2ctl configtest && sudo systemctl reload apache2

If this breaks something: a 526 error page from Cloudflare means Cloudflare doesn't accept the origin certificate, for example because it doesn't cover that hostname. A 525 or a handshake failure usually means AOP is on in Apache but off in Cloudflare, or the CA file path is wrong.

Step 11: Deploy CrowdSec and make it block

CrowdSec reads your logs, spots attack patterns like password guessing or vulnerability scans, and bans the source. Like Fail2Ban, it works from logs. The difference is the shared part: your server reports what it sees, and in return you get a community blocklist of IPs that attacked other CrowdSec users.

How CrowdSec turns log lines into blocked requestsLog filesauth.log (SSH)Apache access logModSecurity logSecurity EngineParsers read each line,scenarios count badbehaviour per IPLocal APIStores decisions,for example: banone IP for 4 hoursCrowdSec Central APIShares your signals,sends back thecommunity blocklistsignalsblocklistnftables bouncerDrops packets frombanned IPsApache moduleAnswers 403 to bannedIPs and bad requests
CrowdSec detects in one place and blocks in another: the engine decides, the bouncers enforce

CrowdSec itself blocks nothing. It only makes decisions. A separate program called a bouncer (CrowdSec now calls them remediation components) enforces them. Install the engine from CrowdSec's own repository, as the official install page shows. It uses a setup script, so download it and read it before you run it:

curl -s https://install.crowdsec.net -o crowdsec-repo.sh
less crowdsec-repo.sh
sudo sh crowdsec-repo.sh
sudo apt install -y crowdsec

The installer looks at your logs and adds matching collections, which are bundles of parsers and attack scenarios. Check what it found and add the ones for this stack:

sudo cscli collections list
sudo cscli collections install crowdsecurity/apache2 crowdsecurity/wordpress
sudo systemctl reload crowdsec

The apache2 collection reads /var/log/apache2/*.log by default. Because the vhost above logs to /var/www/example.com/logs/, tell CrowdSec where to look in /etc/crowdsec/acquis.d/wordpress.yaml:

filenames:
  - /var/www/example.com/logs/access.log
  - /var/www/example.com/logs/error.log
labels:
  type: apache2

Before any bouncer goes live, add your own IP to an allowlist. A burst of 404s while you test a plugin should never lock you out. Create /etc/crowdsec/parsers/s02-enrich/my-allowlist.yaml:

name: me/my-allowlist
description: "Never ban my own IP"
whitelist:
  reason: "admin IP"
  ip:
    - "203.0.113.10"

Now the first bouncer, for nftables:

sudo apt install -y crowdsec-firewall-bouncer-nftables
sudo systemctl restart crowdsec
sudo cscli bouncers list

It creates its own nftables table, so it doesn't touch the rules from step 5. Because /etc/nftables.conf starts with flush ruleset, restart the bouncer whenever you reload nftables, or its table is gone until the next restart.

Behind Cloudflare, web visitors reach your server from Cloudflare addresses, so the firewall bouncer only stops direct connections, such as SSH attempts and scanners hitting your IP. For web attackers you need a bouncer that sees the real IP from step 10. You have two options:

Apache module: ON - it runs inside Apache, sees the real visitor IP through mod_remoteip, and answers 403 to banned IPs. It also connects to CrowdSec's AppSec component, a WAF (web application firewall, a filter for malicious requests) that checks each request against rules for known exploits. The appsec-wordpress collection adds virtual patches for often-exploited WordPress vulnerabilities.

Cloudflare bouncer: DEPENDS - it pushes bans to Cloudflare's edge, so banned IPs never reach your server. It runs as a Cloudflare Worker, and CrowdSec recommends the paid Workers plan because of the blocklist size. Worth it on a busy site, overkill on a new one.

For the Apache route, follow CrowdSec's Apache AppSec quickstart. In short:

sudo apt install -y crowdsec-apache2-bouncer
sudo cscli collections install crowdsecurity/appsec-virtual-patching \
  crowdsecurity/appsec-generic-rules crowdsecurity/appsec-wordpress

sudo tee /etc/crowdsec/acquis.d/appsec.yaml >/dev/null <<'EOF'
appsec_configs:
  - crowdsecurity/appsec-default
labels:
  type: appsec
listen_addr: 127.0.0.1:7422
source: appsec
EOF

sudo systemctl restart crowdsec
sudo apache2ctl configtest && sudo systemctl reload apache2

Keep listen_addr on 127.0.0.1. The AppSec component should only ever talk to Apache on the same machine. Test it from your own computer with a request for a file that should never be public:

curl -I https://example.com/.env

CrowdSec's docs say a working setup answers 403 Forbidden here. If you get a 404, the request reached WordPress uninspected: check that the Apache module is enabled and that its AppSec address in /etc/crowdsec/bouncers/ points to 127.0.0.1:7422.

On my own server, the web layer is ModSecurity with the OWASP Core Rule Set, and CrowdSec feeds the nftables bouncer and reads the ModSecurity log. That works, but ModSecurity with WordPress means a long list of rule exclusions for the block editor, page builders and SEO plugins. The CRS WordPress exclusions plugin covers the core cases; the rest you find one false positive at a time. For a new server I would start with CrowdSec AppSec and add ModSecurity only if you need its depth.

The commands you will use most:

sudo cscli metrics                 # what CrowdSec reads and parses
sudo cscli alerts list --since 24h # what it detected
sudo cscli decisions list          # who is banned right now
sudo cscli decisions add --ip 198.51.100.7 --duration 5m --reason "test"
sudo cscli decisions delete --ip 198.51.100.7

If cscli metrics shows lines read but none parsed for your Apache logs, the log format and the parser don't match. That is the first thing I check after any log format change.

Step 12: Back up off the server and audit what you built

Hetzner's daily backups from step 2 restore the whole server in a few clicks. They live in the same Hetzner account, though, so a stolen account password or a billing problem can take the server and its backups together.

I add a second copy outside the server with BorgBackup to a Hetzner Storage Box. Borg encrypts and deduplicates on the server before upload, so the Storage Box only ever holds encrypted chunks. My backup job runs every night at 01:00. Include the webroot, the config files under /etc and a fresh database dump. A backup you have never restored is a guess, so test a restore of one file now and then:

borg extract --dry-run --list ssh://uXXXXX@uXXXXX.your-storagebox.de:23/./backups/wp \
  ::ARCHIVE-NAME var/www/example.com/public_html/wp-config.php

Keep the Borg passphrase in a file only root can read, and in your password manager. Without it, the backup is useless to you too.

Then audit the result with Lynis, a free tool that scans the server and lists what it would still harden:

sudo apt install -y lynis
sudo lynis audit system

Lynis gives a hardening score and a list of suggestions. Don't chase 100: some suggestions, like a separate partition for /tmp, cost more than they protect on a small cloud server. Read the warnings first, then the suggestions that touch SSH, PHP or the firewall.

My server also runs maldet, rkhunter and AIDE for malware, rootkit and file integrity checks. AIDE in particular flags every changed file, so each legitimate update shows up as an alert. Add them once you have the time to read their reports, or they turn into mail you ignore.

Check it worked

Run these checks after the last step, and again after any big change:

  • sudo sshd -T | grep -E 'permitrootlogin|passwordauthentication|port' shows no, no and your new port
  • sudo nft list ruleset shows your filter table and a separate crowdsec table
  • curl -I https://YOUR_SERVER_IP -k from your computer times out, because both firewalls accept web traffic from Cloudflare only
  • curl -I https://example.com/.env returns 403
  • sudo cscli metrics shows parsed lines for your Apache logs
  • ss -tlnp lists only Apache on 80 and 443, SSH on your port and CrowdSec on 127.0.0.1

That last check is the one I trust most. If a port shows up there and you don't know why, find out before you go to bed.

How to undo a step

Almost every step here adds one file, so undoing it means removing that file and reloading the service:

  • SSH: delete /etc/ssh/sshd_config.d/10-hardening.conf, then daemon-reload and restart ssh.socket
  • nftables: copy /root/nftables.conf.bak back and restart nftables
  • PHP pool: rename www.conf.disabled back, run a2enconf php8.5-fpm and restart PHP-FPM and Apache
  • CrowdSec: sudo apt remove crowdsec-firewall-bouncer-nftables removes its table; sudo cscli decisions delete --all clears every ban

If you lock yourself out completely, the Hetzner web console still works, and the daily backup from step 2 is your last resort.

Frequently asked questions

Do I need ModSecurity if I use CrowdSec AppSec?

No. Both are web application firewalls. CrowdSec AppSec is easier to start with on WordPress because it ships virtual patches for known WordPress vulnerabilities. ModSecurity with the OWASP Core Rule Set is broader but needs many WordPress rule exclusions. My own server pairs ModSecurity with CrowdSec's log-based detection. On a new server I would start with AppSec alone.

Why nftables and not UFW?

UFW is fine and easier to read. I use nftables directly because CrowdSec's bouncer and my own blocklists both manage nftables sets, and one tool is easier to debug. If you already know UFW, keep it and install the matching CrowdSec bouncer.

Are Hetzner's backups enough?

They are good for a fast full restore, with one backup per day and seven slots. They live in the same Hetzner account as the server, so I add an encrypted off-server copy with BorgBackup as well.

Can I follow this guide on Ubuntu 24.04?

Yes. The only differences are the PHP version (8.3 instead of 8.5) and the paths that contain it, such as /etc/php/8.3/fpm/. SSH socket activation, nftables and CrowdSec work the same way.

The server is only half of the setup. The laptop you SSH from needs the same care, and my remote work security rules cover that side.

Cheers,
Mefat

Comments 0

No comments yet. Questions, corrections and your own experience are all welcome.

Help us make this site better? A few cookies show us which guides are useful. Nothing else. Privacy Policy