diff --git a/server/middleware/findFile.js b/server/middleware/findFile.js index b151f9a..6fd0415 100644 --- a/server/middleware/findFile.js +++ b/server/middleware/findFile.js @@ -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(); } ); } diff --git a/server/middleware/parseURL.js b/server/middleware/parseURL.js index e3e3b5a..babc593 100644 --- a/server/middleware/parseURL.js +++ b/server/middleware/parseURL.js @@ -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