htaccess RewriteRule fails if page not found

耗尽温柔 提交于 2019-12-12 03:21:59

问题


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.


回答1:


RewriteEngine On

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !(.*)\.php
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.+)$ $1.php [R] 



回答2:


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:


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.



来源:https://stackoverflow.com/questions/9388652/htaccess-rewriterule-fails-if-page-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!