admin管理员组

文章数量:1167180

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

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

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?

Share Improve this question edited Jun 29, 2011 at 17:10 MPelletier 16.6k18 gold badges89 silver badges140 bronze badges asked Jun 28, 2011 at 7:55 daildail 2071 gold badge2 silver badges5 bronze badges 2
  • 5 The HOST of an http request is part of the header. The request object passed to your callback has a .header() method. Did you try reading the documentation at all? – Karl Knechtel Commented Jun 28, 2011 at 8:00
  • Does this answer your question? Get hostname of current request in node.js Express – Jason Commented Apr 27, 2024 at 20:27
Add a comment  | 

5 Answers 5

Reset to default 19

Use

req.headers.host;

or

req.header('host');

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

req.header('host')

Use that in your request handlers.

Express.js guide - request.hostname

Express.js guide - request.redirect

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

本文标签: javascriptHow to check the HOST using ExpressJSStack Overflow