HTACCESS / PHP - Re-write URL while re-directing t

2019-08-30 23:35发布

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.

标签: php .htaccess
1条回答
时光不老,我们不散
2楼-- · 2019-08-30 23:53

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.";
}
查看更多
登录 后发表回答