UNPKG

741 BJavaScriptView Raw
1/**
2 * Copyright (c) 2015-present, Facebook, Inc.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7'use strict';
8
9const path = require('path');
10
11module.exports = function createRedirectServedPathMiddleware(servedPath) {
12 // remove end slash so user can land on `/test` instead of `/test/`
13 servedPath = servedPath.slice(0, -1);
14 return function redirectServedPathMiddleware(req, res, next) {
15 if (
16 servedPath === '' ||
17 req.url === servedPath ||
18 req.url.startsWith(servedPath)
19 ) {
20 next();
21 } else {
22 const newPath = path.join(servedPath, req.path !== '/' ? req.path : '');
23 res.redirect(newPath);
24 }
25 };
26};