I am trying to rewrite the url of an application with parameters.
I have a link in the main file main.php
.
<a href="index?id=100&title=sub-url-here>Continue</a>
In the index.php
file, there is an image tag with the src pointing to ìmages/
folder.
<img src="images/fileaname.png" />
All this works just fine.
The problem occurs after writing the URL.
This is what I have in the .htaccess
file
RewriteEngine O RewriteRule ^index/([0-9]+)/([0-9a-zA-Z-_]+)/?$ index.php?id=$1&title=$2 [NC,L]
I now have in the index.php
file:
<a href="index/100/sub-url-here/">Continue</a>
However, the image path in the main.php
file is now pointing to
<img src="100/sub-url-here/images/fileaname.png" />
How can I rewrite the image path according to the written url in the .htaccess
?
Advertisement
Answer
The problem is you are using relative URLs to your images. The browser resolves these relative to the current URL in the browser’s address bar (unless you have a <base>
tag that states otherwise). So, when viewing the page URL /index/100/sub-url-here/
in the browser, the relative URL images/filename.png
naturally resolves to index/100/sub-url-here/images/filename.png
, not /images/filename.png
as you are perhaps expecting.
You need to use root-relative URLs (starting with a slash) that are relative to the document root, or absolute URLs (with scheme+hostname) to your images (and other static resources) – so the image URL is not relative to the page URL being displayed.
For example:
<!-- https://example.com/images/filename.png --> <img src="/images/filename.png">
See also, the following question on the Webmasters stack that goes into more detail regarding the use of relative URL-paths when URL-rewritting: