I am trying to run a react app with Node.js backend on the Nginx server.
Here’s my server block in the nginx.conf file:
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
listen [::]:80;
server_name _;
root /usr/share/nginx/folder-name/frontend/build;
index index.html index.htm;
location / {
proxy_pass http://localhost:5000;
}
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
The build
folder contains the compiled react js code(using npm run build
)
Node.js backend is running on port 5000 using pm2/forever.
After restarting the Nginx Server, the react UI appears on the server IP but the UI is distorted.
Also, I am not able to access my backend APIs on MyIP/api/endpoint
.
What am i doing wrong.? This nginx configuration was built from SO and other online resources so there’s a huge probabilty that it could be wrong. Please help!
Thanks in advance!
4
Answers
One issue is with your
proxy_pass
directive. You are missing trailing slash/
First, try this and share your result.
Yes, you can host both API and static files (build files of your front-end) on the same domain or host. Below, you can find a server block for a sample API hosted on port 3000 and static HTML files at a root location being served on port 80.
You can access the front-end at
http://localhost/<blah...>
and the API athttp://localhost/api/<blah...>
(please note how/api
is handled in the URL here and the server block above). Replacelocalhost
with your domain name.The issue is you are setting the API proxy for the root (
/
). The correct one should look like this:If you don’t have
/api
path in your Node.js, you will need a rewrite rule for it like this:I had experience that.Please check my image file
This configuration is running successfully on aws.
Your mistakes is proxy area. Please change like that.
If you want, I can HELP you.