diff --git a/lib/serve-handler/src/index.js b/lib/serve-handler/src/index.js index 4e1ce64..9d48854 100644 --- a/lib/serve-handler/src/index.js +++ b/lib/serve-handler/src/index.js @@ -139,7 +139,9 @@ const shouldRedirect = (decodedPath, {redirects = [], trailingSlash}, cleanUrl) } return { target: ensureSlashStart(decodedPath), - statusCode: defaultType + statusCode: defaultType, + preserveQuery: true, + preserveHash: true } } @@ -164,7 +166,9 @@ const shouldRedirect = (decodedPath, {redirects = [], trailingSlash}, cleanUrl) if (target) { return { target: ensureSlashStart(target), - statusCode: defaultType + statusCode: defaultType, + preserveQuery: true, + preserveHash: true } } } @@ -172,13 +176,15 @@ 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, preserveHash} = redirects[index] const target = toTarget(source, destination, decodedPath) if (target) { return { target, - statusCode: type || defaultType + statusCode: type || defaultType, + preserveQuery: !!preserveQuery, + preserveHash: !!preserveHash } } } @@ -763,8 +769,18 @@ module.exports = async (request, response, config = {}, methods = {}) => { } if (paths.redirect) { + // conditionally preserve search and hash + let req_url, req_search, req_hash + + if (paths.redirect.preserveQuery || paths.redirect.preserveHash) { + req_url = url.parse(request.url) + } + + req_search = (paths.redirect.preserveQuery && req_url.search) ? req_url.search : '' + req_hash = (paths.redirect.preserveHash && req_url.hash) ? req_url.hash : '' + response.writeHead(paths.redirect.statusCode, { - Location: encodeURI(paths.redirect.target) + Location: encodeURI(paths.redirect.target + req_search + req_hash) }) response.end()