功能说明
访问 1.123.com → 自动跳转到 1.123.com:8081
访问 2.123.com → 自动跳转到 2.123.com:8082
访问 3.123.com → 自动跳转到 2.123.com:8083
其他域名访问 → 不跳转(可自定义提示)
代码轻量无依赖,支持 HTTPS/HTTP 自动识别、保留 URL 路径参数(如 1.123.com/test?id=1 → 1.123.com:8081/test?id=1),放在服务端可用于FRP内网穿透家里不同设备输入网址时省略端口号,懒人必备利器!
完整 index.php 代码
<?php
// ===================== 配置区(可自行修改)=====================
// 域名 => 对应要跳转的端口号
$domainPortMap = [
'1.123.com' => '8081',
'2.123.com' => '8082',
'3.123.com' => '8083',
];
// ===================== 核心跳转逻辑 =====================
// 获取当前访问的域名(不带端口)
$currentDomain = $_SERVER['HTTP_HOST'];
// 检查当前域名是否在配置列表中
if (array_key_exists($currentDomain, $domainPortMap)) {
// 获取对应端口
$targetPort = $domainPortMap[$currentDomain];
// 获取协议(http / https)
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
// 获取 URL 路径和参数(如 /test?id=1)
$requestUri = $_SERVER['REQUEST_URI'];
// 拼接最终跳转地址
$redirectUrl = $protocol . $currentDomain . ':' . $targetPort . $requestUri;
// 302 临时跳转(如需永久跳转改为 301)
header("Location: " . $redirectUrl, true, 302);
exit;
}
// ===================== 非指定域名访问 =====================
echo "当前域名未配置跳转规则";
exit;
?>
使用方法
把上面代码复制到 index.php 文件中
将文件上传到你的网站根目录
确保服务器已绑定 1.123.com、2.123.com、3.123.com 这三个域名。
自定义修改说明
修改端口号:直接改 $domainPortMap 数组里的端口值
新增域名:按格式添加 '4.123.com' => '8084'
永久跳转:把 302 改成 301(SEO 推荐)
禁止跳转提示:修改最后面的 echo 内容
如需增加未指定的域名跳转到指定url,如下修改:
<?php
$domainPortMap = [
'1.123.com' => '8081',
'2.123.com' => '8082',
'3.123.com' => '8083',
];
$otherJumpUrl = 'https://laitai.top';//自定义非指定跳转
$host = strtolower($_SERVER['HTTP_HOST']);
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443);
$proto = $isHttps ? 'https://' : 'http://';
$uri = $_SERVER['REQUEST_URI'];
if(isset($domainPortMap[$host])){
$url = $proto.$host.':'.$domainPortMap[$host].$uri;
header('Location:'.$url,true,302);
}else{
header('Location:'.$otherJumpUrl,true,302);
}
exit;
?>
修改说明
找到代码中的 $otherJumpUrl 字段自行改成你想要跳转的网址即可
保留原有三个域名带端口跳转功能
所有不在列表内的域名统一跳转到指定链接
依旧自动适配 http/https、保留原访问路径参数
