Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
21 changes: 21 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down