Nginx with Node api
I'm having a problem at a time and can't solve it. The problem is as follows:
I have a server that on it has an api running with PM2 on port 3000. I installed NGINX and am trying to bind the route of my domain + path to perform the requests for api. I would like to use a route that looks like:
www.dominio.com.br/api
But I can't configure NGINX to do this.
I configured NGINX like this:
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
E this works, but with the route as follows:
www.dominio.com.br
I tried to put the /api
in the location complement, like this:
location /api {
OR
location /api/ {
but it didn't work..
I tried tbm to use upstream and it didn't work! I configured as follows:
upstream teste_api {
server http://localhost:3000;
}
location /api {
set $upstream teste_api;
}
And when I ran the command: sudo nginx-t
This error is displayed: [emerg] "upstream" directive is not allowed here in /etc/nginx/sites-enabled/default:20
Anyone help me please?
1 answers
Normally the directive upstream should be allocated in the Block http {}
in the Nginx configuration file (nginx.conf) ... something like this:
Nginx.conf
http {
##
# node socket upstream
##
upstream teste_api {
ip_hash;
server http://localhost:3000;
}
}
Already in your configuration file of the host (if it is unique) or its subdomains (virtual hosts) you must define the route within the Block server {}
.... similar to the following example:
server {
##
# socket
##
location /api {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_pass http://teste_api;
}
}
Note that in the example above I am setting the headers of: upgrade, connection, version, " x-forwarded-for" and host ... you can set, omit numerous headers here but, these are the basic ones.
On the front-end just call normally:
const socket = new WebSocket('ws://www.dominio.com.br/api')
Source :
Http://nginx.org/en/docs/http/ngx_http_upstream_module.html#upstream