diff --git a/index.js b/index.js index 7be5933..12b5fcd 100644 --- a/index.js +++ b/index.js @@ -604,8 +604,10 @@ async function fastifyHttpProxy (fastify, opts) { rewritePrefixWithVariables = rewritePrefixWithVariables.replace(`:${name}`, value) } - dest = dest.replace(prefixPathWithVariables, rewritePrefixWithVariables) - } else { + if (dest.startsWith(prefixPathWithVariables)) { + dest = dest.replace(prefixPathWithVariables, rewritePrefixWithVariables) + } + } else if (dest.startsWith(prefix)) { dest = dest.replace(prefix, rewritePrefix) } diff --git a/test/test.js b/test/test.js index 7996dad..da7bfac 100644 --- a/test/test.js +++ b/test/test.js @@ -925,6 +925,27 @@ async function run () { t.assert.strictEqual(fromParametersUrl, '/api2/echo-query?foo=bar&baz=qux') }) + test('fromParameters should only rewrite a leading non-parameterized prefix', async t => { + let fromParametersUrl + const server = Fastify() + server.register(proxy, { + upstream: `http://localhost:${origin.server.address().port}`, + prefix: '/api', + rewritePrefix: '/api2', + preHandler (request, reply, done) { + const { url } = reply.fromParameters('/foo/api/bar', request.params, '/api') + fromParametersUrl = url + done() + } + }) + + await server.listen({ port: 0 }) + t.after(() => server.close()) + + await fetch(`http://localhost:${server.server.address().port}/api/a`) + t.assert.strictEqual(fromParametersUrl, '/foo/api/bar') + }) + test('preRewrite handler', async t => { const proxyServer = Fastify()