Skip to content
Open
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
12 changes: 9 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
};
}
}
Expand Down Expand Up @@ -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();
Expand Down