sdouble sdouble - 5 months ago 8
PHP Question

How do I stop mod_rewrite from appending links to url?

I expect the answer is going to be something so simple I'll want to cry, but I can't seem to figure it out. I'm new to mod_rewrite.

I wanted to change my links from things like domain.com/?p=about to domain.com/about*/* (with the trailing slash) and it works fine, but whenever I move on to a link, it appends the new link to the back of the url. For example, I have an about and a contact link. If I click about it navigates to domain.com/about/ then if I click contact, it navigates to domain.com/about/contact/ and will keep adding the links to the end of the url. If I'm at domain.com and click a link(about, in this case) it will go to domain.com/about/ and if I click about 4 more times, my address bar is going to say "domain.com/about/about/about/about/about/" I have reproduced this in a very simple example below, what am I doing wrong?

.htaccess

RewriteEngine On
RewriteRule ([a-zA-Z0-9]+)/$ index.php?p=$1


index.php

<a href="about/">about</a> | <a href="contact/">contact</a><br><br>

<?php
if(!isset($_GET['p'])) {
echo "home";
} else {
echo $_GET['p'];
}
?>


Thank you for your help!

edit:
It works okay if I use an absolute path, but I'd rather not if I don't absolutely have to.

edit2: adding

RewriteBase /


breaks the links. They appear to be going to domain.com/about/ and .../contact/, but I get a 404 - I'm assuming the rule I used is somehow incompatible with the way I'm doing my linking, which is why I included index.php as well.

Answer

You are defining all of your links in HTML relative to the current path.

You will need to change your links such that:

<a href="about/">about</a> | <a href="contact/">contact</a><br><br>

becomes (note the leading / on the urls):

<a href="/about/">about</a> | <a href="/contact/">contact</a><br><br>

When you are on a page site.com/about/us a link like <a href="home/" gets resolved by the browser to be site.com/about/us/home.

The solution is to change all of your links, images, stylesheets, and javascripts to use absolute paths in your URLs, not relative ones like you have now.

EDIT: Just noticed your edit. You really should use absolute paths, not relative ones. If you want to keep the relative URLs then you will have to use something like <base href="/" /> on all of your pages.

Comments