Another rebuild for my own website

Looking at my copyright notice, I realized my website is 20 years old. Such an occasion deserves celebrating with some fresh new features.

It’s a special occasion, obviously, but the main reasons I want to do some upgrades to the website are not necessarily related to that.

First and most important: for about a year I get notifications about failed login attempts to the admin area of the site. I have a pretty secure password, together with some plugins which aim to help with security. But the better safe than sorry approach has always been something I am keen on.

The second reason is that in this age of AI, everything is less safe. The intended purpose of these changes is to reduce the attack surface on the website.

Hosting

For hosting, an interesting alternative presented itself recently as CloudPanel. It’s a free solution, minimal, clean and one which seems to cover most of my needs. However, one thing that it’s missing is native support for Apache, which is not necessarily a dealbreaker.

However, it’s not yet time to make this change. The next step to updating the server will be automating certain actions using n8n and agents. To check the actions done through these flows and interface will prove mighty useful, and that’s why we will keep a solution like Virtualmin still. However, in the future we will also remove this and use scripts to manage the hosted websites.

So we will continue to use Virtualmin. We will create a new server and install a new instance, but with some twists this time.

We will continue to have the latest debian as a base, but start with using the minimal variant of Virtualmin. This varian is a skimmed approach which does not contain Postfix, Dovecot, SpamAssassin, ClamAV, Bind, FTP and most importantly Jailkit.

sudo sh -c "$(curl -fsSL https://download.virtualmin.com/virtualmin-install)" -- --bundle LAMP --type miniCode language: JavaScript (javascript)

Out of the excluded features, the only one we want is the last one: Jailkit. We will add it manually, but we also must remember to enable it in the server templates:

sudo apt update
sudo apt install jailkit webmin-jailkit

To enable Jailkit for all new virtual hosts:

  1. Open Virtualmin > System Settings > Server Templates;
  2. Select Default Settings;
  3. Open the Administrative user section;
  4. Find Chroot jail new domain Unix users?
  5. Set it to Yes;
  6. Save the template.

With the minimal version, some security hardening will also be missing:

sudo apt install fail2ban unattended-upgrades

Read more:

Shortcut

One easy way to go about the hosting is to use some of the scripts I created a while back and updated recently with a lot of help from Gemini.

One first thing we will to is to setup the nice zsh helper you have seen a lot in my articles:

curl -fsSL https://raw.githubusercontent.com/cristidraghici/debian-server-bash-scripts/master/install_antigen.sh | bashCode language: JavaScript (javascript)

One fun thing is that with the new server I was “lucky” enough to get an IP which was being flooded by configuration set for a previous server hosted there. Whoever owned the recycled DigitalOcean IP before you ran a real-time ad-bidding server registered with Xandr and destroyed their droplet without removing the IP from Xandr’s bidder config – so Xandr kept sending thousands of bid requests per second to port 80.

