Reputation: 2040
I've set up a .htaccess file to rewrite the url example.com/foo
too example.com/foo.php
I can separately get the URL to redirect to error.php
if it ends in .php, but I can't seem to do both together.
I've seen other sites hide .php and I want to understand how to do that.
Here's what I've tried:
//.htaccess file
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^([A-Za-z0-9-_]+)/?$ $1.php [NC,L]
RewriteRule ^([A-Za-z0-9-_]+).php?$ error.php [NC,L]
NOTES
Here is what worked for me. I'm going to leave it hear for reference as I'm not sure it all necessarily is necessary.
RewriteEngine On
RewriteRule (.*)index$ http://%{HTTP_HOST}/error [R=404]
RewriteCond %{THE_REQUEST} ^\w+\ /(.*)\.php(\?.*)?\ HTTP/
RewriteRule ^ http://%{HTTP_HOST}/error [R=301]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule .* $0.php
ErrorDocument 404 /error.php
ErrorDocument 301 /error.php
Upvotes: 0
Views: 207
Reputation: 42935
Considering your comment to your own question it seems this is what you are looking for: If the request targets something to what a php script exist with the same name but an added .php
file name extension, then internally rewrite to that. Rewrite to /error.php
in all other cases, if the request resource does not directly exist in the file system.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /error.php [L]
And a general hint: you should always prefer to place such rules inside the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).
Upvotes: 1
Reputation: 3990
I do it using this two rules:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
Upvotes: 1