Load Balancer и Proxy для Meteor не переходят на 127.0.0.1 - Too Many Redirects?

У меня следующая настройка, но я вижу 302 «Перемещено временно», когда я скручиваю балансировщик нагрузки. В браузере он сообщает о слишком большом количестве перенаправлений:

  • 1 балансировщик нагрузки с SSL
  • 2 веб-сервера

Я запрашиваю https://www.domain.com и получаю ответ 302 с тот же URL-адрес в нем (см. правку ниже). Вот настройки сервера:

Сервер 1 - IP, например, 1.1.1.1 Nginx настроен как балансировщик нагрузки, который обрабатывает SSL и перенаправляет http на https:

server_tokens off; # for security-by-obscurity: stop displaying nginx version
upstream www_backend {
    ip_hash;
    server 2.2.2.2:80;
    server 3.3.3.3:80;
}
# this section is needed to proxy web-socket connections
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}
# HTTP
server {
    listen 80;
    server_name www.domain.com; # the domain on which we want to host the application.
    # redirect non-SSL to SSL
    location / {
        rewrite     ^ https://$server_name$request_uri? permanent;
    }
}
server {
    listen 443 ssl spdy;
    server_name www.domain.com;
    ssl on;
    ssl_stapling on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 5m;
    ssl_certificate         /etc/nginx/ssl/www.domain.com/server.pem; # full path to SSL certificate and CA certificate concatenated together
    ssl_certificate_key     /etc/nginx/ssl/www.domain.com/server.key; # full path to SSL key
    ssl_prefer_server_ciphers       on;
    ssl_protocols                   TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-R blah blah';
    # config to enable HSTS(HTTP Strict Transport Security) https://developer.mozilla.org/en-US/docs/Security/HTTP_Strict_Transport_Security
    # to avoid ssl stripping https://en.wikipedia.org/wiki/SSL_stripping#SSL_stripping
    add_header Strict-Transport-Security "max-age=31536000";
    ssl_dhparam /etc/nginx/ssl/dhparams.pem;
    location / {
        proxy_pass http://www_backend;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_headers_hash_bucket_size 128;
    }
}

Веб-сервер 1 - IP, например, 2.2.2.2 Nginx настроен как прокси, прослушивает порт 80 и переходит на порт 8080:

server_tokens off; # for security-by-obscurity: stop displaying nginx version
# this section is needed to proxy web-socket connections
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}
# HTTP
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    server_name www.domain.com;

    root /var/www/nginx/html;

    location /200.html {
        rewrite ^ /200.html break;
    }

    # pass all requests to Meteor
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_set_header X-NginX-Proxy true;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header X-Forwarded-For $remote_addr; # preserve client IP
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_headers_hash_bucket_size 128;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade; # allow websockets
        proxy_set_header Connection $connection_upgrade;

        # this setting allows the browser to cache the application in a way compatible with Meteor
        # on every application update the name of CSS and JS file is different, so they can be cache infinitely (here: 30 days)
        # the root path (/) MUST NOT be cached
        if ($uri != '/') {
            expires 30d;
        }
    }

    error_page 500 502 503 504 /50x.html;
    location /50x.html{
        root /var/www/nginx/html;
    }
}

Я включил несколько статических HTML-страниц, чтобы проверить доступность веб-сервера.

Приложение Meteor прослушивает локальный порт 8080:

export PORT=8080
# this allows Meteor to figure out correct IP address of visitors
export HTTP_FORWARDED_COUNT=1
# The domain name as configured previously as server_name in nginx
export ROOT_URL=http://www.domain.com
#Start Meteor
exec node /var/www/blah/main.js >> /var/log/blah/meteor.log

] Веб-сервер 2 настроен аналогичным образом.

Если я подключаюсь по ssh к web1 и заворачиваю метеор, он отвечает, как ожидалось: curl http: 127.0.0.1: 8080

Если я скручиваю тестовую HTML-страницу со своей машины разработчика, она отвечает как ожидается: curl https://www.domain.com/200.html

Однако, если я скручиваю корень с моего разработчика, он вообще ничего не отвечает: curl https: //www.domain. com

При нажатии на https://www.domain.com в Chrome отображается ошибка «Слишком много перенаправлений». Поскольку я нажимаю https, а не http, я не понимаю, как могут быть вызваны эти перенаправления.

У меня рейтинг A + для SSL от Qualsys. Я' Запустите sudo nginx -t на всех серверах, и файлы nginx верны.

Я создал символическую ссылку из /etc/nginx/sites-enabled/www.domain.com -> /etc/nginx/sites-available/www.domain.com

Я перезагрузил Nginx: sudo nginx -s reload

Редактировать Кстати - я ранее удалил / etc / nginx / sites-enabled / default и / etc / nginx / sites-available / default по рекомендации другого пользователя ServerFault.

Изменить Вот подробный ответ от curl:

* About to connect() to www.domain.com port 443 (#0)
*   Trying 1.1.1.1...
* connected
* Connected to www.domain.com (1.1.1.1) port 443 (#0)
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server key exchange (12):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSL connection using DHE-RSA-AES128-SHA
* Server certificate:
*    subject: CN=www.domain.com
*    start date: 2016-03-14 00:00:00 GMT
*    expire date: 2019-03-14 23:59:59 GMT
*    subjectAltName: www.domain.com matched
*    issuer: C=US; O=GeoTrust Inc.; CN=Blah Blah 
*    SSL certificate verify ok.
> GET / HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5
> Host: www.domain.com
> Accept: */*
> 
< HTTP/1.1 302 Moved Temporarily
< Server: nginx
< Date: Mon, 28 Mar 2016 05:52:35 GMT
< Transfer-Encoding: chunked
< Connection: keep-alive
< Location: https://www.domain.com/
< Strict-Transport-Security: max-age=31536000
< 
* Connection #0 to host www.domain.com left intact
* Closing connection #0
* SSLv3, TLS alert, Client hello (1):

Я проверил журнал доступа Nginx на веб-сервере и, похоже, подтвердил, что это веб-сервер отправляет 302, а не балансировщик нагрузки:

[28/Mar/2016:01:56:28 -0500] "GET / HTTP/1.1" 302 5 "-" "curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5"

Таким образом, балансировщик нагрузки выглядит успешно передача SSL-вызова с 443 на веб-серверы 80. Служба метеора работает в сети 1 и 2 и успешно отвечает на запросы локального порта 8080. Похоже, что прокси веб-сервера не передает запросы порта 80 на порт 8080.

1
задан 28 March 2016 в 10:13
1 ответ

На веб-сервере я изменил строку схемы, чтобы принудительно выполнить https:

proxy_set_header X-Forwarded-Proto https;

sudo reboot , и это сработало.

0
ответ дан 4 December 2019 в 06:30

Теги

Похожие вопросы