Skip to content

Commit be4a268

Browse files
authored
fix: Only replace the prefix at the beginning of the URL. (#452)
Signed-off-by: Paolo Insogna <paolo@cowtech.it>
1 parent f571940 commit be4a268

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

index.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -604,8 +604,10 @@ async function fastifyHttpProxy (fastify, opts) {
604604
rewritePrefixWithVariables = rewritePrefixWithVariables.replace(`:${name}`, value)
605605
}
606606

607-
dest = dest.replace(prefixPathWithVariables, rewritePrefixWithVariables)
608-
} else {
607+
if (dest.startsWith(prefixPathWithVariables)) {
608+
dest = dest.replace(prefixPathWithVariables, rewritePrefixWithVariables)
609+
}
610+
} else if (dest.startsWith(prefix)) {
609611
dest = dest.replace(prefix, rewritePrefix)
610612
}
611613

test/test.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -925,6 +925,27 @@ async function run () {
925925
t.assert.strictEqual(fromParametersUrl, '/api2/echo-query?foo=bar&baz=qux')
926926
})
927927

928+
test('fromParameters should only rewrite a leading non-parameterized prefix', async t => {
929+
let fromParametersUrl
930+
const server = Fastify()
931+
server.register(proxy, {
932+
upstream: `http://localhost:${origin.server.address().port}`,
933+
prefix: '/api',
934+
rewritePrefix: '/api2',
935+
preHandler (request, reply, done) {
936+
const { url } = reply.fromParameters('/foo/api/bar', request.params, '/api')
937+
fromParametersUrl = url
938+
done()
939+
}
940+
})
941+
942+
await server.listen({ port: 0 })
943+
t.after(() => server.close())
944+
945+
await fetch(`http://localhost:${server.server.address().port}/api/a`)
946+
t.assert.strictEqual(fromParametersUrl, '/foo/api/bar')
947+
})
948+
928949
test('preRewrite handler', async t => {
929950
const proxyServer = Fastify()
930951

0 commit comments

Comments
 (0)