diff --git a/README.md b/README.md index d17c1d5..3aec96a 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ In order to redirect visits to a certain path to a different one (or even an ext } ``` -By default, all of them are performed with the status code [301](https://en.wikipedia.org/wiki/HTTP_301), but this behavior can be adjusted by setting the `type` property directly on the object (see below). +By default, all of them are performed with the status code [301](https://en.wikipedia.org/wiki/HTTP_301), but this behavior can be adjusted by setting the `type` property directly on the object (see below). You may also add the flag `preserveQuery` in order to keep the query and hash upon redirect (for example, `/from?myParam=123#quote` by default routes to `/to`, but with `"preserveQuery": true` will route to `/to?myParam=123#quote`). Just like with [rewrites](#rewrites-array), you can also use routing segments: diff --git a/src/index.js b/src/index.js index 05e3430..a45c47e 100644 --- a/src/index.js +++ b/src/index.js @@ -170,13 +170,14 @@ const shouldRedirect = (decodedPath, {redirects = [], trailingSlash}, cleanUrl) // This is currently the fastest way to // iterate over an array for (let index = 0; index < redirects.length; index++) { - const {source, destination, type} = redirects[index]; + const {source, destination, type, preserveQuery} = redirects[index]; const target = toTarget(source, destination, decodedPath); if (target) { return { target, - statusCode: type || defaultType + statusCode: type || defaultType, + preserveQuery: Boolean(preserveQuery) }; } } @@ -583,8 +584,13 @@ module.exports = async (request, response, config = {}, methods = {}) => { const redirect = shouldRedirect(relativePath, config, cleanUrl); if (redirect) { + let Location = redirect.target + if (redirect.preserveQuery) { + const parsedUrl = url.parse(request.url) + Location = `${Location}${parsedUrl.search || ''}${parsedUrl.hash || ''}` + } response.writeHead(redirect.statusCode, { - Location: encodeURI(redirect.target) + Location: encodeURI(Location) }); response.end();