简体   繁体   English

HTACCESS / PHP-在重定向到其他URL的同时重写URL

[英]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 我正在创建带有引荐方案的网站,引荐网址应为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. 我想将URL显示为简单的http://example.com/但仍捕获123456并提供引荐点。

Would it be possible to do this with .htaccess mod_rewrite? .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? 可以转发URL,但是有没有办法在这里重定向并在地址栏中显示http://example.com/ ,而没有引用代码?

It would obviously be possible with PHP Headers but I'd prefer not to use this if at all possible. PHP标头显然有可能,但是我不希望尽可能不要使用它。

This is not possible in a simple way with RewriteModule only, because of HTTP being a stateless protocol. 由于HTTP是无状态协议,因此仅使用RewriteModule不可能以简单的方式实现。 If you remove the referral ID and redirect the user, then you won't know the ID anymore on the second request. 如果删除引荐ID并重定向用户,则在第二个请求中您将不再知道该ID。

So you have to save the ID in a cookie or session with PHP, and redirect the user with the Location header afterwards. 因此,您必须将ID保存在cookie或PHP会话中,然后再使用Location标头重定向用户。

htaccess htaccess

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

index.php 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.";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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