【问题标题】:htaccess trailing slashes break css and js fileshtaccess 尾部斜杠会破坏 css 和 js 文件
【发布时间】:2019-01-25 10:17:52
【问题描述】:

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

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

无论如何,系统使用文件 index.php 和 .htaccess 文件和 localhost/system/param1/param2/param3 之类的 url 应该只是引用 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 时,它可以工作......但是当使用诸如 http://localhost/system/param1/http://localhost/system/param1/param2/etc.. 之类的 url 时,它不再工作,因为链接不会引用正确的路径

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

部分由答案提供的答案:

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

通过将它放在我的 html 标头的顶部,它可以工作,它允许我在每次这样做时只需移动系统而无需编辑代码。

【问题讨论】:

  • 在他们前面加上一个斜线/css/style.css。然后它应该使用根路径。
  • @Sarcoma root 在 localhost/ 或 localhost/system 中
  • RewriteBase / 在 htaccess 中,/system/css/style.css 用于您的 CSS 文件链接。

标签: php .htaccess relative-path


【解决方案1】:

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

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

现在,页面上的所有内容都与https://example.com/ 相关。

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

【讨论】:

  • 啊,谢谢,在我的编辑中,我根据您的提示发布了解决方案。谢谢!
猜你喜欢
  • 2015-09-04
  • 2020-06-27
  • 2012-08-03
  • 2015-01-15
  • 2017-08-09
  • 2013-05-10
  • 2015-10-19
  • 1970-01-01
  • 2018-07-28
相关资源
最近更新 更多