本文介绍了mod_rewrite 到 index.html 会破坏深层 URL 的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于单页应用程序,我的 .htaccess 文件中有以下 RewriteRule 将所有流量定向到 index.html,以便 JS 可以解析 URL 并相应地触发控制器.

For a single-page app, I have the following RewriteRule in my .htaccess file to direct all traffic to index.html so that a JS can parse the URL and fire controllers accordingly.

  # html5 pushstate (history) support:
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !index
  RewriteRule (.*) index.html [L]

这适用于顶级 url,例如 www.mydomain.com/resource,但任何更深的 url,例如 www.mydomain.com/resource/123,都会在 index.html 中破坏当前目录 ('.') 的值.html.

This works fine for top level urls like, www.mydomain.com/resource but anything deeper, like www.mydomain.com/resource/123, breaks the value of the current directory ('.') while in index.html.

例如,我的 index.html 中的 script 标签是这样的

For example, a script tag in my index.html like this

<script src="js/app/config.js"></script>

将转换为 src="resource/app/config.js"

would translate into src="resource/app/config.js"

或者,对于像www.mydomain.com/more/nested/resource/123"这样的 url,同一个 js 文件上的 src 将被解释为more/nested/resource/app/config.js".

Or, for a url like 'www.mydomain.com/more/nested/resource/123' the src on that same js file would be interpreted as "more/nested/resource/app/config.js".

不用说,这些文件不存在并且应用程序崩溃了.

Needless to say, those files don't exist and the app breaks.

任何人都可以对这里发生的事情有所了解吗?谢谢.

Can anybody shed any light to what is going on here? Thanks.

推荐答案

我让它工作了,方法如下:

I got it to work and this is how:

当您将以下内容作为 src 时:

When you give the following as the src:

<script src="js/app/config.js"></script>

您是对的,Apache 正确地重新路由到 index.html(或您拥有的任何后备 URL),然后尝试根据 URL 中的嵌套路径相对地访问资源.

you're right in that Apache correctly reroutes to index.html (or whatever fallback URL you have) and then tries to access resources relatively according to nested path in the URL.

要更正此问题,您需要以/"开头来表示根目录,如下所示:

To correct this, you need to have a leading "/" to signify the root directory, as follows:

<script src="/js/app/config.js"></script>

一旦我为我的 js 库、css 表等做了这个,它就工作得很好,backbone.js 从那里处理了所有的 URL.

Once I did this for my js libraries, css sheets, etc, it worked perfectly fine and backbone.js handled all URLs from there out.

注意:在 Apache 2.2+ 中,您现在可以使用 FallbackResource 而不是 mod_rewrite,它需要更少的行并完成相同的事情.

Note: In Apache 2.2+, you can now use FallbackResource instead of mod_rewrite, it requires fewer lines and accomplishes the same thing.

推荐的另一件事是尽可能使用绝对网址.

Another thing recommended is to use absolute URLs whenever you can.

这篇关于mod_rewrite 到 index.html 会破坏深层 URL 的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 18:43