Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htaccess - Rewrite files that have a directory with the same name

I have a website that has multiple PHP files and directories with the same name, like so:

/projects.php
/projects
/projects/something.php

I have managed to make http://example.com/projects rewrite to http://example.com/projects.php with the following rules (using the answer here):

RewriteEngine On

# Disable automatic directory detection
DirectorySlash Off

# Hide extension
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

This works, however, when I explicitly input the directory slash to the URL, it accesses the folder. Right now:

http://example.com/projects   -->  http://example.com/projects.php  [file]
http://example.com/projects/  -->  http://example.com/projects/     [folder]

I know why it's doing this (projects/.php isn't a file). My attempt at fixing it consisted of checking if it was a folder, and replacing the slash with nothing and accessing that instead.

New .htaccess:

RewriteEngine On

# Disable automatic directory detection
DirectorySlash Off

# Hide extension
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

# Folder fix
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.*)/$ $1.php

This works as intended, however it completely messes up on the client side, as the client still has a folder in it's URL, so when it tries to fetch relative paths, it fails miserably.

Now I thought about doing a redirect with the [R=301] flag but as far as I know, %{REQUEST_FILENAME} is relative to the server, so redirecting to that wouldn't work.

If anyone could point me in the right direction, it'd be much appreciated!

like image 635
pbondoer Avatar asked Nov 06 '13 17:11

pbondoer


1 Answers

Try putting this line at the top:

Options -MultiViews

Read More About it

Your .php hiding rule should be:

RewriteEngine On

# Disable automatic directory detection
DirectorySlash Off

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ /$1.php [L]
like image 144
anubhava Avatar answered Oct 21 '22 11:10

anubhava