Reputation: 3281
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!
Upvotes: 4
Views: 7056
Reputation: 2474
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.
server {
listen 80;
server_name localhost;
location / {
root /var/www/html;
index index.html;
error_page 404 index.html;
}
location /api/ {
proxy_pass http://localhost:3000/;
}
}
You can access the front-end at http://localhost/<blah...>
and the API at http://localhost/api/<blah...>
(please note how /api
is handled in the URL here and the server block above). Replace localhost
with your domain name.
Upvotes: 4
Reputation: 132
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.
location /api/ {
proxy_pass http://127.0.0.1:5000/api/
}
If you want, I can HELP you.
Upvotes: 1
Reputation: 468
The issue is you are setting the API proxy for the root (/
). The correct one should look like this:
server {
listen 80;
listen [::]:80;
server_name _;
root /usr/share/nginx/folder-name/frontend/build;
index index.html index.htm;
location /api {
proxy_pass http://localhost:5000;
}
location / {
try_files $uri $uri/ =404;
}
}
If you don't have /api
path in your Node.js, you will need a rewrite rule for it like this:
location /api {
rewrite ^/api/?(.*) /$1 break;
proxy_pass http://localhost:5000;
proxy_redirect off;
proxy_set_header Host $host;
}
Upvotes: 8
Reputation: 10358
What am i doing wrong.?
One issue is with your proxy_pass
directive. You are missing trailing slash /
...
location / {
proxy_pass http://localhost:5000/;
}
...
First, try this and share your result.
Upvotes: 0