File tree 2 files changed +29
-1
lines changed
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) {
235
235
function handler ( request , reply ) {
236
236
const queryParamIndex = request . raw . url . indexOf ( '?' )
237
237
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
+ }
239
246
reply . from ( dest || '/' , replyOpts )
240
247
}
241
248
Original file line number Diff line number Diff line change @@ -444,6 +444,27 @@ async function run () {
444
444
t . equal ( firstProxyPrefix . body , 'this is /api2/a' )
445
445
} )
446
446
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
+
447
468
test ( 'rewrite location headers' , async t => {
448
469
const proxyServer = Fastify ( )
449
470
You can’t perform that action at this time.
0 commit comments