Shaun Scovil
Shaun Scovil

Reputation: 3987

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:

Any idea what I'm missing here?

Upvotes: 1

Views: 2610

Answers (2)

Shaun Scovil
Shaun Scovil

Reputation: 3987

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.

Upvotes: 0

Ryne Everett
Ryne Everett

Reputation: 6829

You shouldn't need to explicitly capture the URL for your use case. The following should work for your location block:

location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_set_header Host $host;
}

Upvotes: 1

Related Questions