Обновлять:

Обновлять:

У меня есть веб-приложение Django, которое использует внешние порты 80 и 443 совместно с другим сервером. localhostОно прекрасно работает без обратного прокси-сервера, но когда он включен, возникают всевозможные ошибки.

Как заставить обратный прокси работать правильно?

обратный-прокси.conf:

      # SSL Certificate and other SSL configurations
      SSLProxyEngine on
      ProxyRequests on
      SSLProxyVerify require 
      SSLProxyCheckPeerCN on
      SSLProxyCheckPeerName on
      SSLProxyCheckPeerExpire on
      ProxyPreserveHost on
      RequestHeader set X-Forwarded-Proto https

      # Reverse Proxy Configuration
      ProxyPass "/" "https://192.168.1.83/"
      ProxyPassReverse "/" "https://192.168.1.83/"

      # Additional SSL configurations if needed

Я перенаправляю все httpна httpsи включаю указанный выше прокси в свой файл ssl-https conf. Сайт работает нормальнобезвключение (т.е. когда Include .../reverse-proxy.confзакомментировано). Когда включен обратный прокси, я получаю:

[Thu Jan 18 07:09:39.835368 2024] [ssl:error] [pid 46505:tid 133251102926528] [remote 192.168.1.83:443] AH02039: Certificate Verification: Error (20): unable to get local issuer certificate
[Thu Jan 18 07:09:39.835470 2024] [ssl:error] [pid 46505:tid 133251102926528] [remote 192.168.1.83:443] AH02040: Certificate Verification: Certificate Chain too long (chain has 2 certificates, but maximum allowed are only 1)
[Thu Jan 18 07:09:39.835773 2024] [proxy:error] [pid 46505:tid 133251102926528] (20014)Internal error (specific information not available): [client 119.74.38.81:51224] AH01084: pass request body failed to 192.168.1.83:443 (192.168.1.83), referer: https://acupunctureclassique.duckdns.org/
[Thu Jan 18 07:09:39.835832 2024] [proxy:error] [pid 46505:tid 133251102926528] [client 119.74.38.81:51224] AH00898: Error during SSL Handshake with remote server returned by /login/, referer: https://acupunctureclassique.duckdns.org/
[Thu Jan 18 07:09:39.835861 2024] [proxy_http:error] [pid 46505:tid 133251102926528] [client 119.74.38.81:51224] AH01097: pass request body failed to 192.168.1.83:443 (192.168.1.83) from 119.74.38.81 (), referer: https://acupunctureclassique.duckdns.org/

На переднем конце:

Proxy Error
The proxy server could not handle the request

Reason: Error during SSL Handshake with remote server

Apache/2.4.58 (Ubuntu) Server at acupunctureclassique.duckdns.org Port 443

Обновлять:

apachectl -S

VirtualHost configuration:
*:443                  acupunctureclassique.duckdns.org (/etc/apache2/sites-enabled/acu-le-ssl.conf:2)
*:80                   acupunctureclassique.duckdns.org (/etc/apache2/sites-enabled/acu.conf:1)
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex ssl-stapling: using_defaults
Mutex proxy: using_defaults
Mutex ssl-cache: using_defaults
Mutex default: dir="/var/run/apache2/" mechanism=default 
Mutex watchdog-callback: using_defaults
Mutex rewrite-map: using_defaults
Mutex ssl-stapling-refresh: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33 not_used
Group: name="www-data" id=33 not_used

решение1

Реальная проблема, как выяснилось после обсуждений в чате, заключалась в том, что пользователь использовал nginx для проксирования трафика на тот же экземпляр nginx, создавая аккуратный цикл перенаправления, что в конечном итоге приводило к слишком большому заголовку сообщения об ошибке.

> ProxyPass "/" "https://192.168.1.83/"

Вы отправляете свой трафик на https://192.168.1.83. Вы утверждаете, что это сертификат, выпущенный Let's encrypt, но LE будетникогдавыдать сертификат для 192.168.1.83, и ни один публичный CA не выдаст такой сертификат. Помните, чтодействительныйсертификата недостаточно, онимеетчтобы соответствовать ожидаемому имени - которое в данном случае 192.168.1.83. Ваши логи также довольно явно это отражают.

У вас есть несколько альтернатив:

  1. Использовать HTTP-протокол
  2. Используйте самоподписанный сертификат и заставьте Apache доверять ему с помощьюSSLProxyCACertificateдиректива.
  3. Используйте допустимое доменное имя и приобретите допустимый сертификат для доменного имени. Доменное имя может разрешаться в 192.168.1.83, или оно может быть добавлено в /etc/hosts, но Apacheволясопоставьте имя хоста и общее имя (или SAN) в сертификате.
  4. Запрещатьпроверка имени с использованиемSSLProxyCheckPeerName = off
  5. Отключить проверку с помощьюSSLProxyVerify = none, фактически отключая проверку. Это более или менее эквивалентно использованию http...

решение2

Для обратного прокси вам нужно создать виртуальный хост в /etc/apache2/sites-available. Вот пример такой конфигурации VirtualHost

<VirtualHost *:80>
    ServerName yourdomain.com
    ServerAlias www.yourdomain.com

    DocumentRoot /path/to/your/django/static/files

    Alias /static/ /path/to/your/django/static/files/
    <Directory /path/to/your/django/static/files>
        Require all granted
    </Directory>

    ProxyPass / http://localhost:8000/
    ProxyPassReverse / http://localhost:8000/

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:443>
    ServerName yourdomain.com
    ServerAlias www.yourdomain.com

    DocumentRoot /path/to/your/django/static/files

    Alias /static/ /path/to/your/django/static/files/
    <Directory /path/to/your/django/static/files>
        Require all granted
    </Directory>

    SSLEngine on
    SSLCertificateFile /path/to/your/ssl/certificate.crt
    SSLCertificateKeyFile /path/to/your/ssl/private.key
    SSLCertificateChainFile /path/to/your/ssl/chainfile.pem

    ProxyPass / https://localhost:8000/
    ProxyPassReverse / https://localhost:8000/

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Часть https необязательна, вы можете ее пропустить, если вам не нужен https.

Связанный контент