Programatically Create 301 Redirects

The Drupal 7 Redirect module gives a site the ability to redirect from one URL to another using a proper HTTP redirect status (e.g., 301 - Permanently moved). In addition to the user interface there is a programmatic method for entering redirects.

The aptly named redirect_save function takes an object containing the details of the redirect and creates a redirect for the URL.

Here is an example of creating a redirect. A status code of 0 uses the default redirect setting which is 301, unless changed in settings.

// Create an object with our redirect parameters
$redirect = new stdClass();
$redirect->source = 'the-old-url';     // From URL
$redirect->source_options = array();
$redirect->redirect = 'node/1';        // To URL
$redirect->redirect_options = array();
$redirect->status_code = 0;            // Redirect Status, 0 is default
$redirect->type = 'redirect';
$redirect->language = LANGUAGE_NONE;

// Create the redirect


If you use Context there's an alternative in the Context Redirect module that myself and kevinquillen cleaned all the critical/major issues out of about a month ago. Since it uses Context all the redirects are natively exportable through Features :)

The Path redirect import module provides a GUI for this.