1
votes

I have a basic Nginx configuration for a Node API and I can't seem to figure out what I am doing wrong.

My Nginx file looks like this:

user www-data;
worker_processes 4;
pid /run/nginx.pid;

events {
   worker_connections 768;
   multi_accept on;
}

http {

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
    server_tokens off;

include /etc/nginx/mime.types;
default_type application/octet-stream;

access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;

gzip on;
gzip_disable "msie6";

include /etc/nginx/conf.d/*.conf;
   #    include /etc/nginx/sites-enabled/*;
}

and then inside my /etc/nginx/conf.d/ I have a proxy.conf that looks like this:

server {
  listen 80;
  server_name [domain_name];

  add_header Access-Control-Allow-Origin '*';

  location / {
    proxy_pass [client_endpoint]
  }

  location /api {
    add_header Allow 'POST, GET, PUT';

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    proxy_pass http://XX.XXX.XXX.XXX:3005;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

  }
}

The proxy from location "/" works fine, but trying to proxy to another port on the server it times out because it cannot reach it, or it will give me a 403 error. I have tried using the IP address and localhost. Can anyone help me out here? Thanks in advance.

EDIT:

The / location block is working and the /api location is not. I am trying to proxy the /api location to port 3005 on the server. Do I need to proxy to localhost or do I need to proxy to the IP/port of my server? I have tried both so I assume there is an issue with my syntax. What am I missing? Thanks.

2
(1) which location block is giving you problems? / or /api? (2) You are trying to access port 3005 on localhost? Could you be more explicit about what your question is? It didn’t make much sense to me as an outside reader.2ps
I have edited my question to clarify. Hopefully that makes more sense now. Thanks.gradorade

2 Answers

0
votes

Here is what I usually do for node/nginx:

upstream nodejs {
    server 127.0.0.1:3005;
    keepalive 256;
}

server {
  . . . 

  location /api {
    add_header Allow 'POST, GET, PUT';

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    proxy_set_header        Connection "";
    proxy_http_version      1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://nodejs;
  }
}
0
votes

I found the issue. It turned out to not be Nginx related. I enabled TCP traffic on my AWS EC2 instance and the proxy worked.