Nuxt或Laravel无法获得访客的公开IP

时间:2019-08-15 17:26:29

标签: laravel vue.js nginx server-side-rendering nuxt

有Nuxt + Laravel(Apiato)的基本设置。对于nuxt,我将反向代理与nginx一起使用,对于Laravel也是nginx。

当我从Postman到达终结点时,我获得了公共IP,但是当涉及实时站点上的Nuxt时,IP为127.0.0.1。

我使用request()->ip()来获取IP。

我已经尝试添加proxy_set_header,但是我做错了,或者根本没有应用。

两个应用程序都使用同一台服务器。

Nuxt

server {
    index index.html;
    server_name example.com

    location / {
        proxy_pass http://localhost:8002;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-User-Agent $http_user_agent;
        proxy_set_header X-Referer $http_referer;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}

Laravel

server {
    index index.html;
    server_name api.example.com;
    root /var/www/api.example.com/public;
    index index.php index.html index.htm;
    location / {
         try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        try_files $uri /index.php =404;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        fastcgi_param SCRIPT_FILENAME 
        $document_root$fastcgi_script_name;
        #fixes timeouts
        fastcgi_read_timeout 600;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }

    location /.well-known/acme-challenge/ {
        root /var/www/letsencrypt/;
        log_not_found off;
    }

    error_log /var/log/nginx/api_error.log;
    access_log /var/log/nginx/api_access.log;
}

1 个答案:

答案 0 :(得分:0)

如果有代理,请尝试以下操作:

const ip = req.headers['x-forwarded-for'].split(',').pop() ||
  req.connection.remoteAddress

否则,请执行以下操作:

const ip = req.connection.remoteAddress