Using Apache as Reverse Proxy to and from React

51 views Asked by At

I have a React app deployed to an Amazon EC2 instance, which is in turn behind a firewall with limited exposed ports. My React app depends on JSON data drawn from an external source which I do not control, and as such I need a reverse proxy between my app and the server, to insert CORS headers.

The setup I would like looks like this:

  • Apache running on port 8080
  • React on port 3000 (not accessible)
  • User sends requests to 8080, which are forwarded to 3000 to display the app
  • App makes requests to a proxied URL, which are detected by Apache, forwarded, and CORS headers added to response

I was able to get something similar working locally with Nginx and no firewall, but in the cloud I need to use Apache.

My (working) Nginx conf looks like this:

events {
    worker_connections  1024;
}

http {
 server {
  listen 8080;
  server_name localhost;
  proxy_connect_timeout 100;
  proxy_read_timeout 100;
 
  location / {
   proxy_pass http://127.0.0.1:3000;
   }
   location /job/{
   proxy_pass https://url-for-server.com;
   
   if ($request_method = 'OPTIONS') {
   add_header 'Access-Control-Allow-Origin' '*';
   add_header 'Access-Control-Allow-Credentials' 'true';
   add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
   }
   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection 'upgrade';
   proxy_set_header Host $host;
   proxy_cache_bypass $http_upgrade;
   
   add_header 'Access-Control-Allow-Origin' '*';
   add_header 'Access-Control-Allow-Credentials' 'true';
   add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
   }
  }
 } 

I have tried to do something similar in httpd.conf, for example:

Listen 8080
<VirtualHost *:8080>
 ServerName 00.00.00.000/
 ProxyPreserveHost On
 ProxyPass / http://00.00.00.000:3000/
 ProxyPassReverse / http://00.00.00.000:3000/
 ProxyPass /job/ https://url-for-server.com/
 ProxyPassReverse /job/ https://url-for-server.com/
# Header set Access-Control-Allow-Origin "*"
# Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
</VirtualHost>

This setup does let me access the app homepage (running on 3000) from 8080. However, whenever the app makes a fetch request (to /job/etc/etc) it fails with a 404 and I can see from the network console that the request has gone to EC2.IP.ADDRESS:8080/job/etc/etc rather than the external server URL.

So in effect I want Apache to proxy both inbound browser requests to the app and outbound app requests to the server. Is this type of setup possible, or am I missing some obvious problem?

0

There are 0 answers