问题
I've the following rewrite rule in .htaccess:
RewriteRule ^groups/([^/\.]+)/?$ groupdetail.php?gname=$1 [L,NC]
This takes something like www.example.com/groups/groupname and calls www.example/groupdetail.php?gname=groupname. And it works just fine.
But all the relative links on groupdetail.php use groups/ as the relative path, and I don't want them to. How do I avoid this?
For example, when a user clicks on a link <a href="link.php">
on groupdetail.php?gname=groupname, he's taken to www.example/groups/link.php. I want to take the user to www.example.com/link.php.
Obviously, I want to URL to the user to look like "www.example.com/groups/groupname" so I don't want to use [R]/redirect.
回答1:
If like me you had hundreds of relative links in the page, insert a <base href="">
in the <head>
with an absolute path (could use relative too). You'll need to also make the path to .js files in the <head>
absolute because IE and firefox deal with the base href differently. I agree it is an annoying issue.
回答2:
Relative links are resolved by the browser, not the server, so there is nothing you can do with mod_rewrite.
Either use relative links the go up the hierarchy (../link.php
) or use absolute links.
回答3:
If you do not want to have absolute links or use <base>
because you are going to move the page around, you can have the base be generated by php, as following:
echo '<base href="http://'.$_SERVER['SERVER_NAME'].str_replace("index.php","",$_SERVER['PHP_SELF']).'" />';
回答4:
If you change the rewite rule to do a force redirect (add the [R] option), then the browser will be using the /groupdetail.php URL and the relative links will work fine. However, that adds one redirect and makes the URLs less pretty.
RewriteRule ^groups/([^/.]+)/?$ groupdetail.php?gname=$1 [L,NC,R]
回答5:
You can use the BASE tag, if you don't want to use absolute paths:
http://www.w3schools.com/tags/tag_base.asp
回答6:
Hop's answer is correct. The browser sees www.example.com/groups/groupname
as the address, so considers that /groups
is the current directory. So, any links like <a href=link.php>
are assumed to be in the /groups
folder.
When the user moves his mouse over the link, he'll see www.example.com/groups/link.php
as the link address.
The solution is to use absolute links -- just add a slash before the href:
<a href=/link.php>
The user will then see www.example.com/link.php
as the url.
That said, it seems from your question that you are using relative links on purpose... do you have a reason not to use absolute links?
来源:https://stackoverflow.com/questions/144651/how-to-use-apaches-mod-rewrite-rewriterule-without-changing-relative-paths