html 中与 php 服务器的相对路径

Relative path in html with php server

我使用 php -S localhost:8000 作为我的开发服务器。最后我将使用 nginx。但是 php 服务器有问题。

root
|
|---/app
    |
    |---/index.html
    |---/scripts
    |   |
    |   |---/main.css
    |
    |---/styles
        |
        |---/main.js

在我的 app/index.html 我有:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="styles/main.css" type="text/css" />
</head>
<body>

  <script src="scripts/main.js"></script>
</body>
</html>

当我在浏览器中使用 localhost:8000/app 打开页面时,无法找到 css 和 javascript。浏览器正在寻找 localhost:8000/styles resp。 localhost:8000/scripts 而不是 localhost:8000/app/styleslocalhost:8000/app/scripts。当我在没有服务器或使用 nginx 的情况下直接打开文件时,文件被正确找到。所以 php 服务器改变了一些东西。这是怎么回事?

我在 Chrome 和 Firefox 中试过了。两种浏览器中的行为相同。当我使用 localhost/app (nginx) 打开网站时,一切都按预期进行。当我用 localhost:8000/app (php -S localhost:8000) 打开网站时,找不到脚本和样式。它是具有相同文件根的相同文件。不同的行为从何而来?

在查看 PHP: Built-in web server 上的官方文档后,它明确指出:

URI requests are served from the current working directory where PHP was started, unless the -t option is used to specify an explicit document root.

这是 PHP 内置 Web 服务器的一个令人讨厌的行为。幸运的是,有一个解决方法:只需在 URI 中包含 index.html 来启动您的应用程序。打开浏览器并转到

http://localhost:8000/app/index.html