MODX Redirectoid - Redirect with HTTP/1.1 Response Code

Feb 5, 2013

Redirectoid: Super-Simply Redirect

Redirectoid is a super-simple redirector snippet for MODX Revolution that can accept an ID of the Resource you'd like to redirect to (defaults to the site_start) and optionally a response code of 302, 303, or 307 as per HTTP/1.1 protocol described here:

Simply call the snippet like this: [[Redirectoid]]

Requests to that page will be redirected to the site_start. Optionally provide an ID and response code:

[[Redirectoid? &id=`3` &responseCode=`307`]]

This will redirect the page with the snippet call to the Resource with ID 3, sending a Redirect Status Code of "307 Temporary Redirect".

It comes in really handy when you use Resources as slide items, or items in other listings, where you want the Resource to be published, but don't really want people visiting the Resource directly. Just add this snippet to the content field or perhaps a blank "Item Template" with a redirect to the parent ID that actually displays the styled content, like this:

[[Redirectoid? &id=`[[*parent]]`]]

Redirectoid is available in the MODX Extras Repository. Install via Package Management. If you're nostalgic about installing snippets manually like in the Evo days, here's the code:

*UPDATE: there have been newer versions released since this post—the code below is outdated. The repo is hosted on Github here.

// Set defaults  
$id = $modx->getOption('id', $scriptProperties, $modx->getOption('site_start'));  
$responseCode = $modx->getOption('responseCode', $scriptProperties, '301');    

//Set redirect status in accordance with HTTP/1.1 protocol defined here:  
switch ($responseCode) {
    case '302': $redirectStatus = 'HTTP/1.1 302 Found';
    case '303': $redirectStatus = 'HTTP/1.1 303 See Other';
    case '307': $redirectStatus = 'HTTP/1.1 307 Temporary Redirect';
    default: $redirectStatus = 'HTTP/1.1 301 Moved Permanently';  

// Make the URL and send  
$url = $modx->makeUrl($id);  
$modx->sendRedirect($url,array('responseCode' => $redirectStatus));

Vive La MODX!