简体   繁体   中英

HTACCESS / PHP - Re-write URL while re-directing to a different URL

I am creating a website with a referral scheme, where the referral URL will be something like http://example.com/123456

I would like to display the URL as simply http://example.com/ but still capture the 123456 and give the referral point.

Would it be possible to do this with .htaccess mod_rewrite? something like

RewriteRule ^([0-9]+) ?ref=$1 [L]

would work to forward the URL, but is there a way to redirect here and display http://example.com/ in the address bar, without the referrer code?

It would obviously be possible with PHP Headers but I'd prefer not to use this if at all possible.

This is not possible in a simple way with RewriteModule only, because of HTTP being a stateless protocol. If you remove the referral ID and redirect the user, then you won't know the ID anymore on the second request.

So you have to save the ID in a cookie or session with PHP, and redirect the user with the Location header afterwards.

htaccess

RewriteRule ^([0-9]+) index.php?ref=$1 [L]

index.php

if (isset($_GET["ref"])) {
  setcookie("refid", $_GET["ref"]);
  header("Location: http://example.com/");
  exit;
}
if (isset($_COOKIE["refid"])) {
  echo "You came from ref id: $_COOKIE[refid]";
} else {
  echo "You came without a ref id.";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM