Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing The Trailing Slash from a directory in htaccess

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]
like image 694
ghosh Avatar asked May 06 '13 21:05

ghosh


2 Answers

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]
like image 56
Jon Lin Avatar answered Nov 17 '22 21:11

Jon Lin


This come in handy if you want to remove trailing slash

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)$
RewriteRule ^(.*)$ https://mydomainname.com/$1 [R=301,L]

The explanation for this rule is the same as it is for when we want to add a trailing slash, just in reverse. We can also specify specific directories that we don't want apply this rule to.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !directory/(.*)$ 
RewriteCond %{REQUEST_URI} !(.*)$
RewriteRule ^(.*)$ https://mydomainname.com/$1 [R=301,L]

Source

like image 1
Gadrawin Avatar answered Nov 17 '22 21:11

Gadrawin