Drupal alias your file paths using htaccess

Posted by: 
Dominique De Cooman

Clients often ask for clean urls in file names because they want to publish them in magazines so they want urls as clean as possible. H

Here is how to do this using mod_rewrite rules in htaccess:

In your .htaccess file of your drupal root folder you add following line.
For example :
All http://yourdrupal/pdf/whatever.whatever will be redirected to http://yourdrupal/sites/yourdrupal/files/private/whatever.whatever

  RewriteRule ^pdf/(.*)$ /sites/yourdrupal/files/private/$1 [L,QSA]

For more info on apache mod_rewrite rewrite rules: http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewriterule and http://httpd.apache.org/docs/2.0/misc/rewriteguide.html

To output logging you should put this in your virtual host directive:

RewriteLog /rewrite.log
RewriteLogLevel 9

This will give you a clear view on how apache is rewriting.

To not interfere with drupal rewriting you should put an extra condition in the drupal rewriting. (Taken from .htaccess)

For example

  RewriteRule ^(.*)$ /sites/default/files/$1 [L]
  #the [L] will tell apache to stop executing other rewrite rules
  # Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

More examples:


Drupal alias your file paths using htaccess

Could you give more details on the third example? For example, which portions should be customized to meet individual site needs?

Drupal alias your file paths using htaccess

Well the [L] makes apache stop doing the other rewrite rules if it finds a match.

What we want to achieve was to rewrite paths comming in from /DATASERVICE/WIKI/somefile.pdf to /sites/default/files/somefile.pdf

If this match should be made we dont want apache to try and excute yet another rewrite rule, in drupals case the default rewrite rule where you rewrite to /index?q=...

Add new comment