htaccess 尾部斜杠中断 css 和 js 文件

htaccess trailing slashes break css and js files

好的,虽然这类 htaccess 问题被问了很多,但我找不到适合我的情况的(部分)解决方案。

所以我有这个系统可以放在任何系统中,例如localhost/system或localhost/folder/here

无论如何,系统使用文件 index.php 和 .htaccess 文件以及 url 像 localhost/system/param1/param2/param3 应该只引用 index.php但是,放置在 localhost/system/css/ 中的样式表在调用时应该仍然可用。

Htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php [L,QSA]

index.php:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>MyPage</title>
    <link rel='stylesheet' type='text/css' href='css/style.css' />
    <script src='js/index.js'></script>
</head>

<body>
content...
</body>
</html>

如您所见,我喜欢保持路径相对。 当使用 url http://localhost/system/param1 is being used it works... however when an url such as http://localhost/system/param1/ or http://localhost/system/param1/param2/etc.. 它不再有效,因为链接将不会引用正确的路径

我该如何解决这个问题? 正如我所说,堆栈有多个关于此的主题,但我找不到一个解决相对路径的问题。

答案部分由答案提供:

<?php
$basePath = str_replace('index.php', '', $_SERVER['PHP_SELF']);
echo "<base href='{$basePath}' />";
?>

通过将它放在我的 html header 的顶部,它起作用了,它允许我每次移动系统而无需编辑代码。

根据您构建网站的方式,在这些情况下通常最简单的方法就是设置一个基础 URL。将其作为 <head> 标记中的第二个元素,紧跟在字符集声明之后:

<base href="https://example.com/" />

现在,页面上的所有内容都相对于 https://example.com/

(当然,替换为任何你想要的基础。如果你真的只是在任何地方都使用网站的根作为基础,你可以简单地删除它并在引用你的 CSS 文件时使用完整路径, 以 / 开头。)