codepixlabs codepixlabs - 2 years ago 95
PHP Question

Rewrite URL : remove sub folders and file extension from URL

I am trying to remove .php file extension and folder && subfolder from URL if they exist.

Case 1

Input:

127.0.0.1/project/folder/alfa.php


output:

127.0.0.1/project/alfa


Case 2

Input:

127.0.0.1/project/folder/subfolder/beta.php


Output:

127.0.0.1/project/beta


Here is what I have got so far :

Removing just extension works fine, having problem with removing folders

# Turn mod_rewrite on
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^((?! folder/).+?)/?$ folder/ [L,NC]


RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]


Please advice
Thanks.

Answer Source

You can have this .htaccess inside /project/ directory:

RewriteEngine On
RewriteBase /project/

# rewrite to folder/subfolder/
RewriteCond %{DOCUMENT_ROOT}/project/folder/subfolder/$1.php -f
RewriteRule ^(.+?)/?$ folder/subfolder/$1.php [L]

# rewrite to folder/
RewriteCond %{DOCUMENT_ROOT}/project/folder/$1.php -f
RewriteRule ^(.+?)/?$ folder/$1.php [L]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download