Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

php - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...