使用nginx,socket.io和https从nodejs获取IP地址



我正在尝试从套接字对象获取客户端IP地址,但是由于我在https中工作,地址是未定义的。

const app = require('https').createServer(optIO).listen(5000);
const io = require('socket.io').listen(app);
io.on('connection', function (socket) {
   console.log('connected: ', socket.request.connection.remoteAddress);
}); 

我尝试使用标题,但我不知道该怎么做。

我的default.conf文件:

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    root /var/www/html;
    index index.php index.html;
    server_name  server.com;
    ssl on;
    ssl_certificate /var/www/cer/server.chained.crt;
    ssl_certificate_key /var/www/cer/server.key;
    ssl_prefer_server_ciphers on;
    ssl_protocols TLSv1.2;
    ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
    ssl_session_cache shared:SSL:5m;
    ssl_session_timeout 5m;
    location / {
            try_files $uri $uri/ /index.html;
    }
    add_header Strict-Transport-Security "max-age=15768000" always;
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
          root /var/www/html;
    }
    location ~ .php$ {
            try_files $uri =404;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }
    location ~ /.ht {
            deny all;
    } 
}
server {
        listen 80;
        listen    [::]:80;
        server_name    server.com;
        return 301 https://www.$server_name$request_uri;
}

我的nginx.conf文件:

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections 4096;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  5;
    gzip  on;
    include /etc/nginx/conf.d/*.conf;
}

我正在使用socket.io 2.01,nginx 1.12.0和node.js 6.10在debian jesse中。

socket.handshake.address.address;

我在socket.io中找到了解决方案。

我将其放入Default.conf

server {
    listen 443 ssl http2;
   {...}
   location ~* .io {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;
      proxy_pass https://localhost:5000;
      proxy_redirect off; 
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
    }
}

最新更新