11import type { Connect } from 'dep-types/connect'
22import type { ViteDevServer } from '..'
3- import { joinUrlSegments } from '../../utils'
3+ import { joinUrlSegments , stripBase } from '../../utils'
44
5- // this middleware is only active when (config. base !== '/')
5+ // this middleware is only active when (base !== '/')
66
77export function baseMiddleware ( {
88 config
99} : ViteDevServer ) : Connect . NextHandleFunction {
10- const devBase = config . base . endsWith ( '/' ) ? config . base : config . base + '/'
11-
1210 // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
1311 return function viteBaseMiddleware ( req , res , next ) {
1412 const url = req . url !
1513 const parsed = new URL ( url , 'http://vitejs.dev' )
1614 const path = parsed . pathname || '/'
15+ const base = config . rawBase
1716
18- if ( path . startsWith ( devBase ) ) {
17+ if ( path . startsWith ( base ) ) {
1918 // rewrite url to remove base. this ensures that other middleware does
2019 // not need to consider base being prepended or not
21- req . url = url . replace ( devBase , '/' )
20+ req . url = stripBase ( url , base )
2221 return next ( )
2322 }
2423
@@ -30,18 +29,19 @@ export function baseMiddleware({
3029 if ( path === '/' || path === '/index.html' ) {
3130 // redirect root visit to based url with search and hash
3231 res . writeHead ( 302 , {
33- Location : config . base + ( parsed . search || '' ) + ( parsed . hash || '' )
32+ Location : base + ( parsed . search || '' ) + ( parsed . hash || '' )
3433 } )
3534 res . end ( )
3635 return
3736 } else if ( req . headers . accept ?. includes ( 'text/html' ) ) {
3837 // non-based page visit
39- const redirectPath = joinUrlSegments ( config . base , url )
38+ const redirectPath =
39+ url + '/' !== base ? joinUrlSegments ( base , url ) : base
4040 res . writeHead ( 404 , {
4141 'Content-Type' : 'text/html'
4242 } )
4343 res . end (
44- `The server is configured with a public base URL of ${ config . base } - ` +
44+ `The server is configured with a public base URL of ${ base } - ` +
4545 `did you mean to visit <a href="${ redirectPath } ">${ redirectPath } </a> instead?`
4646 )
4747 return
0 commit comments