如何使用JavaScript、jQuery或PHP修改URL路径并实现页面重定向
URL路径修改与重定向实现方案
纯JavaScript实现
直接操作浏览器原生window.location对象即可实现,逻辑会自动保留原URL的查询参数、锚点信息,不会误修改域名部分:
// 切换到带/en/前缀的英文路径 document.querySelector('#switchToEn').addEventListener('click', () => { const { origin, pathname, search, hash } = window.location // 避免重复添加前缀 if (!pathname.startsWith('/en/')) { const newUrl = `${origin}/en${pathname}${search}${hash}` window.location.replace(newUrl) } }) // 切换回无/en/前缀的默认路径 document.querySelector('#switchToDefault').addEventListener('click', () => { const { origin, pathname, search, hash } = window.location if (pathname.startsWith('/en/')) { // 切除前4位字符 /en/ const newPath = pathname.slice(4) const newUrl = `${origin}/${newPath}${search}${hash}` window.location.replace(newUrl) } })
用replace方法跳转不会在浏览器历史记录中留存当前页记录,用户点击后退按钮不会跳转到跳转前的页面,符合路径切换的常规需求。
jQuery实现
核心逻辑和纯JS一致,仅事件绑定方式替换为jQuery的语法:
// 切换到英文路径 $('#switchToEn').click(function() { const { origin, pathname, search, hash } = window.location if (!pathname.startsWith('/en/')) { const newUrl = `${origin}/en${pathname}${search}${hash}` window.location.replace(newUrl) } }) // 切换回默认路径 $('#switchToDefault').click(function() { const { origin, pathname, search, hash } = window.location if (pathname.startsWith('/en/')) { const newPath = pathname.slice(4) const newUrl = `${origin}/${newPath}${search}${hash}` window.location.replace(newUrl) } })
PHP实现
PHP为服务端重定向方案,适合服务端判断自动跳转、无需前端点击触发的场景:
$currentUri = $_SERVER['REQUEST_URI']; $host = $_SERVER['HTTP_HOST']; // 适配PHP8以下版本无str_starts_with的情况 $hasEnPrefix = substr($currentUri, 0, 4) === '/en/'; // 切换到/en前缀路径 if (!$hasEnPrefix) { $newUrl = "https://{$host}/en{$currentUri}"; header("Location: {$newUrl}", true, 302); // 302为临时重定向,永久切换可改为301 exit(); } // 切换回默认路径 if ($hasEnPrefix) { $newUri = substr($currentUri, 4); $newUrl = "https://{$host}/{$newUri}"; header("Location: {$newUrl}", true, 302); exit(); }
如果需要通过按钮触发PHP跳转,可点击后跳转到PHP处理页执行上述逻辑,再重定向到目标地址即可。
内容的提问来源于stack exchange,提问作者R4E Group
相关产品推荐
相关产品推荐

