Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite css/js paths

So I rewrote my paths to something like: URL/really/nice/paths/ using mod_rewrite rules like this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
</IfModule>

The question is how could I rewrite the paths for js/css/image files too, so when they are requested with a relative path from URL/really/nice/path/ to be served from URL/scripts/, URL/styles/ and URL/images/ folders instead? Can this be done without using RewriteBase?

like image 215
Radu Potop Avatar asked Dec 22 '22 04:12

Radu Potop


1 Answers

When URLs are rewritten, the client doesn't know it. So when a client looks at a page at the URL "example.com/some/url/" and the page references an image in "images/image.jpg", the client looks for the image in "example.com/some/url/images/image.jpg" even though the page actually resides in "example.com/some/other/url/". That's the problem you're facing, right?

There are three main solutions to this problem:

  1. Use absolute paths to resources instead of relative ones.
  2. Use the <base> tag to ensure that the client knows the root upon which to build its relative URLs is different from the page's apparent URL.
  3. Add a new rule for "some/url/images/" in your rewrite rules.

Option 1 is probably the best idea, and you'll find that most sites that use URL rewriting use it, including Stack Overflow itself. Option 2 is frowned upon, but works and is relatively easy. Option 3 is the most difficult to maintain, as URL rewriting exceptions and special cases can appear as you're defining new rules.

The most maintainable solution is to use absolute URLs.

like image 140
Welbog Avatar answered Dec 28 '22 10:12

Welbog