<?php
// 获取当前域名
$host = preg_replace('/:\d+$/', '', $_SERVER['HTTP_HOST']);
$requestUri = $_SERVER['REQUEST_URI'];

// 如果已经是 www 开头，不做处理
if (strpos($host, 'www.') === 0) {
    // 已经是 www，正常访问
} else {
    // 提取主域名（去掉所有二级前缀）
    // 例如：ssss.aaaaa.com → aaaaa.com
    //      aaa.bbb.ccc.com → ccc.com（只保留最后两段）
    
    $parts = explode('.', $host);
    $count = count($parts);
    
    // 取最后两段作为主域名
    if ($count >= 2) {
        $mainDomain = $parts[$count - 2] . '.' . $parts[$count - 1];
    } else {
        $mainDomain = $host; // 异常情况
    }
    
    // 自动识别协议
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
    
    // 构造跳转 URL
    $redirectUrl = $protocol . 'www.' . $mainDomain . $requestUri;
    
    // 301 跳转
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $redirectUrl);
    exit();
}
include __DIR__ . '/pz.php';
include __DIR__ . '/userads.php'; 
error_reporting(E_ERROR);
include 'testyuming/class.php';
$cachefile = 'cache-index/index.html';
$cache_time = 86400; // 缓存1小时（3600秒）

ob_start();

// 检查缓存文件是否存在且未过期
if(file_exists($cachefile)){
    // 判断缓存是否在有效期内
    if((time() - filemtime($cachefile)) < $cache_time){
        include($cachefile);
        ob_end_flush();
        exit;
    }
    // 如果缓存过期，删除旧缓存文件
    @unlink($cachefile);
}

if ($huangchu){
    echo $moban;

    if(is_dir('cache-index')){
        $info = ob_get_contents();
        file_put_contents($cachefile, $info, LOCK_EX); // 加文件锁防止并发
    } else {
        if(@mkdir('cache-index', 0755, true)){
            $info = ob_get_contents();
            file_put_contents($cachefile, $info, LOCK_EX);
        }
    }
    exit;
} else {
    // 如果不需要缓存404页面，可以清理输出缓冲
    ob_end_clean();
    
    header("HTTP/1.0 404 Not Found");
    // 然后输出内容
    echo "很抱歉，您请求的页面不存在。";
    exit;
    /* include '404.php'; */
}
?>
