Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

javascript - mod_rewrite to index.html breaks relative paths for deep URLs

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]

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.

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

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

would translate into src="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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I got it to work and this is how:

When you give the following as the src:

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

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>

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...