1
1
import type { Connect } from 'dep-types/connect'
2
2
import type { ViteDevServer } from '..'
3
- import { joinUrlSegments } from '../../utils'
3
+ import { joinUrlSegments , stripBase } from '../../utils'
4
4
5
- // this middleware is only active when (config. base !== '/')
5
+ // this middleware is only active when (base !== '/')
6
6
7
7
export function baseMiddleware ( {
8
8
config
9
9
} : ViteDevServer ) : Connect . NextHandleFunction {
10
- const devBase = config . base . endsWith ( '/' ) ? config . base : config . base + '/'
11
-
12
10
// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
13
11
return function viteBaseMiddleware ( req , res , next ) {
14
12
const url = req . url !
15
13
const parsed = new URL ( url , 'http://vitejs.dev' )
16
14
const path = parsed . pathname || '/'
15
+ const base = config . rawBase
17
16
18
- if ( path . startsWith ( devBase ) ) {
17
+ if ( path . startsWith ( base ) ) {
19
18
// rewrite url to remove base. this ensures that other middleware does
20
19
// not need to consider base being prepended or not
21
- req . url = url . replace ( devBase , '/' )
20
+ req . url = stripBase ( url , base )
22
21
return next ( )
23
22
}
24
23
@@ -30,18 +29,19 @@ export function baseMiddleware({
30
29
if ( path === '/' || path === '/index.html' ) {
31
30
// redirect root visit to based url with search and hash
32
31
res . writeHead ( 302 , {
33
- Location : config . base + ( parsed . search || '' ) + ( parsed . hash || '' )
32
+ Location : base + ( parsed . search || '' ) + ( parsed . hash || '' )
34
33
} )
35
34
res . end ( )
36
35
return
37
36
} else if ( req . headers . accept ?. includes ( 'text/html' ) ) {
38
37
// non-based page visit
39
- const redirectPath = joinUrlSegments ( config . base , url )
38
+ const redirectPath =
39
+ url + '/' !== base ? joinUrlSegments ( base , url ) : base
40
40
res . writeHead ( 404 , {
41
41
'Content-Type' : 'text/html'
42
42
} )
43
43
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 } - ` +
45
45
`did you mean to visit <a href="${ redirectPath } ">${ redirectPath } </a> instead?`
46
46
)
47
47
return
0 commit comments