如何从 url 获取变量并使用 php 进行 301 重定向?
How to get a variable from url and 301 redirect with php?
我想从 url 获取一个变量,然后 301 将访问者重定向到新域并将该变量包含在 php 中的新 url 中。
例如,访问者访问我的网站 http://example.com/?id=abc 在那个网站上我有一个 index.php 文件,上面有这种代码:
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.New-Website.com/?id=$_GET["id"]");
?>
我想将访问者 301 重定向到具有相同变量的新网站。
此代码给出错误 500。
我知道这可以在 .htaccess 中完成,但我需要在 php 中完成。
您不能在双引号字符串中使用双引号
所以修改$_GET["id"]
为
header("Location: http://www.New-Website.com/?id=$_GET[id]");
或
header("Location: http://www.New-Website.com/?id={$_GET['id']}");
第二行错误。双引号不会被转义。建议取出位置并使用连接。
更好的是,指定数据类型
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: New-Website.com/?id=".(int)$_GET["id"]);
如果您使用的是 apache,只需在旧域的根目录中添加一个 .htaccess
文件,内容如下:
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.New-Website.com/ [R=301,L]
并且对旧域的所有请求都将重定向到新域
查看示例 here
<?php
header("Status: 301 Moved Permanently");
header("Location:http://www.New-Website.com/?". $_SERVER['QUERY_STRING']);
exit;?>
我想从 url 获取一个变量,然后 301 将访问者重定向到新域并将该变量包含在 php 中的新 url 中。
例如,访问者访问我的网站 http://example.com/?id=abc 在那个网站上我有一个 index.php 文件,上面有这种代码:
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.New-Website.com/?id=$_GET["id"]");
?>
我想将访问者 301 重定向到具有相同变量的新网站。
此代码给出错误 500。
我知道这可以在 .htaccess 中完成,但我需要在 php 中完成。
您不能在双引号字符串中使用双引号
所以修改$_GET["id"]
为
header("Location: http://www.New-Website.com/?id=$_GET[id]");
或
header("Location: http://www.New-Website.com/?id={$_GET['id']}");
第二行错误。双引号不会被转义。建议取出位置并使用连接。 更好的是,指定数据类型
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: New-Website.com/?id=".(int)$_GET["id"]);
如果您使用的是 apache,只需在旧域的根目录中添加一个 .htaccess
文件,内容如下:
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.New-Website.com/ [R=301,L]
并且对旧域的所有请求都将重定向到新域
查看示例 here
<?php
header("Status: 301 Moved Permanently");
header("Location:http://www.New-Website.com/?". $_SERVER['QUERY_STRING']);
exit;?>