Fragmented Thought

Drupal 6 Bulk Redirecting Urls

By

Published:

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

Trying to do bulk redirection through the path_redirect (D6) or redirect (D7) admin is... painful. You need to enter them one at a time. Staring down a list of a couple hundred can take a full day away from you. This handy function can be run through a drush script to redirect an array of paths anywhere you like in seconds.

Drush Script

Note that this is actually a drupal 6 tested function. It's not perfect, handling for things like query strings breaks down if you try run it multiple times. But for simple aliases, it can handle it all for you. Just give it an array of a source paths like my-title-here and a destination like other/page, and watch the output.

Note that it will tell you about failed redirects, so you will have to watch for them and fix those yourself.

This code is adapted from the path_redirect admin's form validate, so it should operate in a very similar way.

There's an options trigger as well that will allow you to retain existing node aliases, or remove them if desired.

function _bulk_redirect($redirects, $destination, $options){ $options += array( 'unset_node_aliases' => FALSE ); foreach($redirects as $source){ $redirect = array( 'source' => $source, 'language' => '', 'redirect' => $destination ); $valid = TRUE; if( $path = drupal_get_normal_path($source) ){ $nid = str_replace('node/', '', $path); if( is_numeric($nid) && $node = node_load($nid) ){ if( $options['unset_node_aliases'] ){ path_set_alias('node/' . $nid, NULL); } else { $valid = FALSE; drupal_set_message('Can not redirect ' . $source . ' it is attached to an existing node:' . $node->title, 'error'); } } } if ($existing = path_redirect_load_by_source($redirect['source'], $redirect['language'])) { if ($redirect['rid'] != $existing['rid'] && $redirect['language'] == $existing['language']) { // The "from" path should not conflict with another redirect $valid = FALSE; drupal_set_message('Can not redirect ' . $source . ' it conflicts with an existing redirect', 'error'); } } if (!valid_url($redirect['redirect']) && !valid_url($redirect['redirect'], TRUE) && $redirect['redirect'] != '<front>') { //form_set_error('redirect', t('The redirect <strong>to</strong> path does not appear valid.')); } // check that there there are no redirect loops if (url(drupal_strtolower($redirect['source'])) == url(drupal_strtolower($redirect['redirect']))) { drupal_set_message('Can not redirect ' . $source . ' it is an infinate loop.', 'error'); $valid = FALSE; } if( $valid ){ drupal_set_message("Redirecting $source to $destination."); path_redirect_save($redirect); } } }