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

Next.js配置:将所有流量重定向至/pre-registration页面

Next.js 页面访问控制与重定向配置方案

一、前端项目内配置(跨环境通用,推荐)

在项目根目录新建middleware.js(用TypeScript则建middleware.ts),通过Next.js的中间件拦截所有请求,实现访问控制:

import { NextResponse } from 'next/server';

export function middleware(request) {
  const allowedPath = '/pre-registration';
  const currentPath = request.nextUrl.pathname;

  // 访问根路径直接跳转到允许的页面
  if (currentPath === '/') {
    return NextResponse.redirect(new URL(allowedPath, request.url));
  }

  // 除了允许的页面,其他路径直接返回403禁止访问
  if (currentPath !== allowedPath) {
    return new NextResponse('访问被拒绝', { status: 403 });
    // 若不想返回403,也可以直接重定向到允许的页面:
    // return NextResponse.redirect(new URL(allowedPath, request.url));
  }

  // 允许访问的页面直接放行
  return NextResponse.next();
}

// 可选:指定中间件生效的路径,不写默认所有路径都生效
export const config = {
  matcher: ['/', '/contest', '/profile', '/auth', '/pre-registration'],
};

这个文件会在每个请求到达页面之前执行,一次配置就能全局控制所有页面的访问权限,本地开发和部署后行为一致,无需修改单个页面代码。

二、服务器端配置(无需修改前端代码)

如果不想改动前端项目,可以根据部署服务器的类型做对应配置:

1. Nginx 配置

修改Nginx的站点配置文件(通常在/etc/nginx/sites-available/目录下):

server {
  listen 80;
  server_name 你的域名.com;

  # 根路径重定向到/pre-registration
  location = / {
    return 302 /pre-registration;
  }

  # 只允许访问/pre-registration,其他路径返回403
  location / {
    if ($request_uri !~ ^/pre-registration($|/)) {
      return 403;
    }
    # 以下是原有的Next.js代理配置
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}

配置完成后重启Nginx即可生效。

2. Vercel 部署配置

在项目根目录新建vercel.json,配置重定向和路由规则:

{
  "redirects": [
    { "source": "/", "destination": "/pre-registration", "permanent": false }
  ],
  "rewrites": [
    {
      "source": "/(contest|profile|auth)(.*)",
      "destination": "/403"
    }
  ]
}

注意:需要先在项目中创建一个/403页面,用于展示访问被拒绝的提示内容。

总结

  • 优先选择前端中间件方案,不依赖服务器环境,维护更省心;
  • 服务器端配置适合不想改动前端代码的场景,但需根据不同部署平台调整配置逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:42:52