Reputation: 14984
I'm trying to user RewriteRule
in my .htaccess
file to redirect example.com/page to example.com/page.php (or add the .php
to any requested file that does not have an extension.
I tried:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !(.*)\.php
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^/.]+)$ $1.php [R] #I also tried ^(.+)$ with no effect
from "Spoofing" a 404 not found error with .htaccess
I tried this with no other RewriteRule
s in my .htaccess, but it still just resolves to the 404 error page via the ErrorDocument
. All other rules I try to use also get completely skipped if the requested page is not found. Any rule I specify works if the requested url resolves to an existing page or directory.
I have a Godaddy shared hosting Linux server. I am pretty sure that I cannot edit my httpd.conf file.
I'm wondering if anybody could tell me why my RewriteRule
s are ignored when the original request is not a file or directory - when it doesn't exist.
Thank you for any help.
EDIT:
I now see that if I go to mysite.com/index.php RewriteRule works. If I go to mysite.com/index RewriteRule does not work. If I go to a page that does not exist at all - mysite.com/asdfasdfsadf then my RewriteRule works. So it only fails on the extensionless version of an existing url.
Upvotes: 0
Views: 3838
Reputation: 51
I think,
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d
should help.
RewriteBase /
is only for Directory or Location, not for whole VirtualHost!
Upvotes: 4
Reputation: 14984
I did come up with a rudimentary solution using my 404 error page. In my htaccess, I add:
ErrorDocument 404 /error/404.php
And then in 404.php, I have the following code:
$request = $_SERVER['REQUEST_URI'];
$ext_pos = strpos($request, ".");
if (!$ext_pos){
$request = $request.".php";
header("Location: ".$protocol.$domain.$request);
}
It is functional, but does not do exactly as I desire, unfortunately. I want all of the re-writing to work within the .htaccess file.
Upvotes: 1
Reputation: 36
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !(.*)\.php
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [R]
Upvotes: 2