php 当请求的文件不存在时htaccess重写脚本

oxcyiej7  于 2023-01-08  发布在  PHP
关注(0)|答案(1)|浏览(126)

我希望你能帮上忙。我正在尝试写一个.htaccess文件来完成以下任务。
1.重定向到www.地址
1.从URL中删除.php
1.如果文件不存在,则使用filechecker.php?page=filename
第一我可以

RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

第二我可以

RewriteCond %{SCRIPT_FILENAME}.php -f
RewriteRule [^/]$ %{REQUEST_URI}.php [QSA,L]

第三我以为

RewriteCond %{REQUEST_FILENAME}.php !-f
RewriteRule ^([^/]*)$ filechecker.php?page=$1 [QSA,L]

将工作,但由于某种原因,它忽略了一个事实,即该页面确实存在。

b4lqfgs4

b4lqfgs41#

2的解决方案会循环,但修复起来很简单,只需在第2部分和第3部分的文件中沿着以下代码行:

#If the Browser request contains a .php, instruct the browser to remove it.
RewriteCond %{THE_REQUEST}      \.php      [NC]
RewriteRule ^/?(.*)\.php$       http://%{HTTP_HOST}/$1         [R=301,NC,L]

#If a request is received for a non file-system object, that doesn't have a .php suffix, then store the full path, filename, and URI in a variables with that extention.
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-s
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !^\.php$  [NC]
RewriteRule ([^/]+)$      -  [E=testScript:%{SCRIPT_FILENAME}.php,E=testFile:$1.php,E=testURI:%{REQUEST_URI}.php]

#See if the file exists with a .php extention, if it does internally rewrite
RewriteCond %{ENV:testScript} -s  [OR]
RewriteCond %{ENV:testScript} -f
RewriteRule .*              %{ENV:testURI} [L]

#Else if a ENV:testDile is set, then pass the name to the php script
RewriteCond %{ENV:testFile} !^$
RewriteRule .*               /filechecker.php?page=%{ENV:testFile} [L]

仅供参考:Apache mod_rewrite文档值得一读,如果您不清楚上面的规则是做什么的,或者如果您想要一些更抽象的东西,请考虑下面的post

相关问题