最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to redirect pagesapp folder to subdomain in next.js - Stack Overflow

programmeradmin1浏览0评论

I search a lot for this on the internet but I don't find any article related to it.

Like I have a folder called pages in the root of my project and below tree is files of it.

|   404.js
|   auth.js
|   index.js
|   _app.js
|   _error.js
\---app
        index.js

next.js gives default behavior when someone opens project.local:3000 it will openindex.js and project.local:3000/app it will open app/index.js but I want that when someone open app.project.local:3000 it will open app/index.js.

My Hosts file

127.0.0.1 project.local
127.0.0.1 app.project.local

In short

I want to redirect pages/app folder to app.project.local or app.example in next.js

I search a lot for this on the internet but I don't find any article related to it.

Like I have a folder called pages in the root of my project and below tree is files of it.

|   404.js
|   auth.js
|   index.js
|   _app.js
|   _error.js
\---app
        index.js

next.js gives default behavior when someone opens project.local:3000 it will openindex.js and project.local:3000/app it will open app/index.js but I want that when someone open app.project.local:3000 it will open app/index.js.

My Hosts file

127.0.0.1 project.local
127.0.0.1 app.project.local

In short

I want to redirect pages/app folder to app.project.local or app.example. in next.js

Share Improve this question asked May 12, 2020 at 20:54 Nisharg ShahNisharg Shah 19.8k12 gold badges68 silver badges77 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 1

Most updated solution

I found the solution while exploring the documentation on redirects.

In your Next.js's root folder, create a vercel.json file and then insert your redirects as object inside redirects array like so:

{
  "redirects": [
    { "source": "/blog", "destination": "https://blog.example." }
  ]
}

This will only work on production environment. It should work as intended.

I'm still a noobie in next.js (2nd day learning), but I was searching for subdomain support and I found three solutions on this Github issue: https://github./vercel/next.js/issues/5682

  1. Using zones (still no idea how it works)
  2. "Vercel will implement subdomain routing in the near future" (I don't expect to use Vercel in the near future)
  3. (my preferred, but not yet tested) An example using custom servers in Next.js: https://github./dcangulo/nextjs-subdomain-example For #3, see how it was implemented in the server.js file

With the new "middleware" feature of Next.js, you can rewrite it using a function instead of the rewrite object and keep the getStaticProps working.

// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getValidSubdomain } from '@/utils/subdomain';

// RegExp for public files
const PUBLIC_FILE = /\.(.*)$/; // Files

export async function middleware(req: NextRequest) {
  // Clone the URL
  const url = req.nextUrl.clone();

  // Skip public files
  if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes('_next')) return;

  const host = req.headers.get('host');
  const subdomain = getValidSubdomain(host);
  if (subdomain) {
    // Subdomain available, rewriting
    console.log(`>>> Rewriting: ${url.pathname} to /${subdomain}${url.pathname}`);
    url.pathname = `/${subdomain}${url.pathname}`;
  }

  return NextResponse.rewrite(url);
}

You can take a look on nextjs docs about middleware and I've also wrote this medium article with some related content that might help.

this worked for me in next js v14.3.2
// pages/_middleware.ts
import { NextResponse } from 'next/server';

export function middleware(req: any) {
    const url = req.nextUrl.clone();
    const hostname = req.headers.get('host');
    const subdomain = hostname.split('.')[0];

    if (subdomain === 'localhost:6061') {
        return NextResponse.next();
    }
    if (url.pathname.startsWith('/font') ||
        url.pathname.startsWith('/icon') ||
        url.pathname.startsWith('/images') ||
        url.pathname.startsWith('/logo') ||
        url.pathname === '/robots.txt' ||
        url.pathname === '/sitemap.xml' ||
        url.pathname === '/sitemap-0.xml'
    ) {
        return NextResponse.next();
    }

    // Allow shared resources to be served from the main domain
    const sharedResources = ['/favicon.ico', '/globals.css', '/_next', '/static'];
    if (sharedResources.some(path => url.pathname.startsWith(path))) {
        return NextResponse.next();
    }

    console.log(subdomain);
    if (subdomain === 'lms') {
        console.log('here');
        url.pathname = `/lms${url.pathname}`;
        return NextResponse.rewrite(url);
    }

    return NextResponse.next();
}

NextJS now supports Locales: https://nextjs/docs/advanced-features/i18n-routing.

You can specify a locale in your config, e.g. admin and specify the URL like this:

// next.config.js
module.exports = {
  i18n: {
    // These are all the locales you want to support in
    // your application
    locales: ['en-US', 'admin', 'nl-NL'],
    // This is the default locale you want to be used when visiting
    // a non-locale prefixed path e.g. `/hello`
    defaultLocale: 'en-US',
    // This is a list of locale domains and the default locale they
    // should handle (these are only required when setting up domain routing)
    // Note: subdomains must be included in the domain value to be matched e.g. "fr.example.".
    domains: [
      {
        domain: 'example.',
        defaultLocale: 'en-US',
      },
      {
        domain: 'example.nl',
        defaultLocale: 'nl-NL',
      },
      {
        domain: 'admin.example.',
        defaultLocale: 'admin',
        // an optional http field can also be used to test
        // locale domains locally with http instead of https
        http: true,
      },
    ],
  },
}
发布评论

评论列表(0)

  1. 暂无评论