【发布时间】:2021-06-03 12:32:11
【问题描述】:
我正在尝试检测移动设备并将它们发送到我服务器上的不同目录。该网站的桌面版是一个WordPress网站;移动版本是 HTML。目前,移动网站只有在我刷新页面时才会加载。第一次加载似乎来自浏览器缓存,但即使我清除了浏览器缓存,此问题仍然存在。
我正在使用这个 Mobile-detect library 移动检测库来检测请求页面的设备是否是移动的,并使用 PHP header(Location: ...) 重定向访问者。
在我的服务器的根目录中,我有:
// website structure for mywebsite.com
/public_html
/lib
/mobile-detect.php // the mobile detect 3rd-party library
/m // the mobile website version
/index.html
/index.html.bak.bak
/wp-admin
/wp-content
/themes/
my-child-theme/
/wp-includes
etc...
在我的子主题的 header.php 文件中,我尝试了以下方法:
<?PHP
// at the top of the page
require_once 'lib/mobile_detect.php';
$detect = new Mobile_Detect;
if ( $detect->isMobile() ) {
header('Location: https://mywebsite.com/m/');
exit;
}
?>
我尝试使用更多与缓存相关的指令来扩展它:
<?PHP
// at the top of the page
header("Cache-Control: max-age=0, no-cache, no-store, must-revalidate"); //from amclin
require_once 'lib/mobile_detect.php';
$detect = new Mobile_Detect;
if ( $detect->isMobile() ) {
header('Location: https://mywebsite.com/m/');
exit;
}
?>
我尝试在PHP 代码之后的文档的<head> 中添加元标记:
<meta http-equiv=“Expires” content=”-1″>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
除了其他所有功能之外,我还尝试使用 Javascript:
<script type="text/javascript">
if (screen.width <= 699) {
document.location = "https://mywebsite.com/m/";
}
</script>
第 3 方 mobile-detect 库的原始示例在这里推荐使用 Cookie,但我不得不承认,我不明白它的逻辑。我最初尝试过,但遇到了同样的问题:
<?php
@include('lib/mobile_detect.php');
$detect = new Mobile_Detect();
if ($detect->isMobile() && isset($_COOKIE['mobile'])) {
$detect = false;
}
elseif ($detect->isMobile()) {
header('Location:https://mywebsite.com/m/');
}
?>
public_html/m/ 内的 index.html 页面包含以下内容:
<?php
setcookie('mobile','m',time()+3600,'/','mywebsite.com/');
echo @file_get_contents('index.html.bak.bak');
我也尝试向这个文件添加缓存指令:
我也尝试使用wp_redirect 代替header():
<?PHP
// at the top of the page
require_once 'lib/mobile_detect.php';
$detect = new Mobile_Detect;
if ( $detect->isMobile() ) {
wp_redirect('Location: https://mywebsite.com/m/');
exit;
}
?>
WP 站点使用 Clearfy 缓存插件。我已经一次又一次地清除了缓存。
所以我显然在错误的级别上工作,我很好奇这里发生了什么。
为什么浏览器先获取桌面版,然后刷新页面后,再去服务器获取新的header.php文件?这段代码是不是放错地方了?它应该在其他地方的索引文件中吗?我需要为此使用 cookie 吗?啊啊啊!
感谢您对此的帮助!
【问题讨论】:
标签: php wordpress redirect caching browser-cache