因为htaccess规则包括带有css和javascript中断的头


Because of htaccess-rules include header with css and javascript breaks

我的php项目有以下结构:

- classes
    - model.php
- views
    - header.php
    - footer.php
    - user.php
- resources
    - css
        - stylesheet.css
    - js
        - my_javascript.js
- index.php
- controller.php

.htaccess文件

RewriteEngine On
RewriteRule ^/?resources/(.*)$ resources/$1 [L]
RewriteRule ^([a-zA-Z]+)/?([a-zA-Z0-9/]*)$ index.php?page=$1&query=$2 [L]

header.php

<!DOCTYPE html>
<html>
    <head>
       <!-- Styles -->
       <link href="resources/css/stylesheet.css" rel="stylesheet" media="screen">
    </head>
    <body>

正如许多其他人之前在stackoverflow上提到的那样(但他们的解决方案对我不起作用),问题是我目前正在通过index.php重定向所有页面,甚至是我的资源文件,如stylesheet.css。

1:当我请求mydomain/user时,我会得到加载了正确css(mydomain/resources/css/stylesheet.css)的正确资源

2:但当我试图使应用程序RESTful时,我有一个像mydomain/user/4这样的页面,当我发出这样的请求时,我的css突然无法加载。查看http请求它正在查找(mydomain/user/resources/css/stylesheet.css

我试图通过包含$_SERVER['DOCUMENT_ROOT']来解决它。它不起作用,而且似乎不是一个"好"的解决方案。谢谢你的帮助。是的,我是php的新手!

由于您正在屏蔽URL,并且实际脚本运行在与URL中不同的文件夹结构上,因此您必须提供程序中引用的CSS、图像、Javascript等的完整路径。

您可以将代码更改为以下

<link href="http://www.yourdomainname.com/resources/css/stylesheet.css" rel="stylesheet" media="screen">

或者使用文件的相对路径

<link href="/resources/css/stylesheet.css" rel="stylesheet" media="screen">

由于我们在文件路径的开头使用/,服务器将从网站的根工作目录中查找文件。

同时,你应该在你的htaccess文件中添加条件,如下面的

RewriteCond %{REQUEST_FILENAME} !(resources|img|anyother folders that you want to ignore|anyother folders that you want to ignore|...)
RewriteRule ^([a-zA-Z]+)/?([a-zA-Z0-9/]*)$ index.php?page=$1&query=$2 [L]

我希望您在进行这些更改后,在htaccess中不需要RewriteRule ^/?resources/(.*)$ resources/$1 [L]

由于htaccess中的更改不起作用,我将头加载为一个绝对路径,而不是像这个一样

$http_host = $_SERVER['HTTP_HOST'];
$file_path = $_SERVER['PHP_SELF'];
$info = pathinfo($file_path);
$root_path = "http://" . $http_host . $info['dirname']; 
$path = $root_path . "/resources/css/stylesheet.css";

我希望这能帮助其他有同样问题的人。。。