.htaccess 配置为支持 pushState;多参数页面错误 URL

.htaccess configured for pushState support; page errors on multi-parameter URL

我在我的 .htaccess 文件中使用以下配置来支持网站上的 HTML5 pushState 导航:

# HTML5 pushstate support
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ / [L]

当网站的 url 类似于:

时,此方法效果很好
www.example.com/foo

但是,当我使用更复杂的 URL 例如:

时,我开始遇到错误
www.example.com/foo/bar

我找到了 this Whosebug posts which directly addresses my issue。建议的解决方案确实有效,但对我来说,这似乎是解决问题的错误方法。建议的解决方案是为给定页面提供一个 <base> 标记,例如:

<!DOCTYPE html>

<html>
    <head>
        <title></title>
        <base href="/" />
    </head>

    <body>
    </body>
</html>

之所以有效,是因为 according to documentation <base> 标签更正了相关链接。

好吧,很公平,但这就是 .htaccess 文件应该为我做的,对吧?

这是 can/should 在服务器级别而不是在每页的基础上配置的东西吗?还是以这种方式使用 <base> 标签是标准的?

实际上是一个HTML源码问题,正在通过以下方式解决:

<base href="/" />

这样每个 亲戚 URL 都是从该基础 URL 解析的,而不是从当前页面的 URL.

当您当前 URL 为:

http://www.example.com/foo/bar

并在 css/js/image 中包含 相对路径 例如:

<img src="images/header.jpg">
<link rel="stylesheet" type="text/css" href="styles/site.css">

然后浏览器将从当前的 URL 中解析以上相对 URLs 使它们:

http://www.example.com/foo/images/header.jpg
http://www.example.com/foo/styles/site.css

因此导致您的图片和上述 css 路径出现 404。

使用上面定义的 <base> 浏览器将 正确地 上面 URL 的请求为:

http://www.example.com/images/header.jpg
http://www.example.com/styles/site.css

当然可以重写一些重写规则,通过使用扩展识别这些资源,将每个 image/css/js 重定向到根路径,但这些最多是补丁。

<ifModule mod_rewrite.c>
 RewriteEngine On


# Required to allow direct-linking of pages so they can be processed by Angular
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !index
RewriteRule (.*) index.html [L]

</ifModule>