nginx – How to Fix 400 Bad Request (Invalid Hostname) Error

nginx

I've configured nginx as a front-end load-balancer across three nodes of a web application I've constructed. nginx continually returns 400/bad request – invalid hostname errors regardless of the values i use in upstream.server and server.server_name. I've tried localhost and 127.0.0.1 for both of those values and issued requests using matching cURL/Postman requests to no avail.

I've also tried setting the value for server.server_name including the port number to better match the incoming HTTP HOST header to no avail.

nginx.conf

events {
  worker_connections  1024; 
}

http { 
  upstream myapp {
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
    server 127.0.0.1:8003;
  }

  server {
    listen 8000;
    server_name 127.0.0.1;
    location / {
      proxy_pass http://myapp;
    }
  }
}

cURL requests result in the following (no difference between using localhost and 127.0.0.1).

C:\>curl -v http://127.0.0.1:8000/
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0)
> GET / HTTP/1.1
> Host: 127.0.0.1:8000
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 400 Bad Request
< Server: nginx/1.17.1
< Date: Mon, 22 Jul 2019 14:29:22 GMT
< Content-Type: text/html; charset=us-ascii
< Content-Length: 334
< Connection: keep-alive
<
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>
</BODY></HTML>
* Connection #0 to host 127.0.0.1 left intact

Best Answer

Try with this configuration:

events {
  worker_connections  1024; 
}

http { 
  upstream myapp {
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
    server 127.0.0.1:8003;
  }

  server {
    listen 8000;
    server_name 127.0.0.1;
    location / {
      proxy_pass http://myapp;
      proxy_set_header Host $host;
    }
  }
}
Related Topic