Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...