javascript - 用php编写客户端重定向服务器端

标签 javascript php .htaccess redirect

我正在寻找 PHP 中到另一个域的客户端重定向。

我不想进行 301 - 302 - 307 等重定向的原因是我希望页面向爬虫发送 200 HTTP OK 响应。

通常我使用混淆的 JavaScript 在静态网络主机(例如 S3)上执行此操作,但是,我知道爬虫程序可能会获取 JS,因为它是客户端。

我使用的非混淆 JS 代码示例;

window.location.href = "http://yourURL.com";

但是,爬虫获取 PHP 的难度要大得多,因此我想做一个类似的重定向,但是是在 PHP 中。

如果任何人都可以分享他或她对解决此问题的最佳方法的看法,那就太好了。

提前致谢!

最佳答案

PHP manual 中所述:

[...] The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.

所以,理论上,你可以这样做:

<?php
header('HTTP/1.1 201 Created'); // or as of PHP 5.4: http_response_code(201);
header('Location: http://yourURL.com/');

我现在无法测试它,并且我不确定这是否有效。

<小时/>

另一种可能性是“硬读”重定向地址的内容并将其显示在您的页面上:

<?php
$content = file_get_contents("http://yourURL.com/");
echo $content; // this will output the full HTML from the webpage.

注意:只有当您的 php.ini 中有 allow_url_fopen = On 指令或有权以编程方式设置它时,上面的代码才有效:

<?php
ini_set('allow_url_fopen', 'on');

这将提供 200 响应代码。

关于javascript - 用php编写客户端重定向服务器端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31686462/

相关文章:

javascript - 使用 Webpack 将 JSON 打包为纯 JSON 文件

php - 使用PHP发送Firebase通知

.htaccess - 为什么我的 .htaccess 将查询字符串附加到 URL?

regex - .htaccess HTTPS 重定向(一页除外) laravel

javascript - 使用 svg.js 移动导入的 svg

javascript - 原型(prototype)(Javascript): How do I observe multiple events for the same element?

javascript - 从中心到底部关闭物化模态

php - 如何从 RSS url 中获取完整内容?

javascript - 是否使用 php 或 javascript 方法来重定向页面

apache - 使用 htaccess 将图像目录重写到服务器中的另一个文件夹