File tree Expand file tree Collapse file tree 2 files changed +29
-1
lines changed Expand file tree Collapse file tree 2 files changed +29
-1
lines changed Original file line number Diff line number Diff line change @@ -235,7 +235,14 @@ async function httpProxy (fastify, opts) {
235235 function handler ( request , reply ) {
236236 const queryParamIndex = request . raw . url . indexOf ( '?' )
237237 let dest = request . raw . url . slice ( 0 , queryParamIndex !== - 1 ? queryParamIndex : undefined )
238- dest = dest . replace ( this . prefix , rewritePrefix )
238+
239+ if ( this . prefix . includes ( ':' ) ) {
240+ const requestedPathElements = request . url . split ( '/' )
241+ const prefixPathWithVariables = this . prefix . split ( '/' ) . map ( ( _ , index ) => requestedPathElements [ index ] ) . join ( '/' )
242+ dest = dest . replace ( prefixPathWithVariables , rewritePrefix )
243+ } else {
244+ dest = dest . replace ( this . prefix , rewritePrefix )
245+ }
239246 reply . from ( dest || '/' , replyOpts )
240247 }
241248
Original file line number Diff line number Diff line change @@ -444,6 +444,27 @@ async function run () {
444444 t . equal ( firstProxyPrefix . body , 'this is /api2/a' )
445445 } )
446446
447+ test ( 'rewritePrefix with variables' , async t => {
448+ const proxyServer = Fastify ( )
449+
450+ proxyServer . register ( proxy , {
451+ upstream : `http://localhost:${ origin . server . address ( ) . port } ` ,
452+ prefix : '/api/:id/static' ,
453+ rewritePrefix : '/api2'
454+ } )
455+
456+ await proxyServer . listen ( { port : 0 } )
457+
458+ t . teardown ( ( ) => {
459+ proxyServer . close ( )
460+ } )
461+
462+ const firstProxyPrefix = await got (
463+ `http://localhost:${ proxyServer . server . address ( ) . port } /api/123/static/a`
464+ )
465+ t . equal ( firstProxyPrefix . body , 'this is /api2/a' )
466+ } )
467+
447468 test ( 'rewrite location headers' , async t => {
448469 const proxyServer = Fastify ( )
449470
You can’t perform that action at this time.
0 commit comments