无法使用 NodeJS、React、Apache 和 LetsEncrypt 设置端口代理

无法使用 NodeJS、React、Apache 和 LetsEncrypt 设置端口代理

我有以下服务器设置(Ubuntu 19.04):

  • 端口 3333 上的 NodeJS (Express) 后端
  • React 前端/var/www/example.com
  • 带有 LetsEncrypt 和自动 http > https 重定向的 Apache

我正在尝试强制所有请求从example.com/api/*端口 3333 发送到 NodeJS 后端。这是我的sites-enabled/example.com.conf

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName example.com
    ServerAlias example.com
    DocumentRoot /var/www/example.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    RewriteCond %{SERVER_NAME} =example.com [OR]
    RewriteCond %{SERVER_NAME} =www.example.com
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
    ProxyRequests on
    ProxyPreserveHost on
    ProxyPass /api https://127.0.0.1:3333/api
    ProxyPassReverse /api https://127.0.0.1:3333/api
</VirtualHost>

如果有帮助的话,这是我的sites-enabled/example.com-le-ssl.conf

<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerAdmin support@exampl
        ServerName example.com
        ServerAlias example.com
        DocumentRoot /var/www/example.com
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        Include /etc/letsencrypt/options-ssl-apache.conf
        ServerAlias www.example.com
        SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    </VirtualHost>
</IfModule>

使用此配置:

如何让前端正确地代理/重定向example.com/api/*请求到 NodeJS 后端?

答案1

您正在将所有 http 请求重定向到 https,但您的代理指令位于 http 虚拟主机中。

将代理*指令移动到 HTTPS 虚拟主机。

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerAdmin [email protected]
    ServerName example.com
    DocumentRoot /var/www/example.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    Include /etc/letsencrypt/options-ssl-apache.conf
    ServerAlias www.example.com
    SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem

    ProxyRequests off
    ProxyPreserveHost on
    ProxyPass /api https://127.0.0.1:3333/api
    ProxyPassReverse /api https://127.0.0.1:3333/api
</VirtualHost>

另外,设置ProxyRequestsoff。这不会禁用 ProxyPass 指令,但启用它会将您的服务器变成开放代理。通常您不希望出现这种情况。

关于 500 错误,请阅读您的错误日志。

相关内容