Mod_rewrite path problem?


#1

I have the following .htaccess to deal with different ways of accessing the same page:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^([0-9a-zA-Z]+)$ index.php?p=$1
RewriteRule ^([0-9]+)/([a-z0-9-]+)/$ index.php?sa=$1&sb=$2

The first rule matches any short URL, e.g. http://[mysite]/p8Dn, and translates it to the internal id for the requested page. This works fine.

The second rule looks for a URL like

http://[mysite]/4/search-engine-friendly-title/

and extracts the two parts, which PHP uses to locate the page id as before. This generates exactly the same HTML but none of the images (on relative paths) get shown and the local CSS seems to be ignored too.

Is it a path problem? Do I need to use RewriteBase, and if so, how?


#2

Chances are that your PHP script is generating references to CSS and/or images with relative paths, such as:

Since your page is now appearing to the browser in a subdirectory, this ends up getting interpreted as the image being loaded from:

Since that doesn’t exist, the image cannot be loaded.

RewriteBase won’t help you here. You will need to update your application such that it generates absolute paths for images, e.g:

(The leading slash is the critical change here.)


#3

Many thanks for that - I did as you suggested and the page now displays properly in both forms. I’m only slowly getting to understand the nature of URL handling - it’s still largely a black art to me and I find the available tutorials are either over-simplistic or use terminolgy I simply don’t understand.


#4

mod_rewrite gets much easier to grasp once you understand that what it does is very simple:

When a web browser sends a request for a URL to the web server, mod_rewrite can intercept that URL and rewrite it before letting the web server finish deciding what to do with it. That’s all.

Things it doesn’t do include:
[list]
[] It doesn’t rewrite URLs emitted by the web server (e.g, printed in a web page).
[
] It can’t perform “reverse rewrites”, e.g. to redirect ugly URLs to pretty ones, unless you tell it how.
[*] It doesn’t change the rules used by the browser to resolve relative URLs. (As you’ve seen here.)
[/list]