2009年5月22日 星期五

Mod_Rewrite 後造成 圖片, css , javascript 連結錯誤[解決方案]

連結

The relative paths are broken because they are relative to the URL in the browser's address bar. For example, if you had a URL of /index.php?page=abc and a relative URL of images/image-one.jpg, the browser would look for the file at /images/image-one.jpg. However, if you use mod_rewrite to change the URL to /pages/abc.html, the browser will now look for the image at /pages/images/image-one.jpg and it won't find it.

To stop this you have a few options:

1. Don't use /. If you don't use slashes (eg. /page-abc.html), the path will be at the same depth and relative URLs won't break.

2. Use absolute paths (everything after the domain name), eg.
Code:
<img src="/images/image-one.jpg" alt="An image of a one">

You would need to edit all the links in your pages.

If you want to be able to move your script and are using a server-side language, you can use a variable or constant so you will only have to change one line. For example in PHP, you would place a constant definition in you global include/configuration file, like this:
Code:
define('MOD_REWRITE_BASE_PATH', '/');

And use it in when outputting your the links
Code:
<a href="<?php echo MOD_REWRITE_BASE_PATH; ?>images/image-one.jpg">foo</a>

If you move the files, you only have to change the value of MOD_REWRITE_BASE_PATH and all the paths will change.

3. There is also a possibility of a mod_reite "hack" to get it to work. In this case, it would be
Code:
RewriteRule ^.+(/images/.+)$ $1 [L]

4. Add a <base>, eg.
Code:
<base href="http://www.domain.com/">



Edit: Added <base>.

【下列文章您可能也有興趣】

沒有留言: