URL重写:包括源文件到“index.php”;从不存在的HTTP请求中获取


URL rewriting : including source files to "index.php" from HTTP requests which don't really exist

我在URL localhost/site/有一个小网站。它有一个.htaccess文件,一个index.php文件和一个文件夹,用于存储名为img

的图像

。htaccess

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

如上所述,如果localhost/site的url不是目录或文件,则该url将重定向到index.php

index . php文件

<html>
<body>
    <img src="img/logo.png"/>
</body>
</html>

当我转到localhost/sitelocalhost/site/[any_text]时,它工作正常,这是index.php将成功加载文件img/logo.png

但是如果我去localhost/site/[any_text]/[any_text]或进一步到localhost/site的任何子目录(这真的不退出,只有一个请求)index.php将不会加载img/logo.png

为什么呢?

出现这种情况是因为包含的图像没有前导斜杠或其他形式的定位符,如协议和域,将使客户端认为路径是相对于当前查看的路径。因此,如果您正在查看http://example.com/folder/page.html,则img/logo.png的相对映像路径将使客户端请求http://example.com/folder/img/logo.png

如果你插入一个前导斜杠,你将告诉客户端该图像位于相对于网站的根目录,它将导致客户端请求文件http://example.com/img/logo.png

正确的图像html代码应该是:

<img src="/site/img/logo.png" />
<img src="/img/logo.png"/>
          ^ note the leading slash