[Drupal] Adding slashes to the end of virtual directory names in Drupal using htaccess rules

| | 1 min read

In Drupal every path in the site goes via index.php and goes through some Drupal menu. However to make the Drupal application behave live a typical static website in terms of URL architecture sometimes clients request for adding slashes to the end of virtual direcotry paths. At the same time slashes would not look good at the end of virtual file paths. There is an easy way to do this using apache htaccess rules

  # Rewrite rule to add trailing slashes to virtual directories but not to virtual files.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !\.[a-z]*/?$
  RewriteCond %{REQUEST_URI} !/$
  RewriteRule ^(.*)$ $1/ [L,R=301]

  # Rewrite rule to strip trailing slashes from virtual files.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} \.[a-zA-Z]*/?$
  RewriteCond %{REQUEST_URI} /$
  RewriteRule ^(.*)/$ $1 [L,R=301]

The assumption here is that a virtual directory path is one which does not have an extension and a virtual file path is one which has an extension.