tags:

views:

82

answers:

3

Maybe not tricky for some, but tricky for me.

I recently moved things around on my blog and I need to easily redirect users to the new pages.

Previously, I had all of my articles linked like so:

http://www.my-site.com/blog/my-article-title

But I changed it to:

http://www.my-site.com/blog/article/my-article-title

I want to redirect users visiting "blog/my-article-title" to "blog/article/my-article-title".

The tricky part is that I have other sections to my blog, like archives and search, whose URLs are "blog/archives" or "blog/search". As you might already be thinking, a smarter solution is required so users looking for my archives page don't get forwarded to a non-existing article called "archives".

Any help?

+6  A: 

You want to use mod_rewrite (or your web-servers equivalent) and not php for this.

Evan Carroll
A: 

You can use a negative lookahead, like this:

blog/((?!archives|search).+)
Alix Axel
+4  A: 

This is better done in your .htaccess file than PHP; and Jamie Zawinski's famous quote about having two problems if you use regex springs to mind. You need minimal regex for .htaccess and none at all for PHP.

RewriteCond $1 !^(archives|search)
RewriteRule blog/(.*) http://www.my-site.com/blog/article/$1 [R=301]

Or if you have RedirectMatch available, you can combine it with the negative lookahead as already suggested:

RedirectMatch permanent blog/((?!archives|search).+) http://www.my-site.com/blog/article/$1

If you need to use PHP:

$urlparts = explode('/', $_SERVER['REQUEST_URI']);

if ( ! in_array($urlparts[1], array('archives', 'search')) ) {
    $url = 'http://www.my-site.com/blog/article/' . $urlparts[2]
    header('HTTP/1.1 301 Moved Permanently');
    header("Location: $url");
    exit;
}

As you can see, it's much more complicated in PHP and also requires launching an interpreter to do something the server could have done, so avoid that way if you have the option.

Duncan
Thank you, this solution works
iamthejeff