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 @@ -194,7 +194,14 @@ async function httpProxy (fastify, opts) {
194
194
function handler ( request , reply ) {
195
195
const queryParamIndex = request . raw . url . indexOf ( '?' )
196
196
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
+
198
205
reply . from ( dest || '/' , replyOpts )
199
206
}
200
207
Original file line number Diff line number Diff line change @@ -424,6 +424,27 @@ async function run () {
424
424
t . equal ( firstProxyPrefix . body , 'this is /api2/a' )
425
425
} )
426
426
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
+
427
448
test ( 'rewrite location headers' , async t => {
428
449
const proxyServer = Fastify ( )
429
450
You can’t perform that action at this time.
0 commit comments