Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect old Wordpress blog posts urls to new ones

My Wordpress site's blog post URLs used to look like this:

http://example.com/some-random-blog-post-name http://example.com/other-random-blog-post-name http://example.com/in-case-you-dont-get-the-point-theyre-all-different

On my new Wordpress site I want them to live in a /blog/ subdirectory where they belong:

http://example.com/blog/some-random-blog-post-name

What's tricky about this is that the old URLs follow no pattern, so I think I need to match against anything unrecognized. Something like this almost works...

# Redirect unmatched blog posts to /blog/*
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !blog
RewriteCond %{HTTP_HOST} ^example.com [NC,OR]
RewriteRule ^(.*)$ https://example.com/blog/$1 [L,R=301,NC]
</IfModule>

...but it conflicts with Wordpress's own RewriteRules, and breaks all the other site pages that should pass through unchanged.

So how can I achieve the following:

example.com/some-random-post 301--> example.com/blog/some-random-post example.com/another-random-post 301--> example.com/blog/another-random-post

example.com/contact/ --> (No redirect)

like image 908
emersonthis Avatar asked Mar 11 '16 19:03

emersonthis


People also ask

How do I redirect a blog post?

Go to your Blogger blog dashboard, then settings >> search preferences. You can find a Custom Redirects from the Errors and Redirection section. You can enter the old post or URL in the From URL field.


1 Answers

Inside 404.php (or 404 handler) of your theme you can use this snippet at start of the file:

<?php

$url = $_SERVER['REQUEST_URI'];

if (stripos($url, "/blog/", 0) !== 0) {
   header("Location: " . "/blog" . $url);
   exit;
}

// rest of the 404 code
?>
like image 156
anubhava Avatar answered Oct 05 '22 06:10

anubhava