Ssh

用於 SSH 隧道的 Apache 反向代理

  • February 19, 2022

我想為在本地網路中執行的 Home-Assistant(hass) 實例設置一個 Apache 反向代理。

我將本地 hass 實例的流量通過隧道傳輸到遠端伺服器ssh -N proxy@example.com -R 8123:localhost:8123

現在我嘗試在 Apache 中設置一個普通的反向代理:

<VirtualHost *:443>
   ServerName hass.example.com

   SSLEngine On

   # If you manage SSL certificates by yourself, these paths will differ.
   SSLCertificateFile fullchain.pem
   SSLCertificateKeyFile privkey.pem

   SSLProxyEngine on
   SSLProxyProtocol +TLSv1.2 +TLSv1.3
   SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH

   ProxyPreserveHost On
   ProxyRequests Off
   ProxyVia On
   RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}
   
           
   # Proxy all traffic to hass
   ProxyPass / http://localhost:8123/ nocanon
   ProxyPassReverse / http://localhost/
   ErrorLog ${APACHE_LOG_DIR}/hass.example.com-error.log
   CustomLog ${APACHE_LOG_DIR}/hass.example.com-access.log combined
   <IfModule security2_module>
       SecRuleEngine off
   </IfModule>
</VirtualHost>

<VirtualHost *:80>
   ServerName hass.example.com

   Redirect permanent / "https://hass.example.com"

   ErrorLog ${APACHE_LOG_DIR}/hass.example.com-error.log
   CustomLog ${APACHE_LOG_DIR}/hass.example.com-access.log combined
</VirtualHost>

可悲的是,如果我嘗試打開hass.example.com,瀏覽器會以400: Bad Request.

這一切都歸結為Home-Assistant 阻止反向代理嘗試,並且您還必須代理 websocket 請求

調整後的 hass-config ( config/configuration.yaml):

http:
 use_x_forwarded_for: true
 trusted_proxies:
 - ::1
 - 127.0.0.1
 ip_ban_enabled: true
 login_attempts_threshold: 5

阿帕奇配置:

<VirtualHost *:443>
   ServerName hass.example.com

   SSLEngine On

   # If you manage SSL certificates by yourself, these paths will differ.
   SSLCertificateFile fullchain.pem
   SSLCertificateKeyFile privkey.pem

   SSLProxyEngine on
   SSLProxyProtocol +TLSv1.2 +TLSv1.3
   SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH

   ProxyPreserveHost On
   ProxyRequests Off
   ProxyVia On
   RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}
   
           
   # Proxy all traffic to hass
   RewriteEngine On
   RewriteCond %{HTTP:Upgrade} =websocket
   RewriteRule /(.*) ws://localhost:8123/$1 [P]
   RewriteCond %{HTTP:Upgrade} !=websocket
   RewriteRule /(.*) http://localhost:8123/$1 [P]
   ProxyPassReverse / http://localhost:8123


   ErrorLog ${APACHE_LOG_DIR}/hass.example.com-error.log
   CustomLog ${APACHE_LOG_DIR}/hass.example.com-access.log combined
   <IfModule security2_module>
       SecRuleEngine off
   </IfModule>
</VirtualHost>

<VirtualHost *:80>
   ServerName hass.example.com

   Redirect permanent / "https://hass.example.com"

   ErrorLog ${APACHE_LOG_DIR}/hass.example.com-error.log
   CustomLog ${APACHE_LOG_DIR}/hass.example.com-access.log combined
</VirtualHost>

引用自:https://serverfault.com/questions/1089250