1

I am using Wordpress 5.2.3 for a new website on a new server set up.

I have pointed the existing domain at the new server.

The old website was installed on a sub-directory. So Google etc. has indexed mywebsite.com/sub-directory for the various pages.

What is the best way to go about setting up a htaccess redirect so that any visits to mywebsite.com/sub-directory/ go to mywebsite.com/?

To clarify mywebsite.com/sub-directory/about-us would redirect to mywebsite.com/about-us

Can anyone please provide a solution?

1 Answer 1

1

At the top of your root .htaccess file (before the WordPress front-controller) add the following:

# Redirect from /subdirectory/<anything> to `/<anything>`
RewriteRule ^subdirectory/(.*) /$1 [R=302,L]

Change the 302 (temporary) to 301 (permanent) only once you have confirmed it works OK in order to avoid caching issues.

UPDATE: If I wanted to add a further rewrite /subdirectory/old-page to /new-page how would the rule change please?

You would add another rule before the above "generalised" redirect. The most specific redirect(s) should go first in order to avoid conflicts - the first rule that matches, wins in this scenario.

For example:

# Redirect from /subdirectory/old-page to `/new-page`
RewriteRule ^subdirectory/old-page$ /new-page [R=302,L]

# Redirect from /subdirectory/<anything> to `/<anything>`
RewriteRule ^subdirectory/(.*) /$1 [R=302,L]

Note that the above redirects /subdirectory/old-page exactly (ie. no trailing slash) - as in your example. If there should be a trailing slash then add a slash before the end-of-string anchor ($), in other words: ^subdirectory/old-page/$.

Or, to make the trailing slash optional, so it accepts request URLs with and without a trailing slash, use the ? quantifier. eg. ^subdirectory/old-page/?$. Now, it will match both /subdirectory/old-page and /subdirectory/old-page/ and redirect to /subdirectory/new-page (no trailing slash).

3
  • You are a genius @MrWhite that has worked perfectly. Commented Feb 7, 2020 at 8:15
  • If I wanted to add a further rewrite /subdirectory/old-page to /new-page how would the rule change please? Commented Feb 7, 2020 at 8:23
  • 1
    You would add an additional before the generalised redirect. I've updated my answer.
    – MrWhite
    Commented Feb 7, 2020 at 11:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.