ApacheLinuxWebserver

.htaccess Rule to Redirect based on Middle of URL

By November 11, 2018 No Comments

Basic .htaccess redirects are pretty simple when you’re just taking one static url and pointing it to another.  How about when you need to redirect multiple URLs that contain a slug change in the middle of the URL?

We needed to apply this on one of our client’s sites this week and wanted to share as there are several ways out there to do this, but many didn’t work as expected.

So your basic redirect:

Redirect 301 /blog/ https://prodjex.com/web-blog/

Let’s say we want to change a category on the blog and also update the slug.  If we don’t write a rule then the user would receive a 404 error as the page no longer exists and could impact your SEO.

Example Old URL: https://www.prodjex.com/blog/htaccess-tutorials/
Example New URL: https://www.prodjex.com/web-blog/htaccess-tutorials/

To do this we’d need to look at both redirecting the category if the user visits the blog category page and any articles that exist under the category.

Here are the rules to do both:

#Redirect the Articles that exist within the category
RedirectMatch 301 ^/?blog/htaccess-tutorials/(.*)$ https://www.prodjex.com/web-blog/htaccess-tutorials/$1

#Redirect the Category
Redirect 301 /blog/htaccess-tutorials/ https://www.prodjex.com/web-blog/htaccess-tutorials/

That’s it, pretty simple.  Leave any questions in the comments below.

Leave a Reply