mod_rewrite to index.html breaks relative paths for deep URLs

你离开我真会死。 提交于 2019-11-29 02:46:10

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.

I'm using this for html5 history support -- anything in the js, css, img, or svc directories is unmodified. Everything else goes to index.html:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^(js|css|img|svc)($|/) - [L]
RewriteRule ^(.*)$ index.html [L]

Note, I just saw your comment below. If you reference your scripts as

<script src="/js/myscript.js"> 

then you shouldn't need to worry about the base location of your html. Note the slash before "js". I realize this was pointed out in another answer, but the comination of that technique and the rewrite rules might do the trick.

I also wanted all URL's routed to the same file on my server, and found this. The code provided there does exactly what you're after. Here is that code:

Options +FollowSymLinks
IndexIgnore */*
# Turn on the RewriteEngine
RewriteEngine On
#  Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

This would route everything to index.php. Just change it to index.html for your purposes, and I think that will work.

BTW, something like "www.mydomain.com/more/nested/resource/123" would be routed successfully.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!