emulate the apache directory behavior, redirect domain.com/folder to domain.com/folder/

Last modified: August 5, 2009 - 02:11

This module allows Drupal to replicate the apache behaviour regarding directories, namely that when a request for http://domain.com/folder is received it's redirected with a 301 to http://domain.com/folder/ (with a trailing slash).

This module requires that a path alias with a slash exists eg folder/, if an alias doesn't exist no redirect will take place. See this post http://drupal.org/node/203632#comment-1509768 to understand why this behaviour is desirable.

I see this functionality being part of the global redirect module which currently offers the opposite behaviour (slash to no slash).

<?php
// $Id$

/**
* @file
* emulate the apache directory behavior if an alias with a slash exists
* (redirect domain.com/folder to domain.com/folder/).
*/

/**
* Implementation of hook_init().
*/
function no_slash_redirect_init() {
  $request = $_REQUEST['q'];
 
  // if request doesn't end with /
  if($request[strlen($request)-1] != '/'){
   
    // append / to request and look for alias
    $qry = "SELECT COUNT(dst) FROM {url_alias} WHERE dst = '%s'";
    $exists = db_result(db_query($qry, $request.'/'));
   
    // redirect if alias with trailing slash found
    if($exists){
      drupal_goto($request.'/', NULL, NULL, 301);
    }
  }
}

Implementation

berdman - November 11, 2009 - 21:36

I need to implement this into our site. Could you tell me where to put this code and if it's been tested on another site?

Your help is greatly appreciated.

You need to incorporate this

j0hn-smith - November 13, 2009 - 08:49

You need to incorporate this code into a drupal module (create .info and .module files to go somewhere in sites/all/modules/...). Copy the way it's done in other drupal modules. Google is your friend.

 
 

Drupal is a registered trademark of Dries Buytaert.