File tree Expand file tree Collapse file tree 3 files changed +33
-1
lines changed Expand file tree Collapse file tree 3 files changed +33
-1
lines changed Original file line number Diff line number Diff line change @@ -79,6 +79,13 @@ An URL (including protocol) that represents the target server to use for proxyin
7979
8080The prefix to mount this plugin on. All the requests to the current server starting with the given prefix will be proxied to the provided upstream.
8181
82+ The prefix will be removed from the URL when forwarding the HTTP
83+ request.
84+
85+ ### rewritePrefix
86+
87+ Rewrite the prefix to the specified string. Default: ` '' ` .
88+
8289### beforeHandler
8390
8491A ` beforeHandler ` to be applied on all routes. Useful for performing actions before the proxy is executed (e.g. check for authentication).
Original file line number Diff line number Diff line change @@ -8,6 +8,7 @@ module.exports = async function (fastify, opts) {
88 }
99
1010 const beforeHandler = opts . beforeHandler
11+ const rewritePrefix = opts . rewritePrefix || ''
1112
1213 const fromOpts = Object . assign ( { } , opts )
1314 fromOpts . base = opts . upstream
@@ -26,7 +27,8 @@ module.exports = async function (fastify, opts) {
2627 fastify . all ( '/*' , { beforeHandler } , reply )
2728
2829 function reply ( request , reply ) {
29- var dest = request . req . url . replace ( this . basePath , '' )
30+ var dest = request . req . url
31+ dest = dest . replace ( this . basePath , rewritePrefix )
3032 reply . from ( dest || '/' , opts . replyOptions )
3133 }
3234}
Original file line number Diff line number Diff line change @@ -23,6 +23,10 @@ async function run () {
2323 throw new Error ( 'kaboom' )
2424 } )
2525
26+ origin . get ( '/api2/a' , async ( request , reply ) => {
27+ return 'this is /api2/a'
28+ } )
29+
2630 await origin . listen ( 0 )
2731
2832 tearDown ( origin . close . bind ( origin ) )
@@ -179,6 +183,25 @@ async function run () {
179183 const { headers } = await got ( `http://localhost:${ proxyServer . server . address ( ) . port } /api` )
180184 t . match ( headers , { 'x-test' : 'test' } )
181185 } )
186+
187+ test ( 'keepPrefix true' , async ( t ) => {
188+ const proxyServer = Fastify ( )
189+
190+ proxyServer . register ( proxy , {
191+ upstream : `http://localhost:${ origin . server . address ( ) . port } ` ,
192+ prefix : '/api' ,
193+ rewritePrefix : '/api2'
194+ } )
195+
196+ await proxyServer . listen ( 0 )
197+
198+ t . tearDown ( ( ) => {
199+ proxyServer . close ( )
200+ } )
201+
202+ const firstProxyPrefix = await got ( `http://localhost:${ proxyServer . server . address ( ) . port } /api/a` )
203+ t . equal ( firstProxyPrefix . body , 'this is /api2/a' )
204+ } )
182205}
183206
184207run ( )
You can’t perform that action at this time.
0 commit comments