I have 2 websites php and reactjs
- php site running on http://localhost
- react site running on http://localhost:3000
I'd like to access http://localhost:3000/funds page when user visit URL http://localhost/funds. I tried with apache proxy but it is showing blank react site as images and css missing on path. Any other suggestion to achieve this, Thanks.
ProxyPass /funds http://localhost:3000/funds
ProxyPassReverse /funds http://localhost:3000/funds
CodePudding user response:
My working demo on github works for both
http://localhost:8080/funds
and http://localhost:8080
. The dockerized solution here is forwarding port 80 to 8080 but it can be set up to use port 80 if needed.
Still can't figure out what's the problem!
try check Apache log files. if the basics of reverse proxying SPA apps is well understood, just reading logs can solve most problems easily.
Edit: Serving A React App and PHP(or anything else) Together.
A react app cannot be served at subpaths. The javascript code for react basically assumes that it's from the root path(/
). If it is served from other sub paths(such as /funds
), it will fail to reach other necessary resources such as .css, .js
...etc.
The failure process:
- react bootstrap index page at
/subpath/index.html
- without modifying the setting, it'll try to get all resources from
/
:/bundle.js
,/styles.css
,/favicon.ico
- requests fail, because they exists at
/subpath/bundle.js
,subpath/styles.css
and so on...
This is not easily solved unless environment specific setting is used. the discrepancy between local and production environment will make things more complicated later.
Solution 2: using subdomain
The best solution in this case, is to use subdomain. Apps do not have to change at all because they are all served from the root path. However, it requires hosts file modification to run from a local machine.
let's say I want to use sample.test
as domain.
- php will be served at
sample.test
- react app will be served at
react.sample.test
# hosts file
127.0.0.1 sample.test
127.0.0.1 react.sample.test
# httpd.conf
# Custom Reverse Proxy /w subdomains
# this setting is no more needed.
# ProxyPass "/react" "http://react-frontend:3000/"
# ProxyPassReverse "/react" "http://react-frontend:3000/"
# ProxyPass "/" "http://php-frontend:80/"
# ProxyPassReverse "/" "http://php-frontend:80/"
# resolve to different service by subdomain.
<VirtualHost *:80>
ServerName react.sample.test
RewriteEngine On
ProxyPass "/" "http://react-frontend:3000/"
ProxyPassReverse "/" "http://react-frontend:3000/"
<Directory "/">
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</Directory>
</VirtualHost>
<VirtualHost *:80>
ServerName sample.test
ProxyPass "/" "http://php-frontend:80/"
ProxyPassReverse "/" "http://php-frontend:80/"
</VirtualHost>
I've updated Github source. Try run the dockerized demo.