2

I am in the process of migrating a website from Wordpress to Craft and need to redirect the blog entries. In the existing site, the entries are in the root of the site, eg:

example.com/this-is-a-blog-post

In the Craft site, the post will be under a /blog subdirectory like so:

example.com/blog/this-is-a-blog-post

Assuming the slugs are the same, how would I go about creating 301 redirects for all existing posts?

1 Answer 1

3

There's a plugin to set up custom routes: Reroute by Trevor Davis, but this would require you to set them all up manually. If there's lots and lots of blog entries, you would probably want to avoid this.

As you said your slugs do match, you could just set up an ElementCriteriaModel with the slug parameter set to the relevant URI segment and see if there's an entry for that; and if that's the case redirect to that entry.

You would do this with this simple PHP code form a custom plugin. Set up a plugin and place the snippet in the init() method of your primary plugin class:

if (craft()->request->isSiteRequest())
{
    $inRoot = ((craft()->request->getSegment(2) === null) && (craft()->request->getSegment(1) !== null));

    if ($inRoot)
    {
        $criteria = craft()->elements->getCriteria(ElementType::Entry);
        $criteria->section = 'blog';
        $criteria->slug = craft()->request->getSegment(1);
        $entry = $criteria->first();

        if ($entry)
        {
            craft()->request->redirect($entry->url, true, 301);
        }
    }
}

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.