This lead to the following two changes:

  1. adding more hardening directly to the server;
  2. adding a firewall from DigitalOcean, which automatically limitted the traffic which was overloading the server.

    The scripts can be found here and you can either execute them in order from top to bottom or select what you are interested in:

    Implementation

    For now, we will keep WordPress as the engine of the website. It’s a mature project I am familiar with and I still want to complete some old ideas about plugins which I haven’t gotten around to yet.

    One shot prompt

    This prompt does not guarantee the same results, but it’s a good starting point if you want these same modifications on a project.

    # Role & Goal
    
    You are migrating an existing standard WordPress site in this workspace (containing `wp-config.php`, `wp-content/`, and a SQL dump) **in place** into a modern, local-authoring **Roots Bedrock + Docker Compose + Static Site Export & SSH/rsync Deployment** platform.
    
    Production serves **static HTML/CSS/JS/media** on Apache via SSH/`rsync`; WordPress runs strictly locally in Docker for authoring, dependency management, backups, and static exports.
    
    ---
    
    ## Configuration (Fill in or leave `auto` where indicated)
    
    ```yaml
    PROJECT_SLUG: "<project-slug>"                  # e.g., example-site (used for container names & composer name)
    COMPOSER_VENDOR: "<vendor>"                     # e.g., myorg (composer name: <vendor>/<project-slug>)
    PROD_URL: "https://<example.com>"               # Canonical production URL (no trailing slash)
    SQL_DUMP_PATH: "auto"                           # Relative path to .sql or .sql.gz dump, or auto-detect
    DB_PREFIX: "auto"                               # Auto-detect from wp-config.php or SQL dump
    ACTIVE_THEME_SLUG: "auto"                       # Auto-detect active theme / child theme from DB dump
    WEB_PORT: 8080                                  # Local HTTP port for Apache
    DB_PORT: 3307                                   # Local host port for MySQL
    STATIC_PATH_MODE: "relative"                    # 'relative' (root-relative) or 'absolute'
    SEARCH_REWRITE: "duckduckgo"                    # 'duckduckgo' (site:<domain>) or 'none'
    STATIC_SSH_PATH: "/var/www/<example.com>/public_html"
    ```
    
    ---
    
    ## Non-Negotiable Safety Rules
    
    1. **Preserve originals first**: Before moving or deleting anything, archive the original `wp-config.php`, `wp-content/`, and SQL dump into `.backups/pre-migration-original.tar.gz` (and keep `.backups/` gitignored). Never destroy the original SQL dump or uploads.
    2. **Never commit or expose secrets**: `.env`, `.env.local`, `.data/`, `.backups/`, `dist/`, `dist_static/`, SSH keys, and SQL dumps must be in `.gitignore`. Generate fresh random WordPress salts for local `.env` (never reuse production salts in `.env.example`).
    3. **Never auto-commit**: Leave all git changes staged or unstaged for human review unless explicitly instructed otherwise.
    4. **Zero third-party Python dependencies**: All scripts in `scripts/` and tests in `tests/` must use **Python 3.9+ standard library only**.
    5. **Conservative destructive boundaries**: Output directories must be dedicated, non-hidden top-level project folders outside protected source/data folders (`web`, `vendor`, `config`, `docker`, `scripts`, `tests`, `patches`).
    
    ---
    
    ## Phase 1: Inspect Existing Site & Produce Migration Audit
    
    Inspect the workspace before making structural changes:
    - Read `wp-config.php` for `$table_prefix`, custom constants, and `WP_CONTENT_DIR` overrides.
    - Locate the SQL dump (`.sql` or `.sql.gz`) and identify: site URL(s), active theme/parent theme, active plugins, and permalink structure.
    - Inventory `wp-content/plugins/` and `wp-content/themes/`:
      - **Public WordPress.org plugins & themes**: Resolve to `wpackagist-plugin/*` / `wpackagist-theme/*` in `composer.json` pinned to compatible versions.
      - **Custom, premium, or child themes/plugins**: Keep tracked in git under `web/app/themes/<slug>/` or `web/app/plugins/<slug>/` with explicit `.gitignore` un-ignore rules (`!web/app/...`), and exclude third-party vendor/Composer-managed themes/plugins from Pint formatting.
      - **Docker-disabled plugins**: Identify login/security/caching plugins that interfere with local Docker authoring (e.g., reCAPTCHA, Limit Login Attempts, Sucuri, page-cache plugins, Duplicator) and list them in `DOCKER_DISABLED_PLUGINS` instead of deleting them.
    - **Dynamic features audit**: Inspect for contact form plugins, native WP comments, AJAX endpoints, search forms, or e-commerce/membership plugins. Do **not** silently break them — document every detected dynamic feature and recommended static alternative (e.g., Web3Forms/Formspree, Disqus/Giscus) in your final summary.
    
    ---
    
    ## Phase 2: Target Directory Layout & Core Platform
    
    Restructure the repository into this exact layout:
    
    ```text
    .
    ├── .env.example
    ├── .gitignore
    ├── .github/workflows/verify.yml
    ├── Makefile
    ├── README.md
    ├── composer.json
    ├── docker-compose.yml
    ├── pint.json
    ├── wp-cli.yml
    ├── config/
    │   ├── application.php
    │   ├── static.htaccess
    │   └── environments/
    │       ├── development.php
    │       └── staging.php
    ├── docker/
    │   ├── apache/ (Dockerfile, apache.conf, php.ini)
    │   ├── cli/    (Dockerfile, init-wordpress.sh)
    │   └── mysql/  (my.cnf)
    ├── patches/                        # Composer patches if PHP 8.4 compatibility fixes are needed
    ├── scripts/
    │   ├── backups.py
    │   ├── cleanup.py
    │   ├── reliability.py
    │   ├── static_build.py
    │   ├── static_deploy.py
    │   ├── static_transform.py
    │   ├── static_validate.py
    │   ├── update.php
    │   ├── urls-local.sh
    │   └── verify.py
    ├── tests/
    │   ├── test_reliability.py
    │   └── test_update.py
    └── web/
        ├── index.php
        ├── wp-config.php
        ├── wp/                         # Gitignored; installed by Composer (roots/wordpress)
        └── app/
            ├── mu-plugins/
            │   └── cli-only-updates.php
            ├── plugins/                # Gitignored except .gitkeep & custom/premium plugins
            ├── themes/                 # Composer themes gitignored; custom/child themes tracked
            └── uploads/                # Gitignored; bind-mounted from .data/apache/uploads
    ```
    
    Move the existing uploads into `.data/apache/uploads/` and copy/compress the original SQL dump to `.data/db_init/dump.sql.gz`. Remove legacy root WordPress core files (`wp-admin/`, `wp-includes/`, root `wp-*.php`, old `wp-content/`) once migrated and backed up.
    
    ---
    
    ## Phase 3: Bedrock, Composer & CLI-Only Updates
    
    1. **`composer.json`**:
       - Require PHP `>=8.1`, `composer/installers`, `vlucas/phpdotenv`, `oscarotero/env`, `roots/bedrock-autoloader`, `roots/bedrock-disallow-indexing`, `roots/wordpress`, `roots/wp-config`, `wp-cli/wp-cli-bundle`, `cweagans/composer-patches` (with `"composer-exit-on-patch-failure": true`), and `require-dev`: `laravel/pint`.
       - Configure `wpackagist` repository (`only: ["wpackagist-plugin/*", "wpackagist-theme/*"]`), `wordpress-install-dir: "web/wp"`, and `installer-paths` mapping mu-plugins, plugins, and themes into `web/app/*`.
       - Add Composer scripts: `lint` (`pint --test`), `lint:fix` (`pint`), `backup`, `restore`, `static:build`, `static:deploy`, `urls:local`.
    2. **Bedrock configuration (`config/application.php`, `config/environments/*.php`, `web/wp-config.php`, `web/index.php`, `wp-cli.yml`)**:
       - Load `.env` and optional `.env.local` override via `vlucas/phpdotenv`.
       - Under `WP_ENV === 'development'` for web requests (not `PHP_SAPI === 'cli'`), dynamically derive `WP_HOME` and `WP_SITEURL` from the request host (`HTTP_X_FORWARDED_HOST` / `HTTP_HOST`) to avoid redirect loops; preserve `.env` values for CLI/staging/production.
       - Set `CONTENT_DIR = '/app'`, `AUTOMATIC_UPDATER_DISABLED = true`, `DISALLOW_FILE_EDIT = true`, `DISALLOW_FILE_MODS = !(defined('WP_CLI') && WP_CLI)`, `CONCATENATE_SCRIPTS = false`.
       - Development overrides: `SAVEQUERIES`, `WP_DEBUG`, `WP_DEBUG_DISPLAY`, `WP_DEBUG_LOG` (`.data/debug.log`), `DISALLOW_INDEXING = true`.
    3. **CLI-only Updates (`web/app/mu-plugins/cli-only-updates.php` & `scripts/update.php`)**:
       - Block all web/automatic core, plugin, and theme upgrades (`upgrader_pre_download` returning `WP_Error`) while keeping update availability checks visible in WP Admin with clear instructions to run `make update`.
       - `scripts/update.php` (run after `composer update` in `make update`): inspect outdated direct dependencies outside `composer.json` constraints, prompt interactively (`y` to approve, Enter/EOF to skip), resolve approved changes together, then sync installed WordPress/WPackagist version floors into `composer.json` and `composer.lock`.
    4. **PHP 8.4 compatibility patches**: If any migrated WPackagist plugin triggers PHP 8.4 fatal/deprecation errors during local boot or crawl, create clean unified diffs in `patches/` wired through `cweagans/composer-patches` rather than editing vendor files directly.
    
    ---
    
    ## Phase 4: Docker Compose & Safe Auto-Initialization
    
    1. **`docker-compose.yml`** with three services on a shared bridge network:
       - `apache`: Built from `php:8.4-apache` with `gd` (freetype, jpeg, webp), `mysqli`, `pdo_mysql`, `zip`, `exif`, `intl`, `opcache`, `default-mysql-client`, `patch`, and Apache mods `rewrite headers expires deflate`. `DocumentRoot /var/www/html/web`, rewrite `^wp-content/(.*)$ /app/$1 [L]`, security headers, gzip, expires, and deny rules for `.env`, `composer.*`, `.git`, `wp-config.php`, `*.log`. Bind-mount `.` to `/var/www/html` and `./.data/apache/uploads` to `/var/www/html/web/app/uploads`. Include HTTP healthcheck.
       - `mysql`: `mysql:8.4` with `--mysql-native-password=ON`, persistent `./.data/mysql`, custom `docker/mysql/my.cnf`, and authenticated `mysqladmin ping` healthcheck.
       - `cli`: Built from `php:8.4-cli-alpine` with `mysql-client`, `mariadb-connector-c`, `gd` (with webp), `exif`, `mysqli`, `pdo_mysql`, `bash`, `gzip`, `python3`, Composer, WP-CLI fallback (preferring `vendor/bin/wp`), and `docker/cli/init-wordpress.sh` as entrypoint.
    2. **Safe initialization (`docker/cli/init-wordpress.sh`)**:
       - Bounded authenticated MySQL readiness loop (`WP_DB_WAIT_ATTEMPTS=20`, `WP_DB_WAIT_INTERVAL=3`) printing the last DB error on timeout.
       - Guard with `.data/.wordpress-initializing` marker: if present on boot, exit non-zero and refuse to overwrite until manually inspected/cleared.
       - If `wp core is-installed` succeeds, leave the database intact.
       - If not installed, check `SHOW TABLES`: if any tables exist, **refuse to overwrite** and exit non-zero.
       - Otherwise create marker, import `.data/db_init/dump.sql.gz` (or run `wp core install` if no dump exists), run `scripts/urls-local.sh` (rewriting `PROD_URL` and `/wp-content/` references cleanly to local `WP_HOME` and `/app/`, supporting `--dry-run`), activate the migrated theme, set/flush permalinks, verify `wp core is-installed`, remove marker, deactivate `DOCKER_DISABLED_PLUGINS`, and stay alive (`exec tail -f /dev/null`).
    
    ---
    
    ## Phase 5: Static Site Export, Validation & Apache SSH/rsync Deployment
    
    Build a dependency-free Python 3.9+ pipeline in `scripts/`:
    
    1. **`scripts/reliability.py`**:
       - `.env` / `.env.local` loader (with `os.environ` precedence).
       - Strict `output_path()` guard: only dedicated, non-hidden top-level project directories with no symlinks, traversal, tracked git files, or reserved directory names.
       - Strict `remote_path()` guard: absolute path with at least 3 nested segments (e.g., `/var/www/site/public_html`), safe character set only, no hidden or reserved segments.
    2. **`scripts/static_build.py`**:
       - Acquire exclusive lock directory `.<output>.build-lock`.
       - Always crawl into a fresh staging directory; replace `<output>/` only after all transforms and validations succeed. On failure, retain `.<output>-build-*/` with `failure.txt` and `crawl.log`.
       - Fetch `robots.txt` via same-origin-enforced HTTP client; recursively fetch all advertised sitemaps and child sitemaps to seed the crawl.
       - Crawl local WordPress using GNU `wget` (`--mirror`/recursive, page requisites, respecting local origin). Copy non-PHP static assets from the active/parent theme when needed and fetch any remaining referenced `srcset`/`imagesrcset` and CSS `url(...)` assets; provide an actionable `make media-regenerate` hint on 404 media thumbnails.
       - Reconcile crawl 404s only for verified redirects or known `/wp-content/` -> `/app/` replacements present in the stage; fail the build on any other crawl/network error.
       - Copy `config/static.htaccess` into the stage as `.htaccess`.
       - Run `static_transform.py`, then `static_validate.py`, write `.static-build.json` (build settings + SHA-256 checksums of all files), and atomically swap into `<output>/`. Support `--skip-crawl` and `--clean`.
    3. **`scripts/static_transform.py`**:
       - Support `STATIC_PATH_MODE`: `relative` (root-relative paths for internal links/assets) or `absolute`.
       - Strip `?ver=`/`?v=` query strings from static asset URLs while preserving absolute `PROD_URL` in SEO/metadata (`canonical`, OpenGraph, JSON-LD, share links, sitemaps, `robots.txt`).
       - Strip unsupported WordPress discovery `<link>` tags (`xmlrpc`, `wp-json`, `oembed`, `rsd`, `wlwmanifest`, pingback).
       - If `SEARCH_REWRITE=duckduckgo`, rewrite WordPress search forms to query DuckDuckGo scoped to `site:<prod-domain>`.
       - Never corrupt ordinary article prose or code examples.
    4. **`scripts/static_validate.py`**:
       - Verify homepage exists, canonical URLs, internal links, required assets (`href`/`src`/`srcset`/`imagesrcset`/CSS `url()`), recursive sitemaps, JSON-LD JSON syntax, absence of PHP warnings/fatal errors, and absence of localhost/development URLs in functional markup/runtime data (allowing localhost mentions inside ordinary article text/code).
       - Provide `verify_manifest(source, prod_url)` checking `.static-build.json` presence, matching `PROD_URL`, complete file list, and exact SHA-256 checksums.
    5. **`scripts/static_deploy.py`**:
       - Validate SSH host/user/port/key and `remote_path()`.
       - Acquire `.<output>.build-lock`, call `verify_manifest()` to reject modified/stale/mismatched artifacts, then deploy via `rsync -avz --itemize-changes --delay-updates --partial-dir=.rsync-partial` excluding `.DS_Store`, `.git`, `.rsync-partial`, and `.static-build.json`.
       - Support `--dry-run` and `--no-delete` (defaulting to `--delete --delete-after` when `STATIC_DELETE_REMOTE=true`).
    6. **`config/static.htaccess`**:
       - `Options -Indexes`, `ErrorDocument 404 /404.html`, deny `.static-build.json` and `.(env|sql|log|bak)`, block `.rsync-partial`, rewrite `^wp-content/(.*)$ /app/$1 [L]`, security headers (`X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`, HSTS on HTTPS), `mod_deflate`, and `mod_expires` caching.
    7. **`scripts/cleanup.py`**:
       - Safely delete only `dist/`, `dist_static/`, and their diagnostic build folders (never `.data/`, `.backups/`, `.env`, or `vendor/`), supporting `--dry-run` and confirmation.
    
    ---
    
    ## Phase 6: Verified Backups, Makefile, Tests & CI
    
    1. **`scripts/backups.py`**:
       - Lock via `.backups/.operation-lock`.
       - `create`: export DB (`mysqldump`/WP-CLI) + `uploads/` + git metadata into a unique temp dir, generate SHA-256 manifest, package `.tar.gz`, read back and verify the archive before publishing to `.backups/`.
       - `restore <file>`: validate a private copy first (single root dir, non-empty `database.sql`, `uploads/` dir, reject path traversal, symlinks, special files, duplicates; verify checksums if present), create a verified pre-restore recovery backup first, import SQL, merge uploads retaining newer files, normalize URLs, and preserve `.backups/.backup-*` / `.backups/.restore-*` on failure with recovery instructions.
    2. **Self-documenting `Makefile`**:
       - Categorized `help` default goal + targets: `up`, `down`, `restart`, `logs`, `ps`, `build`, `shell`, `wp` (supporting both `ARGS="..."` and `make wp -- ...`), `media-regenerate`, `backup`, `restore`, `install`, `update`, `lint`, `lint-fix`, `verify`, `static-build`, `serve-dist`, `static-deploy`, `clean`, and `fresh` (interactive confirmation to reset `.data/mysql/*` and init marker).
    3. **Verification suite (`scripts/verify.py`, `tests/`, `.github/workflows/verify.yml`)**:
       - `scripts/verify.py` (read-only against tracked source): check prerequisites (`php`, `composer`, `shellcheck`, `bash`), Python AST syntax check, `composer validate --no-check-publish`, `composer lint` (Pint `per` preset), `php -l` on all tracked `.php` files, `shellcheck` on all `.sh` scripts, and `python3 -B -m unittest discover -s tests -b`.
       - `tests/test_reliability.py` & `tests/test_update.py`: comprehensive unit tests using temporary directories and mocked DB/SSH commands covering path guards, lockfiles, backup/restore corruption & traversal rejection, static transform/validation/manifest tampering detection, init-script non-overwrite guarantees, and `update.php` version syncing.
       - `.github/workflows/verify.yml`: run `composer install` and `make verify` on push and PR (PHP 8.4, Python 3.12, ShellCheck).
    4. **`README.md`**: Document architecture, prerequisites, getting started, Makefile commands, backup/restore safety, static build/deploy workflow, and code quality.
    
    ---
    
    ## Phase 7: Mandatory End-to-End Verification Gates
    
    Before finishing, you **must** execute and confirm all of the following succeed without errors:
    
    1. `make install` — Composer installs cleanly (including any patches).
    2. `make up` — Containers build and start cleanly; inspect `docker compose logs cli` to confirm the DB dump imported, URLs normalized, active theme activated, and `http://localhost:<WEB_PORT>` responds with HTTP 200 and no PHP errors.
    3. `make backup` — Creates and verifies a backup archive in `.backups/`.
    4. `make static-build` — Crawls local WordPress, transforms, validates, and produces `dist/` with a valid `.static-build.json` manifest (if media thumbnail 404s occur, run `make media-regenerate` and re-run `make static-build`).
    5. `make verify` — Passes Composer validation, Pint lint, `php -l`, ShellCheck, and all Python unit tests.
    
    In your final report, summarize:
    - Migrated plugins/themes classification (WPackagist vs. tracked custom/premium vs. `DOCKER_DISABLED_PLUGINS`) and any PHP 8.4 patches added.
    - Dynamic features audit (forms, comments, search, AJAX) and recommended next steps.
    - Verification results for all 5 gates and location of `.backups/pre-migration-original.tar.gz`.
    Code language: PHP (php)

    Makefile

    I will start the description of the implementation with one of the last completed things: introducing a Makefile, to help with managing the commands available inside the website. These commands give a good summary of the changes and the direction of the project, so going though them first might help with an overall picture.

    draghici.net - Makefile commands
    
    Docker Lifecycle (Website Runtime):
      build              Rebuild Docker images
      down               Stop and remove Docker containers and networks
      logs               View container logs (follow mode, optionally pass service via ARGS)
      ps                 List running container status and ports
      restart            Restart Docker containers
      shell              Open an interactive bash shell in the CLI container
      up                 Start Docker containers in detached mode
    
    WordPress & Backups (via Docker):
      backup             Create database and uploads backup inside Docker (.backups/)
      media-regenerate   Regenerate missing WordPress media thumbnails inside Docker (optional: ARGS="--skip-delete")
      restore            Restore database and uploads inside Docker (usage: make restore FILE=<path>)
      wp                 Execute WP-CLI inside Docker (e.g. make wp ARGS="plugin list" or make wp -- plugin list)
    
    Composer & Code Quality (Host Native):
      install            Install PHP dependencies on the host via composer
      lint-fix           Run Pint and automatically fix code style issues
      lint               Run Pint code style linter
      update             Update dependencies, review out-of-range releases and sync WordPress versions
      verify             Check PHP, shell scripts, and reliability tests without changing source
    
    Static Site Export & Deploy (Host Native):
      serve-dist         Serve static site from dist/ locally with Python (optional: PORT=3000)
      static-build       Crawl local WordPress and generate static site in dist/ (optional: ARGS="--clean")
      static-deploy      Deploy static site from dist/ to production server via rsync/ssh
    
    Maintenance & Cleanup:
      clean              Remove only dist/ and dist_static/ (preserves data and dependencies)
      fresh              Reset Docker environment and database volume (re-imports SQL dump on start)Code language: PHP (php)

    Bedrock

    One important change we will introduce is that we will start using Bedrock and composer to manage the website, instead of plain WordPress. This will help with keeping a versioned variant of the project. File structure:

    .
    ├── .github/                  # CI/CD workflows and automated checks
    ├── config/                   # Centralized application & server configuration
    │   └── environments/         # Environment-specific overrides (dev, staging, etc.)
    ├── dist/                     # Generated static site output (HTML, assets, feeds)
    ├── docker/                   # Local container definitions & service configs
    │   ├── apache/               # Web server & PHP runtime container
    │   ├── cli/                  # CMS CLI tooling & initialization container
    │   └── mysql/                # Local database configuration
    ├── honeypot/                 # Isolated, lightweight security decoy layer
    ├── patches/                  # Version-locked patches applied to dependencies
    ├── scripts/                  # Build, validation, deployment & maintenance tooling
    │   ├── (static pipeline)     # Crawling/building, transforming, validating, deploying
    │   ├── (maintenance)         # Backups, cleanup, asset updates, local helpers
    │   └── (verification)        # Reliability and post-build sanity checks
    ├── tests/                    # Automated tests for build & maintenance scripts
    ├── web/                      # Web root (Bedrock-style WordPress layout)
    │   ├── app/                  # Site-specific content & extensions
    │   │   ├── mu-plugins/       # Must-use plugins loaded automatically
    │   │   ├── plugins/          # Composer-managed plugins
    │   │   ├── themes/           # Site themes and presentation layer
    │   │   └── uploads/          # Media library assets
    │   └── wp/                   # Core CMS files (managed via Composer)
    ├── composer.json             # PHP & CMS dependency manifest (+ lockfile)
    ├── docker-compose.yml        # Local multi-container orchestration
    ├── Makefile                  # Unified commands for dev, build, test, and deploy
    ├── pint.json                 # Code style and formatting configuration
    └── wp-cli.yml                # Local CMS CLI configurationCode language: PHP (php)

    Static files

    The main security update we will do is that we will actually generate static files which will be hosted on the server, instead of the normal WordPress installation. This will dramatically reduce the attack surface on the website.

    We will convert the WordPress website by generating our own crawler. As most of the scripts in this project, the generator will be based on python. It will use wget to retrieve the files and then multiple processes for activities like replacing the existing paths with static ones or ensuring we have all the media generated. The output will be saved in the ./dist folder and we will have a command to serve these files locally, should we want to test the generated content.

    One thing to keep in mind and pay attention to is that we will have to convert all the interactive parts to static. On my site the comments were already disabled, but the search was still something which needed attention. The simple fix was to use a search engine to search the files, a better fix would be to implement some sort of text search.

    Honeypot

    As I mentioned, there have been many unauthorized attempts to access the admin area of my website. Most of these have been logged and the IPs they originated from are now in a list which is not allowed to login on any of my sites.

    Since they already know to try to login to this site, it would be a pity not to log the attempts even if the site is now static. So, this is why I have introduced a “honeypot” – it’s basically a login form simulator which only logs the login attempts. It’s a bit greedy of me to do this, since adding interactive forms still opens the website to some risk, but I’d say that it’s worth it.

    Docker

    We will have multiple ways to run the website: static and served by a HTTP server, dynamic on a PHP based hosting server or via docker. The current preferred way will be via docker and locally.

    The aim for the docker implementation will be to run the website locally, which will make for a comfortable approach. Among other things, this will involve the fact that we don’t need certain security plugins, and this we need to implement a way to disable them.

    We will use a pretty basic docker implementation for it, which can be guessed from the content of the docker-compose.yml file:

    services:
      apache:
        build:
          context: .
          dockerfile: ./docker/apache/Dockerfile
        container_name: draghici-apache
        restart: unless-stopped
        ports:
          - "${WEB_PORT:-8080}:80"
        volumes:
          - .:/var/www/html:cached
          - ./.data/apache/uploads:/var/www/html/web/app/uploads:cached
          - ./.data/apache/logs:/var/log/apache2
          - ./docker/apache/php.ini:/usr/local/etc/php/conf.d/php-config.ini:cached
          - ./docker/apache/apache.conf:/etc/apache2/sites-available/000-default.conf:cached
        depends_on:
          mysql:
            condition: service_healthy
        networks:
          - app_network
        healthcheck:
          test: ["CMD", "curl", "-f", "http://localhost/"]
          interval: 30s
          timeout: 10s
          retries: 3
          start_period: 40s
    
      mysql:
        image: mysql:8.4
        container_name: draghici-mysql
        restart: unless-stopped
        environment:
          MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}
          MYSQL_DATABASE: ${DB_NAME}
          MYSQL_USER: ${DB_USER}
          MYSQL_PASSWORD: ${DB_PASSWORD}
        ports:
          - "${DB_PORT}:3306"
        volumes:
          - ./.data/mysql:/var/lib/mysql
          - ./docker/mysql/my.cnf:/etc/mysql/conf.d/my.cnf:ro
        networks:
          - app_network
        healthcheck:
          test:
            [
              "CMD-SHELL",
              'MYSQL_PWD="${DB_ROOT_PASSWORD}" mysqladmin ping -h localhost -u root',
            ]
          interval: 10s
          timeout: 5s
          retries: 5
        command: --mysql-native-password=ON
    
      cli:
        build:
          context: .
          dockerfile: ./docker/cli/Dockerfile
        container_name: draghici-cli
        volumes:
          - .:/var/www/html:cached
          - ./.data/apache/uploads:/var/www/html/web/app/uploads:cached
          - ./docker/cli/init-wordpress.sh:/usr/local/bin/init-wordpress.sh
        environment:
          DB_NAME: ${DB_NAME}
          DB_USER: ${DB_USER}
          DB_PASSWORD: ${DB_PASSWORD}
          DB_HOST: ${DB_HOST}
          WP_HOME: ${WP_HOME}
          WP_ADMIN_USER: ${WP_ADMIN_USER}
          WP_ADMIN_PASSWORD: ${WP_ADMIN_PASSWORD}
          WP_ADMIN_EMAIL: ${WP_ADMIN_EMAIL}
          WP_DB_WAIT_ATTEMPTS: ${WP_DB_WAIT_ATTEMPTS}
          WP_DB_WAIT_INTERVAL: ${WP_DB_WAIT_INTERVAL}
          DOCKER_DISABLED_PLUGINS: ${DOCKER_DISABLED_PLUGINS-login-recaptcha,limit-login-attempts-reloaded,sucuri-scanner}
        depends_on:
          mysql:
            condition: service_healthy
        networks:
          - app_network
    
    networks:
      app_network:
        driver: bridgeCode language: JavaScript (javascript)

    A slightly special part of the implementation is the cli container, which is somewhat of a service container to install tools and use as a “command center” for the implementation.

    The Dockerfile will install the necessary dependencies and wait for connections from users to run commands on it:

    FROM php:8.4-cli-alpine
    
    USER root
    
    # Install dependencies
    RUN apk update && \
        apk add --no-cache \
        mysql-client \
        mariadb-connector-c \
        libpng-dev \
        libjpeg-turbo-dev \
        freetype-dev \
        libwebp-dev \
        curl \
        git \
        bash \
        gzip \
        python3
    
    # Configure MySQL client to skip SSL
    RUN echo -e "[client]\nskip-ssl" > /etc/my.cnf
    
    # Install PHP extensions
    RUN docker-php-ext-configure gd \
          --with-freetype \
          --with-jpeg \
          --with-webp && \
        docker-php-ext-install -j$(nproc) gd exif mysqli pdo_mysql
    
    # Install WP-CLI fallback (vendored vendor/bin/wp is preferred at runtime)
    RUN curl -fsSL -o /usr/local/bin/wp https://github.com/wp-cli/wp-cli/releases/download/v2.12.0/wp-cli-2.12.0.phar && \
        chmod +x /usr/local/bin/wp
    
    # Install Composer
    COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
    
    # Copy init script
    COPY ./docker/cli/init-wordpress.sh /usr/local/bin/init-wordpress.sh
    RUN chmod +x /usr/local/bin/init-wordpress.sh
    
    WORKDIR /var/www/html
    
    ENTRYPOINT ["/usr/local/bin/init-wordpress.sh"]
    Code language: PHP (php)

    A rather special file is the init-wordpress.sh entrypoint, which configures the local instance: sets the database content, disables the plugins which are not needed, makes the container wait for commands:

    #!/usr/bin/env bash
    set -euo pipefail
    
    PROJECT_ROOT="${WP_PROJECT_ROOT}"
    cd "$PROJECT_ROOT"
    
    WP_PATH="$PROJECT_ROOT/web/wp"
    DUMP_FILE="$PROJECT_ROOT/.data/db_init/dump.sql.gz"
    MARKER="$PROJECT_ROOT/.data/.wordpress-initializing"
    ATTEMPTS="${WP_DB_WAIT_ATTEMPTS}"
    INTERVAL="${WP_DB_WAIT_INTERVAL}"
    [[ "$ATTEMPTS" =~ ^[1-9][0-9]*$ && "$INTERVAL" =~ ^[0-9]+$ ]] || {
        echo "Invalid database readiness retry settings." >&2; exit 1;
    }
    export MYSQL_PWD="${DB_PASSWORD:?DB_PASSWORD is required}"
    
    trap 'echo "WordPress initialization failed; inspect the error before restarting." >&2' ERR
    ready=false
    last_db_error=""
    for ((attempt=1; attempt<=ATTEMPTS; attempt++)); do
        if last_db_error=$(mysql -h "${DB_HOST:?}" -u "${DB_USER:?}" "${DB_NAME:?}" -e 'SELECT 1' 2>&1); then
            ready=true
            break
        fi
        if [ "$attempt" -lt "$ATTEMPTS" ]; then sleep "$INTERVAL"; fi
    done
    if [ "$ready" != true ]; then
        echo "Database readiness timed out after $ATTEMPTS attempts." >&2
        if [ -n "$last_db_error" ]; then
            echo "Last database error: $last_db_error" >&2
        fi
        exit 1
    fi
    
    WP_BIN="$PROJECT_ROOT/vendor/bin/wp"
    if [ ! -f "$WP_BIN" ]; then WP_BIN=wp; fi
    wp_run() { "$WP_BIN" "$@" --path="$WP_PATH" --allow-root; }
    
    disable_docker_plugins() {
        local plugins_raw="${DOCKER_DISABLED_PLUGINS}"
        local plugin
        local -a plugins=()
    
        [ -n "$plugins_raw" ] || return 0
        IFS=',' read -r -a plugins <<< "${plugins_raw// /,}"
        for plugin in ${plugins[@]+"${plugins[@]}"}; do
            [ -n "$plugin" ] || continue
            if wp_run plugin is-active "$plugin" >/dev/null 2>&1; then
                echo "Deactivating Docker-disabled plugin: $plugin"
                wp_run plugin deactivate "$plugin"
            fi
        done
    }
    
    if [ -e "$MARKER" ]; then
        echo "Previous initialization did not finish. Inspect/recover the database, then remove $MARKER to retry." >&2
        exit 1
    fi
    if wp_run core is-installed; then
        echo "WordPress is installed; leaving its database and configuration intact."
    else
        # A failed installation check does not establish that the database is empty.
        tables=$(mysql -N -B -h "${DB_HOST:?}" -u "${DB_USER:?}" "${DB_NAME:?}" -e 'SHOW TABLES')
        if [ -n "$tables" ]; then
            echo "Database contains tables but WordPress is not installed. Refusing to overwrite it." >&2
            exit 1
        fi
        mkdir -p "$PROJECT_ROOT/.data"
        touch "$MARKER"
        if [ -f "$DUMP_FILE" ]; then
            gzip -dc "$DUMP_FILE" | mysql -h "$DB_HOST" -u "$DB_USER" "$DB_NAME"
            bash "$PROJECT_ROOT/scripts/urls-local.sh"
            if wp_run plugin is-installed duplicator; then
                wp_run plugin deactivate duplicator
            fi
        else
            wp_run core install \
                --url="${WP_HOME:?WP_HOME is required}" \
                --title="draghici.net" \
                --admin_user="${WP_ADMIN_USER:?WP_ADMIN_USER is required}" \
                --admin_password="${WP_ADMIN_PASSWORD:?WP_ADMIN_PASSWORD is required}" \
                --admin_email="${WP_ADMIN_EMAIL:?WP_ADMIN_EMAIL is required}" --skip-email
        fi
        wp_run theme activate draghici-5
        wp_run rewrite structure '/%postname%/' --hard
        wp_run rewrite flush --hard
        wp_run core is-installed
        rm "$MARKER"
        echo "WordPress initialization completed successfully."
    fi
    
    disable_docker_plugins
    
    echo "Website URL: ${WP_HOME:?WP_HOME is required}"
    echo "Keeping WP-CLI container alive for manual commands..."
    exec tail -f /dev/nullCode language: PHP (php)