H
H
Hecktosaurus2021-04-21 17:35:39
Node.js
Hecktosaurus, 2021-04-21 17:35:39

How to hang a server on a specific domain?

I created a server on the local machine (matched via hosts), it is necessary that it respond only to requests from a specific domain. Now works on both 'css.loc' and 127.0.0.1.
I solve the issue by checking request.headers.host; maybe there is a better solution? I tried to just specify the domain in .listen(port, host), but the server still responds to 127.0.0.1

const https = require('https');
const fs = require('fs');

const host = 'css.loc'; // настройка доменного имени
const port = 443; // настройка порта

const options = {
  key: fs.readFileSync('./_ssl/css.loc.key'),
  cert: fs.readFileSync('./_ssl/css.loc.crt')
};

https.createServer(options, function (request, response) {

    const receivedHost = request.headers.host.split(':')[0]; // узнаем доменное имя без порта
    console.log(receivedHost);
    
    if (receivedHost != host){
        return false; // не отвечаем на запрос и не продолжаем скрипт в случае 127.0.0.1, к примеру
    }

    response.end("Hello world!");

}).listen(port, host);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BasiC2k, 2021-04-21
@BasiC2k

Of course, it will respond to 127.0.0.1, because it is located on this machine. You have already been told - nginx. It can be installed and configured so that calls to 127.0.0.1 are ignored.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question