Skip to content

Commit 2725439

Browse files
Copilothuangyiirene
andcommitted
fix: handle edge cases in path construction
- Handle root path (/) specially to avoid double slashes - Use precise regex for locale prefix removal - Ensure clean URLs: /cn instead of /cn/ - Improve path normalization logic Co-authored-by: huangyiirene <7665279+huangyiirene@users.noreply.github.com>
1 parent d0b6127 commit 2725439

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

apps/docs/middleware.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,8 @@ export default function middleware(request: NextRequest) {
101101
// If it's the default locale and hideLocale is 'default-locale', redirect to remove locale prefix
102102
if (locale === i18n.defaultLanguage && i18n.hideLocale === 'default-locale') {
103103
const url = new URL(request.url);
104-
url.pathname = pathname.replace(`/${i18n.defaultLanguage}`, '') || '/';
104+
// Remove locale prefix more precisely to avoid issues with partial matches
105+
url.pathname = pathname.replace(new RegExp(`^/${i18n.defaultLanguage}(/|$)`), '$1') || '/';
105106
const response = NextResponse.redirect(url);
106107
setLocaleCookie(response, locale);
107108
return response;
@@ -116,13 +117,15 @@ export default function middleware(request: NextRequest) {
116117
// If preferred language is the default, rewrite internally (keep URL clean)
117118
if (preferredLanguage === i18n.defaultLanguage && i18n.hideLocale === 'default-locale') {
118119
const url = new URL(request.url);
119-
url.pathname = `/${i18n.defaultLanguage}${pathname}`;
120+
// Handle root path specially to avoid double slashes
121+
url.pathname = pathname === '/' ? `/${i18n.defaultLanguage}` : `/${i18n.defaultLanguage}${pathname}`;
120122
return NextResponse.rewrite(url);
121123
}
122124

123125
// For non-default languages, redirect to the localized path
124126
const url = new URL(request.url);
125-
url.pathname = `/${preferredLanguage}${pathname}`;
127+
// Handle root path specially to avoid double slashes
128+
url.pathname = pathname === '/' ? `/${preferredLanguage}` : `/${preferredLanguage}${pathname}`;
126129
const response = NextResponse.redirect(url);
127130
setLocaleCookie(response, preferredLanguage);
128131
return response;

0 commit comments

Comments
 (0)