Removing The Trailing Slash from a directory in htaccess

ghosh picture ghosh · May 6, 2013 · Viewed 8.2k times · Source

The following is my directory structure

Root/
    index.php
    contact.php
    projects.php
                /index.php
                /project1.php
                /project2.php

I have rewrites in place to remove the .php extension from all file names. It works perfectly fine and I can access www.website.com/projects/project2.php from www.website.com/projects/project2

I also want to be able to access www.website.com/projects/index.php as www.website.com/projects

I have managed to write a rule which rewrites the url to www.website.com/projects/ when i type www.website.com/projects

However, I am not being able to get rid of the last trailing slash.

Please note that I do not really understand much of this. Most of it is from what I have found on the internet. I have looked around a lot but not got anything to work till now.

Here is the code:

Options +FollowSymLinks -MultiViews

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteRule ^projects$ /projects/index.php [L,E=LOOP:1]

Answer

Jon Lin picture Jon Lin · May 7, 2013

This is caused by mod_dir and the DirectorySlash directive. It will automatically 301 redirect requests for a directory that's missing the trailing slash. This fixes an information disclosure security concern (described in the above link) which lists the directory contents even when there's an index file (e.g. index.php). So if you turn this functionality off, be very careful about your directories. If you've got directory indexing turned off, then that's not so much of a concern.

You can turn of directory slashes using:

DirectorySlash Off

You can turn off directory indexing using the Options:

Options -Indexes

And then, you need to have your projects rule before your php extension rule:

Options +FollowSymLinks -MultiViews -Indexes

DirectorySlash Off

RewriteEngine on

RewriteRule ^projects$ /projects/index.php [L,E=LOOP:1]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]