Restrict access to Node.js-based HTTP server by IP address

后端 未结 2 1784
无人及你
无人及你 2020-11-29 03:04

How can I restrict access by IP address in a Node.js HTTP server application?

I\'m looking for something like this:

Deny from all
Allow from ..
         


        
2条回答
  •  青春惊慌失措
    2020-11-29 03:33

    I'm not sure how bulletproof is this approach, but here it is, collected from answers around the web:

    var http = require('http');
    http.createServer(function (req, res)
    {
        var ip = req.ip || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
        if (ip == '127.0.0.1') // exit if it's a particular ip
            res.end();
    ...
    

    Please, someone more proficient in node - correct me

提交回复
热议问题