htaccess – How to Implement Multiple 301 Redirects

.htaccess301-redirectWordpress

I am moving a blog hosted on an Apache server to a new domain.

The permalinks are kept the same for the blog posts but there are a few pages where the url slug will change on the new domain.

My question is if the following is possible and how I would do that with rewrite rules.

The URL slugs/permalinks of the blog posts and most of the pages on the old domain will stay the same on the new domain. So I imagine that I could add a redirect rule that redirects from https://huiskopenomteverhuren.nl/ to https://vastgoedmentor.com as it will find the same /slug on the new domain

Some pages of the old website have moved to new permalink. So I need additional rules to redirect for example https://huiskopenomteverhuren.nl/kennisbank/ to https://vastgoedmentor.com/resources and do this for a few other pages as well.

Best Answer

You can create multiple RewriteRule directives with regular expressions within your server configuration. You should start with the specific redirects with changed permalinks. The general redirect for all other pages can be added at the end.

RewriteEngine On

RewriteRule ^/kennisbank(/.*)?$ https://vastgoedmentor.com/resources$1 [END,R=301]
RewriteRule ^/old2(/.*)?$       https://vastgoedmentor.com/new2$1      [END,R=301]
RewriteRule ^/old3(/.*)?$       https://vastgoedmentor.com/new3$1      [END,R=301]

RewriteRule ^/(.*)$           https://vastgoedmentor.com/$1           [END,R=301]

The notation of (/.*)? will perform the redirect with and without a trailing slash and add any additional path details to the new URL. Hence, it will turn huiskopenomteverhuren.nl/kennisbank/something-or-nothing to vastgoedmentor.com/resources/something-or-nothing.

More details on the RewriteRule can be found at https://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriterule

As all rules point to a different domain there is no risk to run into a loop. But it is still a good idea to add the END flag to all rules to avoid the remaining rules to be evaluated. Other than the L flag, the END flag also avoids evaluation any additional rules in .htaccess files.

More details on the flags can be found at https://httpd.apache.org/docs/current/rewrite/flags.html

Related Topic