开发者

How to check the HOST using ExpressJS?

I have to check the HOST of the http request, if it's equal to example.com or www.example.com, I have to do a 301 redirect.

开发者_运维技巧

How can I do this using Node.js and Express Web Framework?


Use

req.headers.host;

or

req.header('host');

Both will return you host name. e.g localhost:3000


Express.js guide - request.hostname

Express.js guide - request.redirect


req.header('host')

Use that in your request handlers.


Do a string search, using a regular expression, as so:

if ( req.headers.host.search(/^www/) !== -1 ) {
  res.redirect(301, "http://example.com/");
}

The search method accepts a regular expression as the first argument, denoted by surrounding slashes. The first character, ^, in the expression means to explicitly look at the beginning of the string. The rest of the expression is looking for three explicit w's. If the string begins with "www", then the search method will return the index of match, if any (0), or -1, if it wasn't found.


Today for me it's req.host, req.hostname and req.headers.host - I'm going with req.host though. update vscode tells me req.host is deprecated and use req.hostname instead

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