-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (40 loc) · 1.22 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const parseURL = require('url').parse;
/**
* SEO optimization
*
* Redirect domains starting with www to non-www
* and remove slash at the end of URL for improve SEO
*
* @param app <object> : an express base of server [const app = expres()]
*/
module.exports = function (app) {
app.get('/*', function (req, res, next) {
const
protocol = req.protocol + '://',
urlParam = parseURL(req.url),
search = urlParam.search || '';
let
host = req.headers.host,
doRedirect = false,
pathname = urlParam.pathname;
const
WWWExist = req.headers.host.match(/^www\./) !== null,
slashExist = pathname.charAt(pathname.length - 1) === '/' && pathname !== '/';
// remove www
if (WWWExist) {
host = req.headers.host.replace(/^www\./, '');
doRedirect = true;
}
// remove slash
if (slashExist) {
pathname = pathname.slice(0, -1);
doRedirect = true;
}
// redirect to truest url
if (doRedirect) {
res.redirect(301, protocol + host + pathname + search);
} else {
return next();
}
});
}