Назад | Перейти на главную страницу

Nginx proxy_pass всегда отправляет на [:: 1]

У меня проблемы с перенаправлением с Nginx на gunicorn. я использую proxy_pass перенаправить на https://127.0.0.1:5000, и все же перенаправление отправляется на https://[::1]:5000.

Вот мой собственный .conf файл, который включен внутри nginx.conf:

server {
    listen 80;
    server_name mydomain.no www.mydomain.no myotherdomain.no;

    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
    server_name mydomain.no www.mydomain.no myotherdomain.no;
    ssl_certificate /path/to/chain;
    ssl_certificate_key /path/to/private/key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!MD5;

    root /var/www/html/;
    index index.html;
    charset UTF-8;

    location /api {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $http_host;
            proxy_pass https://127.0.0.1:5000;
    }
}

Вот мой nginx.conf файл:

user  django django;
worker_processes  1;

error_log  /path/to/error.log warn;
pid        /path/to/nginx.pid;

events {
worker_connections  1024;
}

http {
include       /path/to/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  /path/to/access.log  main;

sendfile        on;

keepalive_timeout  65;

include /path/to/conf.d/*.conf;
}

Последний include это то, что включает мой файл .conf, и это единственный файл в conf.d каталог (я также проверял наличие скрытых файлов).

Когда я начал сегодня, proxy_pass был установлен на localhost, но я получил 502, когда попытался подключиться к mydomain.no/api/door. Первым делом я проверил, mydomain.no:5000/api/door сработало, и это действительно так. Итак, я пошел проверить error.log. Там я обнаружил такую ​​ошибку:

2016/02/06 06:35:23 [error] 14280#0: *18082 connect() failed (111: Connection refused)
while connecting to upstream, client: nnn.nnn.nnn.nnn, server: mydomain.no,
request: "GET /api/door HTTP/1.1", upstream: "https://[::1]:5000/api/door", host:
"mydomain.no", referrer: "https://mydomain.no/"

Как видите, Nginx по какой-то причине перенаправляется на локальный хост IPv6. Затем я попытался изменить localhost на явный IPv4 с 127.0.0.1, но все равно получил ту же ошибку.

Чтобы предоставить как можно больше (возможно) релевантной информации, вот мой nginx -V также (отформатирован для удобочитаемости):

nginx version: nginx/1.6.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-4) (GCC)
TLS SNI support enabled
configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx 
--conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log 
--http-log-path=/var/log/nginx/access.log 
--http-client-body-temp-path=/var/lib/nginx/tmp/client_body
--http-proxy-temp-path=/var/lib/nginx/tmp/proxy
--http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi
--http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi
--http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid
--lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx
--with-file-aio --with-ipv6 --with-http_ssl_module
--with-http_spdy_module --with-http_realip_module
--with-http_addition_module --with-http_xslt_module
--with-http_image_filter_module --with-http_geoip_module
--with-http_sub_module --with-http_dav_module --with-http_flv_module
--with-http_mp4_module --with-http_gunzip_module
--with-http_gzip_static_module --with-http_random_index_module
--with-http_secure_link_module --with-http_degradation_module
--with-http_stub_status_module --with-http_perl_module --with-mail
--with-mail_ssl_module --with-pcre --with-pcre-jit
--with-google_perftools_module --with-debug --with-cc-opt='-O2 -g -pipe
-Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong
--param=ssp-buffer-size=4 -grecord-gcc-switches 
-specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic'
--with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'

Я попытался изменить настройки IPv6 моей машины, даже отключив IPv6 для всех моих сетевых интерфейсов (включая локальный), но ничего не дало никакого эффекта. Поэтому я обращаюсь к вам за помощью. Что вызывает proxy_pass всегда быть IPv6?

Оказывается, эта проблема была вызвана тем, как был настроен Gunicorn. Мои коллеги сказали мне, что они установили его с шифрованием TLS, но при ближайшем рассмотрении он вообще не использовал шифрование. В [::1] ошибка, вероятно, была вызвана тем, что Nginx вернулся к IPv6 после сбоя соединения IPv4.

Просто изменив proxy_pass из https к http исправил мою проблему при сохранении шифрования, поскольку переход с Nginx на Gunicorn был внутренним. Я также изменил Gunicorn, чтобы он принимал только локальные соединения, поскольку в любом случае доступ к нему будет осуществляться только через прокси-сервер Nginx.