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
79
79
80
80
The 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.
81
81
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
+
82
89
### beforeHandler
83
90
84
91
A ` 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) {
8
8
}
9
9
10
10
const beforeHandler = opts . beforeHandler
11
+ const rewritePrefix = opts . rewritePrefix || ''
11
12
12
13
const fromOpts = Object . assign ( { } , opts )
13
14
fromOpts . base = opts . upstream
@@ -26,7 +27,8 @@ module.exports = async function (fastify, opts) {
26
27
fastify . all ( '/*' , { beforeHandler } , reply )
27
28
28
29
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 )
30
32
reply . from ( dest || '/' , opts . replyOptions )
31
33
}
32
34
}
Original file line number Diff line number Diff line change @@ -23,6 +23,10 @@ async function run () {
23
23
throw new Error ( 'kaboom' )
24
24
} )
25
25
26
+ origin . get ( '/api2/a' , async ( request , reply ) => {
27
+ return 'this is /api2/a'
28
+ } )
29
+
26
30
await origin . listen ( 0 )
27
31
28
32
tearDown ( origin . close . bind ( origin ) )
@@ -179,6 +183,25 @@ async function run () {
179
183
const { headers } = await got ( `http://localhost:${ proxyServer . server . address ( ) . port } /api` )
180
184
t . match ( headers , { 'x-test' : 'test' } )
181
185
} )
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
+ } )
182
205
}
183
206
184
207
run ( )
You can’t perform that action at this time.
0 commit comments