How to use apache mod_rewrite rewriterule without changing relative paths

I have the following rewrite rule in .htaccess:

RewriteRule ^groups/([^/\.]+)/?$ groupdetail.php?gname=$1 [L,NC] 

Will it take something like www.example.com/groups/groupname and call www.example / groupdetail.php? gname = groupname. And it works great.

But all relative links to groupdetail.php use groups / as a relative path, and I don't want them. How can I avoid this?

For example, when a user clicks the <a href="link.php"> link to groupdetail.php? gname = groupname, it goes to www.example / groups / link.php. I want to take the user to www.example.com/link.php.

Obviously, I want the user url to look like "www.example.com/groups/groupname", so I don't want to use [R] / redirect.

+4
source share
6 answers

If I had hundreds of relative links on the page, insert <base href=""> in the <head> with an absolute path (you can also use a relative). You will also need to make the path to the .js files in <head> absolute, because IE and firefox deal with the underlying href differently. I agree that this is an annoying problem.

+5
source

Relative links are resolved by the browser, not the server, so you can do nothing with mod_rewrite.

Either use relative links up the hierarchy ( ../link.php ), or use absolute links.

+3
source

If you do not want to have absolute links or use <base> because you are going to move the page around, you can create a php base, as shown below:

 echo '<base href="http://'.$_SERVER['SERVER_NAME'].str_replace("index.php","",$_SERVER['PHP_SELF']).'" />'; 
+2
source

If you change the rewrite rule, force the redirection (add the [R] option), then the browser will use /groupdetail.php and the relative links will work fine. However, this adds one redirect and makes the URL less attractive.

 RewriteRule ^groups/([^/.]+)/?$ groupdetail.php?gname=$1 [L,NC,R] 
+1
source

You can use the BASE tag if you do not want to use absolute paths:

http://www.w3schools.com/tags/tag_base.asp

+1
source

The answer to the hop is correct. The browser sees www.example.com/groups/groupname as an address, so it considers /groups to be the current directory. Thus, it is assumed that any links like <a href=link.php> are in the /groups folder.

When the user moves the mouse over the link, he will see www.example.com/groups/link.php as the address of the link.

The solution is to use absolute links - just add a slash before href:

<a href=/link.php>

Then the user will see www.example.com/link.php as a URL.

However, it seems from your question that you are using relative links for the purpose ... do you have a reason not to use absolute links?

0
source

Source: https://habr.com/ru/post/1277259/


All Articles