我正在尝试通过 htaccess 找到执行以下操作的方法。
- 删除 (.php) 扩展名
- 删除尾部斜杠 (/)
- 将以前的 (.php) 页面重定向到非 php 页面
- 将根索引的所有跟踪重定向到根域
这是目录结构的示例。
"http://example.com" (canonical - this is what I want)
"http://example.com/index" (redirect or 404)
"http://example.com/index/" (redirect or 404)
"http://example.com/index.php" (redirect or 404)
"http://example.com/index.php/" (redirect or 404)
"http://example.com/about" (canonical - this is what I want)
"http://example.com/about/" (redirect or 404)
"http://example.com/about.php" (redirect or 404)
"http://example.com/about.php/" (redirect or 404)
更新:
这就是我当前的配置,使用 php 委派规范链接并执行重定向/显示 404。如果您发现它有问题或可以提供更好的解决方案,我将非常感激。现在下面的代码可以工作,通过给每个 php 文件它自己的特定于页面的规范链接函数。然后,该函数会识别当前页面是否与规范页面相同,否则将引发错误,使预期页面成为唯一可以访问内容的页面。
ErrorDocument 404 /404.php
RewriteEngine On
#removes trailing slash
RewriteCond %{HTTP_HOST} ^localhost:8888$
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
#removes php extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
<?php
function resolve_canonical($canonical,$location = "404"){
$current_url= "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
if($current_url !== $canonical){
if($location == "404"){
//header("location: http://".$_SERVER['HTTP_HOST']."/404");
//header("HTTP/1.0 404 Not Found");
readfile('404.php');
exit();
}elseif($location == "redirect"){
header("location: ".$canonical);
exit();
}
}
}
?>