Use 301 redirects for deprecated request paths and queries

This commit is contained in:
Michael Jackson 2018-05-18 17:55:28 -07:00
parent e3091c6fe5
commit efe325e6ff
2 changed files with 28 additions and 17 deletions

View File

@ -69,7 +69,7 @@ function findFile(req, res, next) {
}
} else if (filename) {
// They are requesting an explicit filename. Only try to find an
// index.js if they are NOT requesting an HTML directory listing.
// index.js if they are NOT requesting an index page.
useIndex = filename.charAt(filename.length - 1) !== "/";
} else if (
req.query.main &&
@ -120,16 +120,26 @@ function findFile(req, res, next) {
filename = file.replace(req.packageDir, "");
if (
req.query.main != null ||
getBasename(req.filename) !== getBasename(filename)
) {
// Need to redirect to the module file so relative imports resolve
// correctly.
if (req.query.main != null) {
// Permanently redirect ?main requests to their exact files.
// Deprecated, see https://github.com/unpkg/unpkg/issues/63
delete req.query.main;
return res.redirect(
301,
createPackageURL(
req.packageName,
req.packageVersion,
filename,
createSearch(req.query)
)
);
}
if (getBasename(req.filename) !== getBasename(filename)) {
// Redirect to the exact file so relative imports resolve correctly.
// Cache module redirects for 1 minute.
res
return res
.set({
"Cache-Control": "public, max-age=60",
"Cache-Tag": "redirect,module-redirect"
@ -143,11 +153,12 @@ function findFile(req, res, next) {
createSearch(req.query)
)
);
} else {
req.filename = filename;
req.stats = stats;
next();
}
req.filename = filename;
req.stats = stats;
next();
}
);
}

View File

@ -3,7 +3,7 @@ const parsePackageURL = require("../utils/parsePackageURL");
const createSearch = require("./utils/createSearch");
const knownQueryParams = {
main: true,
main: true, // Deprecated, see #63
meta: true,
module: true
};
@ -30,17 +30,17 @@ function sanitizeQuery(query) {
* Parse and validate the URL.
*/
function parseURL(req, res, next) {
// Redirect /_meta/path to /path?meta.
// Permanently redirect /_meta/path to /path?meta.
if (req.path.match(/^\/_meta\//)) {
req.query.meta = "";
return res.redirect(302, req.path.substr(6) + createSearch(req.query));
return res.redirect(301, req.path.substr(6) + createSearch(req.query));
}
// Redirect /path?json => /path?meta
// Permanently redirect /path?json => /path?meta
if (req.query.json != null) {
delete req.query.json;
req.query.meta = "";
return res.redirect(302, req.path + createSearch(req.query));
return res.redirect(301, req.path + createSearch(req.query));
}
// Redirect requests with unknown query params to their equivalents