自制简易PHP CMS的.htaccess重写问题:无法隐藏index.php?id=
自制简易CMS的URL重写问题
我正在开发一款仅基于PHP和HTML5的简易自制CMS,内部页面通过index.php的?id=参数传递路径,PHP代码中用$_GET['id']获取路径值来加载对应内容。
文件结构
/articles /img 404.php footer.html header.html index.php sidebar.html style.css
当前页面加载代码
if ($_GET) { $page_file = $_GET['id']; } else { $page_file = 'articles/about.html'; } $body = file_get_contents($page_file);
链接需求
侧边栏(sidebar.html)和导航菜单(header.html)中的多数链接指向/articles文件夹内的文章。在没有.htaccess重写规则时,以下链接可以正常工作:
<a href="index.php?id=articles/LICENSE.html">
我希望隐藏index.php?id=这部分,让下面这种格式的链接也能正常访问:
<a href="articles/LICENSE.html">
页面中已经设置了<base target="_top">。
.htaccess规则异常问题
我编写的.htaccess规则如下:
RewriteEngine On RewriteRule ^$ index.php [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.*) index.php?id=$1 [QSA,L] RewriteRule ^index\.php$ - [L]
目前的问题是:除了<a href="articles/LICENSE.html">这个链接外,其他功能均正常。该链接不会被重定向到index.php?id=articles/LICENSE.html,而是直接尝试访问articles/LICENSE.html文件本身。
已尝试的无效规则
我试过多种重写规则,比如:
RewriteRule ^(articles/.*) index.php?id=$1 [L] RewriteRule ^(articles/.*) index.php?id=$1 [QSA,L] RewriteRule ^(articles\/.*) index.php?id=$1 [L] RewriteRule ^articles/([A-Za-z0-9-]+)$ index.php?id=articles/$1 [QSA,L] ...
但所有尝试都无效。
奇怪的可行方案
有意思的是,如果修改index.php中的内容加载代码为:
$body = file_get_contents('articles/'.$page_file); // 或者 $body = file_get_contents("articles/$page_file");
同时将链接改成以下格式:
<a href="LICENSE.html">
保留原来的.htaccess规则,整个系统就能正常运行了!
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

