htaccess – I need to redirect an entire subdirectory in WordPress to the homepage – is this correct?


RewriteRule ^subfolder [R=301,L]

Strictly speaking this redirects any URLs that start /subfolder, including URLs of the form /subfolderfoo and /subfolderbar which obviously don’t fall “within the subdirectory”. And this is regardless of whether “subfolder” is a physical subdirectory on the filesystem or an entirely virtual (WordPress) URL-path. (If it was a physical subdirectory then you could create another .htaccess file in that subdirectory instead and “simplify” the rule.)

To redirect /subfolder and only URLs that are contained within that URL-path segment, eg. /subfolder/foo and /subfolder/bar, but not /subfolderfoo etc. then you should use the following instead:

RewriteRule ^subfolder($|/) [R=301,L]

Would I need to edit it to specifically work on WordPress?

This will work on WordPress as it would on any other Apache website.

However, it must go near the top of the .htaccess file, before the WordPress front-controller. ie. before the # BEGIN WordPress section. Otherwise, if /subfolder is a virtual URL-path, the directive will never be processed (since the request would be routed to the WordPress front-controller and processing stops).

You should test first with 302 (temporary) redirects to avoid potential caching issues.

henry 1 year 2021-07-22T19:35:46-05:00 0 Answers 0 views 0

Leave an answer