我正在一个自制的糟糕的 CMS 中工作,仅使用 PHP 和 HTML5。内部链接作为参数通过
index.php
传递给 ?id=
,并使用 $_GET['id']
恢复。
我的文章将存储在
/articles
文件夹中,图片存储在/img
中,CSS和标准框架存储在/
中:
/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
)中的大多数链接将指向文章文件夹中的帖子。因此,在没有 .htaccess
重写规则的情况下,这是有效的:
<a href="index.php?id=articles/LICENSE.html">
但是我想隐藏
index.php?id=
,所以我可以写这个并且它继续工作:
<a href="articles/LICENSE.html">
在这两种情况下:
<base target="_top">
。
我的
.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);
or
$body = file_get_contents("articles/$page_file");
并链接到:
<a href="LICENSE.html">
并遵守规则:
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]
有效!
@cbroe帮助了我。
articles/LICENSE.html
实际上作为文件存在。
正确
.htaccess
来处理这个问题:
RewriteEngine On
RewriteRule ^$ index.php [L]
RewriteRule (.*\.html)$ index.php?id=$1 [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?id=$1 [QSA,L]
RewriteRule ^index\.php$ - [L]
此外,为了避免多次点击许可证链接并变成:
/articles/articles/.../articles/articles/LICENSE.html
,我必须使用根相对 URL。
这是因为相对 URL 的工作原理。从浏览器的角度来看,您位于 /articles/ 文件夹“中”,因此根据该文件夹解析相对 URLarticles/LICENSE.html,结果为 /articles/articles/LICENSE.html。使用根相对 URL,以前导斜杠开头。
右:
<a href="/articles/LICENSE.html">
错误:
<a href="articles/LICENSE.html">