mod_rewrite to index.html breaks relative paths for deep URLs

前端 未结 3 1046
轻奢々
轻奢々 2020-12-16 08:41

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 accordin

相关标签:
3条回答
  • 2020-12-16 09:02

    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.

    0 讨论(0)
  • 2020-12-16 09:14

    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.

    0 讨论(0)
  • 2020-12-16 09:26

    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.

    0 讨论(0)
提交回复
热议问题