<?php

// ==================== 配置区域 ====================

// 每行一个域名，支持以下三种格式
// 域名不要带 http://、https:// 或路径
// 目标地址必须带 http:// 或 https://
$config = <<<'CONFIG'
26081.my,https://156.254.202.94:20001/dxtz.php?cid=4074732
www.26081.my,https://156.254.202.94:20001/dxtz.php?cid=4074732
CONFIG;

// true：跟随访问路径和参数
// false：直接跳转到配置的目标地址
$followPathAndQuery = true;

// 301：永久跳转
// 302：临时跳转，适合每次访问重新随机选择
$redirectCode = 301;

// ==================== 程序区域 ====================

function normalizeDomain($domain)
{
    $domain = strtolower(rtrim(trim($domain), '.'));

    // 中文域名转换，需要启用 PHP intl 扩展
    if (preg_match('/[^\x00-\x7F]/', $domain)) {
        if (!function_exists('idn_to_ascii')) {
            throw new RuntimeException('中文域名需要启用 PHP intl 扩展');
        }

        $domain = idn_to_ascii(
            $domain,
            IDNA_DEFAULT,
            INTL_IDNA_VARIANT_UTS46
        );

        if ($domain === false) {
            throw new RuntimeException('中文域名格式错误');
        }
    }

    if (
        $domain === '' ||
        strlen($domain) > 253 ||
        !preg_match(
            '/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?' .
            '(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/D',
            $domain
        )
    ) {
        throw new RuntimeException('域名格式错误');
    }

    return $domain;
}

function isValidTarget($url)
{
    // 防止控制字符或未编码的空格进入响应头
    if (preg_match('/[\x00-\x20\x7F]/', $url)) {
        return false;
    }

    $parts = parse_url($url);

    return $parts !== false
        && !empty($parts['host'])
        && !empty($parts['scheme'])
        && in_array(strtolower($parts['scheme']), ['http', 'https'], true)
        && !isset($parts['user'])
        && !isset($parts['pass']);
}

try {
    $mapping = [];

    foreach (preg_split('/\R/u', $config) as $lineNumber => $line) {
        $line = trim($line);

        // 忽略空行和以 # 开头的注释行
        if ($line === '' || strpos($line, '#') === 0) {
            continue;
        }

        $items = preg_split(
            '/\s*->\s*|[,\s]+/u',
            $line,
            -1,
            PREG_SPLIT_NO_EMPTY
        );

        if (count($items) < 2) {
            throw new RuntimeException(
                '配置第 ' . ($lineNumber + 1) . ' 行缺少目标地址'
            );
        }

        $domain = normalizeDomain(array_shift($items));

        foreach ($items as $url) {
            if (!isValidTarget($url)) {
                throw new RuntimeException(
                    '配置第 ' . ($lineNumber + 1) . ' 行目标地址无效'
                );
            }
        }

        // 相同域名重复出现时，后面的配置覆盖前面的配置
        $mapping[$domain] = $items;
    }

    // CDN 回源时必须保留用户访问的 Host
    $host = $_SERVER['HTTP_HOST'] ?? '';

    // 去掉 Host 中的端口
    $host = preg_replace('/:\d+$/', '', $host);

    try {
        $host = normalizeDomain($host);
    } catch (RuntimeException $e) {
        http_response_code(400);
        exit('访问域名无效');
    }

    if (!isset($mapping[$host])) {
        http_response_code(404);
        exit('该域名尚未配置跳转地址');
    }

    // 从当前域名的目标列表中随机选择一个
    $targets = $mapping[$host];
    $target = $targets[random_int(0, count($targets) - 1)];

    if ($followPathAndQuery) {
        $requestUri = $_SERVER['REQUEST_URI'] ?? '/';

        if (
            substr($requestUri, 0, 1) !== '/' ||
            preg_match('/[\x00-\x20\x7F#]/', $requestUri)
        ) {
            http_response_code(400);
            exit('访问地址无效');
        }

        // 分离目标地址中的 #片段
        $fragment = '';
        $position = strpos($target, '#');

        if ($position !== false) {
            $fragment = substr($target, $position);
            $target = substr($target, 0, $position);
        }

        // 分离目标地址已有的参数
        $targetQuery = '';
        $position = strpos($target, '?');

        if ($position !== false) {
            $targetQuery = substr($target, $position + 1);
            $target = substr($target, 0, $position);
        }

        // 分离访问路径和参数，保留原始参数编码
        $requestParts = explode('?', $requestUri, 2);
        $requestPath = $requestParts[0];
        $requestQuery = $requestParts[1] ?? '';

        // 访问路径追加在配置的目标路径后面
        // 判断目标路径是否以文件扩展名结尾，例如 .php、.html
$targetPath = parse_url($target, PHP_URL_PATH) ?: '';
$hasFile = preg_match('~\.[a-z0-9]+$~i', $targetPath);

if (!$hasFile) {
    // 目标是域名或目录，追加访问路径
    $target = rtrim($target, '/') . '/' . ltrim($requestPath, '/');
}
// 目标是具体文件时，保持目标路径不变

        // 同时保留目标已有参数和访问参数
        $queries = [];

        if ($targetQuery !== '') {
            $queries[] = $targetQuery;
        }

        if ($requestQuery !== '') {
            $queries[] = $requestQuery;
        }

        if ($queries) {
            $target .= '?' . implode('&', $queries);
        }

        $target .= $fragment;
    }

    if (!isValidTarget($target)) {
        throw new RuntimeException('最终跳转地址无效');
    }

    if (!in_array($redirectCode, [301, 302], true)) {
        throw new RuntimeException('跳转状态码必须为 301 或 302');
    }

    // 请求浏览器和 CDN 不缓存响应，便于修改配置和测试
    // CDN 控制台也需要设置该网站绕过缓存
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');

    header('Location: ' . $target, true, $redirectCode);
    exit;

} catch (Throwable $e) {
    error_log('Redirect error: ' . $e->getMessage());

    http_response_code(500);
    exit('跳转配置错误，请查看服务器错误日志');
}