nginx: Easily Resolve “404 Not Found” for WordPress Subdirectories

When running a WordPress website, sub-directories are often used for pages or for multi-site WordPress setups. However, you may sometimes encounter a 404 Not Found error when trying to access sub-directories. The homepage may work fine, but the subdirectories may be inaccessible.

This issue can be easily resolved by updating the nginx configuration. The following block of code can be added to let nginx know to redirect traffic for subdirectories to the WordPress site corresponding to the domain name:

if (!-e $request_filename) {
    rewrite /wp-admin$ $scheme://$host$uri/ permanent;
    rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 last;
    rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ $1 last;
}
location / {
    try_files $uri $uri/ /index.php?$args ;
}

The nginx configuration file on your server may resemble the following example.

After updating the configuration, restart the nginx server.

sudo systemctl restart nginx

The 404 Not Found error should now be resolved and sub-directories should be accessible.

Leave a Reply

Your email address will not be published. Required fields are marked *