For serving React app behind reverse proxy such as Nginx or Apache We first create an application using create-react-app
Create a react app using npx like:
npx create-react-app portal
Then install serve node package like:
npm install -g serve
Then you need to update the package.json and add two lines below (assume we want to run under 5000 and the domain name is https://www.yourdomain.com/):
“proxy”: “http://localhost:5000/”,
“homepage”: “https://www.yourdomain.com/portal”,
Then you need to build react application:
npm run build
Then to make your program runs indefinitely install pm2 :
npm install pm2 -g
For starting the application run:
pm2 serve build 5000 –spa
It is time to add the reverse proxy in Nginx as below:
sudo vim /etc/nginx/nginx.conf
server {
listen 443 ssl;
ssl_certificate /PATH_TO_SSL_CRT_FILE.crt;
ssl_certificate_key /PATH_TO_SSL_PRIVATE.key;
server_tokens off;
root /var/www;
server_name www.yourdomain.com;
client_max_body_size 1G;
location /portal {
proxy_pass http://localhost:5000/;
}
}
And for Apache:
sudo vim /etc/apache2/sites-enabled/default-ssl.conf
<VirtualHost _default_:443>
# ....
ProxyPreserveHost On
RewriteEngine On
ProxyPass /portal http://localhost:5000/
ProxyPassReverse /portal http://localhost:5000/
</VirtualHost>
Then you need to restart nginx or Apache:
sudo service nginx restart
sudo service apache2 restart
Finally you should be able to see your react app is running by:
https://www.your-domain.com/portal
For nginx you can also use below instead of serve:
you need to run “npm run build” first and copy the build files into /var/www/html
In the example below the assumption is your application is running in a path such as www.yourdomain.com/portal
server {
listen 443 ssl;
ssl_certificate /PATH_TO_SSL_CRT_FILE.crt;
ssl_certificate_key /PATH_TO_SSL_PRIVATE.key;
server_tokens off;
root /var/www;
server_name www.yourdomain.com;
client_max_body_size 1G;
location /portal {
alias /var/www/html;
try_files $uri $uri/ /map/index.html =404;
}
}
Also if you are using react router maker sure you have basename
The last example is when you want to run react in the root, not in a path;
server {
#listen 80;
#listen [::]:80;
listen 443 SSL;
ssl_certificate /PATH_TO_SSL_CRT_FILE.crt;
ssl_certificate_key /PATH_TO_SSL_PRIVATE.key;
server_name www.yourdomain.com;
client_max_body_size 1G;
location / {
root /var/www/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
}