I have a php file that loads an article from a db based on the given variables. There is also an .htacces file in the root of the site. I used this in the htaccess to redirect
RewriteRule ^articles/([a-zA-Z0-9-_\s]+).html$ template/index.php?action=viewarticle&alias=$1
after redirecting, the page shows fine but the html in the page goes wrong, for example:
media/2011/02/21/logos.jpg
turns in to articles/media/2011/02/21/logos.jpg
This happens because the htacces is redirecting. Is there anyway to do this redirect while keeping the root dir unchanged?
This happens coz the htacces is redirecting.
No, this happens because the browser thinks that
example.com/articles/my_article.html
is a resource in the /articles
sub-directory, and treats all relative URLs as relative to /articles
.
There is no way to change that behaviour.
You will need to start using absolute image references, or relative image references that consider the additional directory:
<img src="/media/2011/02/21/logos.jpg"> <------ recommended
<img src="../media/2011/02/21/logos.jpg">
you could also use <base>
as suggested by @Boris but absolute paths (or full URLs) are a vastly cleaner solution to the problem in my opinion.
First, what do you mean by "html in the pages goes wrong":
.htaccess don't change anything in your code.
There is an html element which allow you to define base url used everywhere in your page.
<base href="/root" />
if you have for example <a href="/articles/12">Article 12</a>
then when clicking on the link, you will redirect to /root/articles/12
Also, mixing Pekka's answer with Boris', you should define somewhere in your application which is the root path of your application and output all paths as absolute, prepending the base dir you defined earlier.
for example: in config.inc.php
define("ROOT_URI", "http://myserver.com/myapp");
everywhere:
<img src="<?php echo ROOT_URI;?>/media/2011/02/21/logos.jpg
This is like using the base
element as Boris suggested, without using it (I also dislike base
), and makes your application able to work in whatever folder under the webserver it is stored.