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?
We can use the req. hostname property to get the hostname from a current incoming request in express. Example: const express = require("express"); const app = express(); app.
To get the name or hostname of the OS, you can use the hostname() method from the os module in Node. js. /* Get hostname of os in Node. js */ // import os module const os = require("os"); // get host name const hostName = os.
The req. hostname contains the hostname that is derived from the host HTTP header. This property will get its value from the X-Forwarded-Host header field when the trust setting properties are enabled (or not set to false). This header can be set by the client or by the proxy.
Express. js is used by Fox Sports, PayPal, Uber and IBM.
Express.js guide - request.hostname
Express.js guide - request.redirect
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With