Reputation: 5183
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.
Upvotes: 4
Views: 1611
Reputation: 3114
Based on your clarification in your comment on your question - this will be hard to handle dynamically via RewriteRule
alone.
Consider this:
How is Apache to know that /project/beta
maps to /project/folder/subfolder/beta.php
while /project/alfa
maps to /project/folder/alfa.php
?
You could hardcode these like so:
RewriteRule ^project/beta/? /project/folder/subfolder/beta.php [QSA,L]
RewriteRule ^/project/alfa/? /project/folder/alfa.php [QSA,L]
If this isn't feasible due to a large number of rules that would be required here I would attempt to solve this via a script. Something like this:
If the requested resource is not a file or directory send it to a script. Then have the script search a target directory structure such as /project
for all php files that match the second portion of your masked URL (the alfa / beta part). If only one file is found require it in order to run it.
Upvotes: 0
Reputation: 657
You can use the following regex to capture the required fields from URL. Then use captured values 1, 2 to generate the output.
([0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\/[A-Za-z0-9]*).*(\/.*)\.php
You can see the demo here. It captures the address and parent folder in 1 and filename in 2.
Note : I have considered the address to be ipv4
Upvotes: 1
Reputation: 785146
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]
Upvotes: 2