views:

36

answers:

1

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?

+2  A: 

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.

Welbog
Option 2 is appealing. I didn't know the `<base>` tag existed. Why is it frowned upon?Option 1 is not very elegant when you have to load a bunch of JS files from another JS file. Or to use images in a CMS.
wooptoo
Well, `<base>` has its own set of complications. For example, if you are using internal URLs (with hashes - like `<a href="#header2">...`) then what will happen is that URL will point to the base URL you've defined instead of an address within the page. It's also adding another level of complexity to how the URLs are built, which can make debugging them a bit of pain. Basically it's got its own concerns that you should understand before diving into it. If you're studious and read up on `<base>`, it's probably a good idea (given that you don't have fine control over the URLs your CMS creates).
Welbog