I’m running my node.js back-end server at port 3001 while my react.js is running at port 3000 i have been trying to setup my nginx server to no avail, kept getting either bad gateway or cors error please help below is my nginx config file, refer below:
listen 80;
listen [::]:80;
root /var/www/157.245.3.88/;
# Add index.php to the list if you are using PHP
index index.html;
server_name 157.245.3.88:3000;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
# try_files $uri $uri/ =404;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:3000;
proxy_redirect http://127.0.0.1:3000 http://$server_name/;
}
}
server {
listen 80;
listen [::]:80;
server_name 157.245.3.88:3001;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:3001;
proxy_redirect http://127.0.0.1:3001 http://$server_name/;
}
location /order-checkout {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header HOST $host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:3001/order-checkout;
proxy_redirect http://127.0.0.1:3001/order-checkout http://$server_name/;
}
location /api {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header HOST $host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:3001/api;
proxy_redirect http://127.0.0.1:3001/api http://$server_name/;
}
}
2
Answers
root
directive takes directory where static files are located. I don’t think/var/www/157.245.3.88/
is directory. Create a dir in/var/www/<name>
and put your react bundle there. For this example i’ll assume/var/www/example_com/
and i’ll also assume domain name isexample.com
.server_name
takes domain name not ip address. So it should beexample.com
or/andwww.example.com
.You don’t need
proxy_redirect
.proxy_pass
is more than enough.once completed test config by running
then restart nginx.
HeadsUp: I have kept config simple as possible to your question but you might endup adding more config. Like adding ssl certificate rules (certbot), redirecting
www.example.com
toexample.com
(or vice-versa), logging (access/error) and more. Refer docs for more.I think instead of adding a react bundle in the /www you can simply use the pm2 to keep your react app running and simply setup reverse proxy for that localhost port.
let me know if you need server bloc code for that