301 Redirect Drupal to WordPress

301 Redirect

301 Redirect Drupal to WordPress

Just having converted my website over to WordPress from Drupal,
the one thing I wanted to do was to keep my rankings for some of my old posts by making sure I redirected my old Drupal links to my new WordPress links.  This is how I was able to accomplish this with 301 Redirect.

301 Redirect

For those of you not familiar with the URL formats of Drupal, your basic link is http://www.example,com/?q=node/xx, where xx is the ID of the post / page.  For WordPress, your basic link is http://www.example.com/?p=xx, where xx is the ID of the post / page. Seems like a pretty basic problem to resolve with some .htaccess rewrite rules.

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on

# Rewrite Drupal URLs to WordPress
# Drupal form ?q=node/11 to WordPress form ?p=11
RewriteCond %{QUERY_STRING} ^q=node/(.+)$
RewriteRule ^(.*)$ https://kylestubbins.com/?p=%1 [R=301,L]

</IfModule>

Done. Simple. We grab the QUERY_STRING (everything after the ?) and then grab the number from the end, if it matches our pattern of q=node/xx, rewrite it to our WordPress format and give a 301 Redirect.

So I go to Google, do a site search and check some links.  404 errors. What?   Seems I forgot about Drupal’s clean URLs, which is using the format of http://www.example.com/node/xx.  Again, no real big deal. We just need another re-write rule.

But wait!  Where is our QUERY_STRING? We don’t have one with our clean URLs.  Not to fret, we can use the REQUEST_URI and do a RegEx test on that.  Our conditional test for this is;

RewriteCond %{REQUEST_URI} ^/node/(.+)$

This time, we are looking for a match on the form “/node/xx” (without the quotes), we still grab the page ID (the xx part) and do the same rewrite as we did the first time.

RewriteRule ^(.*)$ https://kylestubbins.com/?p=%1 [R=301,L]

We can add this rewrite condition below the first condition and above the actual rewrite rule, like so;

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine on

# Rewrite Drupal URLs to Wordpress
# Drupal form ?q=node/11 to WordPress form ?p=11
RewriteCond %{QUERY_STRING} ^q=node/(.+)$
RewriteCond %{REQUEST_URI} ^/node/(.+)$
RewriteRule ^(.*)$ https://kylestubbins.com/?p=%1 [R=301,L]

</IfModule>

Now, it doesn’t matter which form the URL comes in as, they are both rewritten to the the new WordPress form.  Both of these links will redirect back to this post;

https://kylestubbins.com/?q=node/498
https://kylestubbins.com/node/498

So, why does the URL for this post show up as https://kylestubbins.com/301-redirect-drupal-wordpress and not https://kylestubbins.com/?=498?  That’s the WordPress Permalinks system at work!

 

Leave a Reply