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 @@ -194,7 +194,14 @@ async function httpProxy (fastify, opts) {
194194 function handler ( request , reply ) {
195195 const queryParamIndex = request . raw . url . indexOf ( '?' )
196196 let dest = request . raw . url . slice ( 0 , queryParamIndex !== - 1 ? queryParamIndex : undefined )
197- dest = dest . replace ( this . prefix , rewritePrefix )
197+ if ( this . prefix . includes ( ':' ) ) {
198+ const requestedPathElements = request . url . split ( '/' )
199+ const prefixPathWithVariables = this . prefix . split ( '/' ) . map ( ( _ , index ) => requestedPathElements [ index ] ) . join ( '/' )
200+ dest = dest . replace ( prefixPathWithVariables , rewritePrefix )
201+ } else {
202+ dest = dest . replace ( this . prefix , rewritePrefix )
203+ }
204+
198205 reply . from ( dest || '/' , replyOpts )
199206 }
200207
Original file line number Diff line number Diff line change @@ -424,6 +424,27 @@ async function run () {
424424 t . equal ( firstProxyPrefix . body , 'this is /api2/a' )
425425 } )
426426
427+ test ( 'rewritePrefix with variables' , async t => {
428+ const proxyServer = Fastify ( )
429+
430+ proxyServer . register ( proxy , {
431+ upstream : `http://localhost:${ origin . server . address ( ) . port } ` ,
432+ prefix : '/api/:id/static' ,
433+ rewritePrefix : '/api2'
434+ } )
435+
436+ await proxyServer . listen ( { port : 0 } )
437+
438+ t . teardown ( ( ) => {
439+ proxyServer . close ( )
440+ } )
441+
442+ const firstProxyPrefix = await got (
443+ `http://localhost:${ proxyServer . server . address ( ) . port } /api/123/static/a`
444+ )
445+ t . equal ( firstProxyPrefix . body , 'this is /api2/a' )
446+ } )
447+
427448 test ( 'rewrite location headers' , async t => {
428449 const proxyServer = Fastify ( )
429450
You can’t perform that action at this time.
0 commit comments