Using Caddy to give WordPress its own directory

A Caddy makeover of the WordPress support page Giving WordPress Its Own Directory

It’s possible to have your website served from the webroot, but have WordPress moved to a subdirectory so it doesn’t clutter the root directory. You might want to do this to enable other behaviour such as:

  1. Sideloading other assets without mixing them up with WordPress files.
  2. Serving separate website versions e.g. /2019, /2020, /latest.

The rest of this write-up assumes that the website is located at mydomain.com and WordPress files are relocated to subdir.

Moving a Root install to its own directory

You have two different methods to move WordPress from the webroot to a subdirectory:

  1. Without a change in the WordPress URL (mydomain.com)
  2. With a change in the WordPress URL (mydomain.com/subdir)

Method I (Without a URL change)

With this method, rewrites are required to redirect to the relocated WordPress files and to support WordPress Permalinks.

  1. After Installing WordPress in the root folder, move everything from the root folder into subdir.
  2. Update the site block in the Caddyfile and then reload Caddy.
    # Matcher and rewrite for WordPress files
    @subdir {
        not path /subdir/*
        not file
    }
    rewrite @subdir /subdir{uri}

    # Proxy requests to PHP-FPM
    php_fastcgi unix//run/php/php7.4-fpm.sock {
        index off
    }
    # Rewrite for WordPress permalinks
    try_files {path} {path}/index.php /subdir/index.php

:writing_hand: Depending on your PHP-FPM config, the php_fastcgi can also be php_fastcgi 127.0.0.1:9000.

  1. Log in to WordPress at mydomain.com/admin

Method II (With a URL change)

With this method, Caddy automatically handles the WordPress Permalink structure through the php_fastcgi directive. Changes to the Caddyfile are not required.

  1. Create subdir under the webroot.
  2. From the WordPress General Settings screen, set the WordPress address (URL) and then click Save Changes. Ignore the erros that appear.

  1. Move the WordPress files from the webroot to subdir.
  2. Copy (don’t move!) index.php back into the webroot.
  3. Edit the webroot index.php. Change the following line and save the file.
require __DIR__ . '/wp-blog-header.php';

…to include /subdir

require __DIR__ . '/subdir/wp-blog-header.php';
  1. Log in to WordPress at mydomain.com/subdir/admin
Credits and References

Credits

@Whitestrake @francislavoie for Caddy code design, coaching and supporting me, and challenging my thinking,

References

  1. Giving WordPress Its Own Directory
  2. Process check: Spreading the Caddy Word
2 Likes