HTACCESS / PHP - 重定向到不同的URL时重写URL

时间:2012-02-04 19:35:44

标签: php .htaccess

我正在创建一个推荐方案的网站,推荐网址将类似于http://example.com/123456

我想将网址显示为http://example.com/,但仍会抓取123456并提供引荐点。

是否可以使用.htaccess mod_rewrite执行此操作?

之类的东西
RewriteRule ^([0-9]+) ?ref=$1 [L]

会转发网址,但是有没有办法在这里重定向并在地址栏中显示http://example.com/,而没有引荐代码?

显然可以使用PHP Headers,但如果可能的话,我宁愿不使用它。

1 个答案:

答案 0 :(得分:4)

由于HTTP是无状态协议,因此只能使用RewriteModule以简单方式实现这一点。如果您删除推介ID并重定向用户,则您在第二次请求时不再知道该ID。

因此,您必须使用PHP将ID保存在cookie或会话中,然后使用Location标头重定向用户。

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.";
}
相关问题