OBS: text translated with the help of AI
I am trying to use a middleware in Next.js to rewrite the URL for a subdomain (like dividas.dominio.com) to /dividas. The behavior works correctly in the development environment, but when I deploy to production, the rewrite does not happen and the page doesn't load as expected.
Here is the code for my middleware:
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.get('access_token') || '';
const host = request.headers.get('host') || '';
if (host.startsWith('dividas') && request.nextUrl.pathname === '/') {
const url = new URL('/dividas', request.url);
return NextResponse.rewrite(url);
}
if (request.nextUrl.pathname.startsWith('/auth')) {
if (token) {
return NextResponse.redirect(new URL('/admin/posts', request.url));
}
}
if (request.nextUrl.pathname.startsWith('/admin')) {
if (!token) {
const loginUrl = new URL('/auth/login', request.url);
return NextResponse.redirect(loginUrl);
}
}
return NextResponse.next();
}
export const config = {
matcher: ['/auth/:path*', '/admin/:path*', '/:path*', '/']
};
What is happening: In production, when I access https://dividas.dominio.com.br/, the page does not load, and nothing is displayed. I expected the URL to be rewritten to https://dividas.dominio.com.br/dividas, but this does not happen.
In development, everything works perfectly. Because i change dividas to local and accessed with localhost:3000 And i dont have nothin in / And load my page /dividas
DNS and subdomain configurations are correct because when I access https://dividas.dominio.com.br/dividas, the page loads correctly.
Also, https://dominio.com.br/dividas works fine (without the subdomain).
ERROR: 404 This page could not be found.
What I expect: I do not want to be redirected to https://dividas.dominio.com.br/dividas when I visit https://dividas.dominio.com.br/.
I want the page at /dividas to load on the screen, but the URL should remain the same (https://dividas.dominio.com.br/).
However, this does not work in production.
What I have tried so far: I checked the DNS settings, and they are correct.
I configured the middleware to rewrite the path to /dividas when the host starts with dividas.