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:
- Sideloading other assets without mixing them up with WordPress files.
- 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:
- Without a change in the WordPress URL (
mydomain.com
) - 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.
- After Installing WordPress in the root folder, move everything from the root folder into
subdir
. - 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
Depending on your PHP-FPM config, the php_fastcgi
can also be php_fastcgi 127.0.0.1:9000
.
- 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.
- Create
subdir
under the webroot. - From the WordPress General Settings screen, set the WordPress address (URL) and then click Save Changes. Ignore the erros that appear.
- Move the WordPress files from the webroot to
subdir
. - Copy (don’t move!)
index.php
back into the webroot. - 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';
- 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,