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

如何解决爬虫重定向问题?Google索引重定向错误处理

解决Next.js多语言站点SEO工具的「重定向错误」问题

问题核心

你的语言中间件存在无意义的自定向逻辑,搜索引擎爬虫(如Google URL Inspection工具)会严格校验重定向链,这类多余的跳转(路径正确却因cookie状态重定向)会被判定为「重定向错误」,而普通浏览器访问时因缓存或cookie处理逻辑不会显现问题。

问题代码分析

原中间件里的两处逻辑触发了不必要的重定向:

  • 访问正确的语言路径但无cookie时,会重定向到当前路径(自定向)
  • 路径语言与cookie语言不匹配时,直接重定向到当前路径(自定向)

修改后的中间件代码

import { NextResponse } from "next/server";
import { fallbackLng, languages } from "@/app/i18n/settings";

const cookieName = "i18next";

const languageMiddleware = (req) => {
  const cookieLng = req.cookies.get(cookieName)?.value;
  const pathLang = req.nextUrl.pathname.split("/")[1].toLowerCase().trim();
  const isDevelopment = process.env.NODE_ENV === 'development';
  const response = NextResponse.next(); // 默认返回正常响应,避免不必要重定向

  // 处理根路径重定向
  if (req.nextUrl.pathname === "/") {
    const browserLang = req.headers.get("accept-language")?.split(",")[0].split("-")[0];
    const targetLng = languages.includes(browserLang) ? browserLang : fallbackLng;
    // 根路径用302临时重定向(支持用户切换语言),如需永久重定向可改为301
    return NextResponse.redirect(new URL(`/${targetLng}`, req.url), { status: 302 });
  }

  // 处理无效语言路径重定向
  if (!languages.includes(pathLang)) {
    return NextResponse.redirect(new URL(`/${fallbackLng}${req.nextUrl.pathname}`, req.url), { status: 302 });
  }

  // 更新cookie:仅在需要时设置,不触发重定向
  if (cookieLng !== pathLang) {
    response.cookies.set(cookieName, pathLang, {
      sameSite: 'Lax',
      secure: !isDevelopment,
      path: '/'
    });
  }

  return response;
};

export default languageMiddleware;

关键修改说明

  1. 移除自定向逻辑:不再因cookie状态(无cookie/不匹配)触发重定向,仅在路径无效或根路径时跳转,减少重定向链长度
  2. 统一响应对象:默认返回NextResponse.next(),仅在必要时返回重定向响应
  3. 优化无效路径处理:将无效语言路径重定向到对应默认语言的同路径(而非仅根路径),提升用户体验
  4. 明确重定向状态码:根路径和无效路径重定向使用302(临时),符合多语言站点的用户切换场景

额外SEO优化建议

  • 在根路径的app/page.jsx中添加交替语言链接,帮助搜索引擎识别多语言版本:
    export default function RootPage() {
      return (
        <>
          <link rel="alternate" hrefLang="en" href="https://yourdomain.com/en" />
          <link rel="alternate" hrefLang="de" href="https://yourdomain.com/de" />
          <link rel="alternate" hrefLang="x-default" href="https://yourdomain.com/en" />
        </>
      );
    }
    
  • 在robots.txt中允许抓取所有语言路径:
    User-agent: *
    Allow: /en/
    Allow: /de/
    
  • 在Google Search Console中分别提交各语言版本的站点地图

内容的提问来源于stack exchange,提问作者Gündoğdu Yakıcı

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:42:11