htaccess RewriteRule fails if page not found

2019-09-02 02:03发布

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 RewriteRules 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 RewriteRules 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.

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-02 02:47

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!

查看更多
爷的心禁止访问
3楼-- · 2019-09-02 02:54
RewriteEngine On

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !(.*)\.php
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [R] 
查看更多
聊天终结者
4楼-- · 2019-09-02 02:59

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.

查看更多
登录 后发表回答