WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

My old permalink structure is like this:


My new permalink structure was switched to this:


I need to set up a 301 redirect in htaccess that correctly redirects the old posts. Any help on how to do this?

share|improve this question

migrated from webmasters.stackexchange.com Apr 5 '13 at 8:53

This question came from our site for pro webmasters.

marked as duplicate by brasofilo, toscho Apr 5 '13 at 11:58

This question was marked as an exact duplicate of an existing question.

You can use this query to generate the RewriteRules that you will need. Once generated the would go into your .htaccess file and need to be prepended with:

RewriteEngine On
RewriteBase /

The following SQL output should setup rewrite rules for /postname/ to /category/postname/ based on what is in your database now. The trailing forward slash is optional.

SET SESSION group_concat_max_len = 1000000; -- make sure we can hold all the redirects
SELECT GROUP_CONCAT(CONCAT('RewriteRule ^', post_name, '/?$ ', t.slug, '/', post_name, '/ [R=301,L]') SEPARATOR '\n') redirects
FROM {$wpdb->posts} p 
JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy = 'category'
JOIN {$wpdb->terms} t ON tt.term_id = t.term_id

The output will be similar to to following:

RewriteRule ^atlanta-falcons/?$ random/atlanta-falcons/ [R=301,L]
RewriteRule ^passion-flower-pistil-negative/?$ photos/passion-flower-pistil-negative/ [R=301,L]
RewriteRule ^crane-takeoff/?$ photos/crane-takeoff/ [R=301,L]
share|improve this answer