diff --git a/index.js b/index.js index 51a8178..d9d95f8 100644 --- a/index.js +++ b/index.js @@ -194,7 +194,14 @@ async function httpProxy (fastify, opts) { function handler (request, reply) { const queryParamIndex = request.raw.url.indexOf('?') let dest = request.raw.url.slice(0, queryParamIndex !== -1 ? queryParamIndex : undefined) - dest = dest.replace(this.prefix, rewritePrefix) + if (this.prefix.includes(':')) { + const requestedPathElements = request.url.split('/') + const prefixPathWithVariables = this.prefix.split('/').map((_, index) => requestedPathElements[index]).join('/') + dest = dest.replace(prefixPathWithVariables, rewritePrefix) + } else { + dest = dest.replace(this.prefix, rewritePrefix) + } + reply.from(dest || '/', replyOpts) } diff --git a/test/test.js b/test/test.js index 8a96180..bbda84c 100644 --- a/test/test.js +++ b/test/test.js @@ -424,6 +424,27 @@ async function run () { t.equal(firstProxyPrefix.body, 'this is /api2/a') }) + test('rewritePrefix with variables', async t => { + const proxyServer = Fastify() + + proxyServer.register(proxy, { + upstream: `http://localhost:${origin.server.address().port}`, + prefix: '/api/:id/static', + rewritePrefix: '/api2' + }) + + await proxyServer.listen({ port: 0 }) + + t.teardown(() => { + proxyServer.close() + }) + + const firstProxyPrefix = await got( + `http://localhost:${proxyServer.server.address().port}/api/123/static/a` + ) + t.equal(firstProxyPrefix.body, 'this is /api2/a') + }) + test('rewrite location headers', async t => { const proxyServer = Fastify()