user2079164
user2079164

Reputation: 21

How to prevent direct access to IP Express node.js

I can't find a resource for this anywhere online, all I see is references for nginx.

I need help with this quickly as my server is live with users accessing it and somehow google indexed my ip address and users are accessing my site through my ip.

I plan to migrate servers tonight and am aware of why my ip was indexed, but in the meantime need a method to prevent direct access via my ip.

This obviously isn't working, and don't have much room to test, unless I stop the server and kick all of my users off for an extended period of time:

app.get('myiphere', function(req, res){
    res.redirect('domain.com');
});

Upvotes: 1

Views: 2008

Answers (3)

sonEtLumiere
sonEtLumiere

Reputation: 4562

To prevent direct access to your site from IP you can set the loopback IP this way:

app.listen(3000, '127.0.0.1', () => console.log('Server running on port 3000'))

Upvotes: 1

Dorad
Dorad

Reputation: 3713

You can implement an application-level middleware which checks that a request host-name isn't anything else but your domain. That way an access to your with an IP address wouldn't cause a processing (on application level).

const SITE_ADDRESS = 'yourwebsite.com';
app.use((req,res,next) => {
  if (req.hostname.includes(SITE_ADDRESS)) 
    next();
  else
    res.status(403).end(`Access with ${req.hostname} is restricted. Use ${SITE_ADDRESS} instead.`);
});

Upvotes: 1

joernneumeyer
joernneumeyer

Reputation: 46

Prevent indexing by creating a robots.txt at your server root directory. See https://stackoverflow.com/a/390379/11191351

Upvotes: 0

Related Questions