NodeJS – Cannot Set Up Port Proxy with NodeJS, React, Apache, and LetsEncrypt

apache-2.4lets-encryptnode.js

I've got the following server setup (Ubuntu 19.04):

  • NodeJS (Express) backend on port 3333
  • React frontend in /var/www/example.com
  • Apache with LetsEncrypt and automatic http > https redirect

I'm trying to force all requests from example.com/api/* to the NodeJS backend on port 3333. This is my sites-enabled/example.com.conf:

<VirtualHost *:80>
    ServerAdmin support@example.com
    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>

If it helps, this is my 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>

With this config:

How do I get the frontend to correctly proxy/redirect example.com/api/* requests to the NodeJS backend?

Best Answer

You are redirecting all http requests to https, but your proxy directives are in the http virtualhost.

Move the proxy* directives to the HTTPS virtualhost.

<VirtualHost *:80>
    ServerAdmin support@example.com
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerAdmin support@example.com
    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>

On a side note, set ProxyRequests to off. This doesn't disable the ProxyPass directives, but enabling this turns your server into an open proxy. Usually you don't want this.

Regarding the 500 error, read your error log.

Related Topic