Search code examples
nginxvirtualhostserverproxypass

Nginx: How to forward requests to a port using proxy_pass


I'm just getting started with Nginx and am trying to set up a server block to forward all requests on the subdomain api.mydomain.com to port 8080.

Here's what I've got:

UPDATED:

server {
  server_name api.mydomain.com;

  location / {
    proxy_pass http://127.0.0.1:8080/;
    proxy_set_header    Host            $host;
    proxy_set_header    X-Real-IP       $remote_addr;
    proxy_set_header    X-Forwarded-for $remote_addr;
  }
}

server {
  server_name www.mydomain.com;
  return 301 $scheme://mydomain.com$request_uri;
}

server {
  server_name mydomain.com;

  root /var/www/mydomain.com;
  index index.html index.htm;

  location / {
    try_files $uri $uri/ =404;
  }
}

The server block exists in /etc/nginx/sites-available and I have created a symlink in /etc/nginx/sites-enabled.

What I expect:

I'm running deployd on port 8080. When I go to api.mydomain.com/users I expect to get a JSON response from the deployd API, but I get no response instead.

Also, my 301 redirect for www.mydomain.com is not working. That block was code I copied from Nginx Pitfalls.

What I've tried:

  • Confirmed that mydomain.com:8080/users and $ curl http://127.0.0.1:8080/users return the expected response.
  • Restarted the nginx service after making changes to the server block.
  • Tried removing the proxy_set_header lines.

Any idea what I'm missing here?


Solution

  • As it turns out, my problem was not with Nginx configuration but rather with my DNS settings. I had to create an A NAME record for each of my sub-domains (www and api). Rookie mistake.

    A colleague of mine actually helped me troubleshoot the issue. We discovered the problem when using telnet from my local machine to connect to the server via IP address and saw that Nginx was, in fact, doing what I intended.