Ben Holness
Ben Holness

Reputation: 2707

Using htaccess to remove .php and allow path

I currently have a .htaccess file that allows people to enter the URL without the php extension, such that http://domain.com/account redirects to account.php

I would like to be able to have it so that if I enter http://domain.com/account/contactinfo (or http://domain.com/account/settings/groups and so on) it still goes to account.php, but I am not sure how to change what I have to achieve this.

Current .htaccess :

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(([A-Za-z0-9\-_\.]+/)*[A-Za-z0-9\-_\.]+)?$ $1.php

Any help appreciated! Obviously if there exists a folder it should follow that path (e.g. if /folder/page.php exists, then http://domain.com/folder/page/create would go to folder/page.php)

Upvotes: 1

Views: 571

Answers (1)

Mike Brant
Mike Brant

Reputation: 71384

Try this is you don't need to pass any URI info into query string (i.e. your app will still look at $_SERVER['REQUEST_URI'])

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([A-Za-z0-9\-_\.]+)(/[A-Za-z0-9\-_\.]*)?$ $1.php&q=$2 [QSA]
# Note the optional '&q=$2' on line above if you want to make removed part of URI available as passed parameter

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ / [L,QSA]

Note that since I removed the condition to check for a valid php file, I added a second conditional rewrite rule to just redirect to site root if the re-written request does not point to a valid PHP file. You could obviously redirect this to a 404 page or whatever else you might want to redirect to. Or you could remove this altogether and let Apache give it's default 404 response.

Upvotes: 1

Related Questions