CSS, Images, and JS not loading due to url rewrite

2019-07-31 01:54发布

问题:

I'm having trouble with css and images loading the moment my url ends in a /. I'm working off my localhost and the urls are rewritten in the form:

localhost/mysite/public/user/testuser/books/1234

With the request loading the user profile page of testuser and changing the page state to focus on a book with the id 1234.

Everything works fine with localhost/mysite/public/user, but the moment I introduce a / or /testuser to the url the CSS, JS, and Images break. I do have url rewriting in place and read a number of posts that state its a .htaccess rewrite problem. Here is the structure of my site:

mysite/
    app/
        controllers/
        models/
        etc...
    public/
        css/
            styles.css
        images/
            profilepic.png
        js/
    index.php

All images, js, and css are referenced via relative path: ex: ../public/css/styles.css.

Contents of .htaccess are:

Options -MultiViews
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

I read a mix of solutions including changing all the paths to absolute or changing them to /css/styles.css for example. Absolute of course works, but that doesn't make sense when I move the site to its actual domain I would need to change every instance.

There was also a note about excluding css, jpeg, etc... files from the rewrite using:

RewriteCond %{REQUEST_URI} !^.*\.(css|jpe?g|gif|png|js|ico)$ [NC]

Unfortunately none of these options worked and I'm not sure where else I should look. Any ideas?

回答1:

If you don't want to change every instance when you move your site, just update the <head> section of your html page header and add this

<base href="http://www.example.com/" />

or

<base href="/" />

This will take care of that problem and you don't have to update all instances to absolute paths.