You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript/React重定向时添加重复斜杠的问题要如何解决?

重定向URL双斜杠问题修复方案

1. Nginx 配置场景修复

  • 不要硬拼接域名末尾斜杠与路径,错误写法示例:return 301 $scheme://$host/$request_uri;,$host后多余的斜杠和自带开头斜杠的$request_uri拼接会产生双斜杠。
  • 正确写法删除多余斜杠:return 301 $scheme://$host$request_uri;
  • 全局开启斜杠自动合并(默认开启,若被手动关闭可重新打开):
merge_slashes on;

2. Apache .htaccess 配置场景修复

  • 错误写法示例:Redirect 301 / https://www.mydomain.or/,目标地址末尾斜杠和后续拼接的子路径开头斜杠会重复。
  • 正确写法删除目标地址末尾斜杠:Redirect 301 / https://www.mydomain.or
  • 可添加重写规则主动合并连续斜杠:
RewriteEngine On
RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]

3. 服务端代码重定向场景修复

  • 不要同时保留域名末尾斜杠和路径开头斜杠,错误写法示例(Node.js):
// 错误写法
const domain = 'https://www.mydomain.or/';
const path = '/images/logo.gif';
res.redirect(301, domain + path);
  • 用标准URL构造方法自动处理斜杠冲突:
// 正确写法
const redirectUrl = new URL('/images/logo.gif', 'https://www.mydomain.or/');
res.redirect(301, redirectUrl.href);
  • PHP场景可手动 trim 多余斜杠后拼接:
$domain = rtrim('https://www.mydomain.or/', '/');
$path = ltrim('/images/logo.gif', '/');
$redirectUrl = $domain . '/' . $path;

4. 前端JS重定向场景修复

  • 避免硬拼接地址,用URL构造函数自动处理:
const redirectUrl = new URL('/images/logo.gif', 'https://www.mydomain.or/');
window.location.href = redirectUrl.href;

内容的提问来源于stack exchange,提问作者RandomDeveloper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:06:01