Esskimo
Esskimo

Reputation: 29

Location directive doesn't seem to be working for some reason

A few days ago I stumbled upon Nginx inside k8s deployment. As I'm relatively new to Nginx I want to understand how it works - so I made my own dev deployment.

The thing is I can't get my nginx.conf to work as I intended:

  1. When you access the /healthz endpoint, return 200 (health check for the k8s)
  2. Redirect any other http trafic to https

Here's my current nginx.conf:

server {
  listen 80;
  listen [::]:80;
  server_name _;

  location /healthz {
    return 200 "healthy";
  }
  return 301 https://$host$request_uri;

  access_log off;
  error_log /usr/share/nginx/web/logs/http_error.log error;
}

server {
  listen 443 ssl http2 default_server;
  listen [::]:443 ssl http2 default_server;
  server_name company.com;

  root /usr/share/nginx/web;
  index index.html;

  access_log off;
  error_log /usr/share/nginx/web/logs/ssl_error.log error;

  ssl_certificate /usr/share/nginx/web/cert/company.crt;
  ssl_certificate_key /usr/share/nginx/web/cert/company.key;
}

Response I'm getting (I've removed the IP adresses):

[error] 28#28: *2 open() "/usr/share/nginx/web/healthz" failed (2: No such file or directory), client: xx.xx.xx.xx, server: company.com, request: "GET /healthz HTTP/2.0", host: "xx.xx.xx.xx", referrer: "http://xx.xx.xx.xx:80/healthz"

Request is on port 80 to /healthz but instead of returning 200, it gets redirected to the https server where it fails

At this point I really don't know why it doesn't work, so please, even if it's some dumb mistake, please feel free to point it out!
What am I doing wrong here?

Upvotes: 0

Views: 105

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15470

All the directives processed by ngx_http_rewrite_module from the server context (including return one) are executed before the same directives from location context. You should define two locations to achieve desired behavior:

server {
    listen 80;
    listen [::]:80;
    server_name _;

    access_log off;
    error_log /usr/share/nginx/web/logs/http_error.log error;

    location / {
        return 301 https://$host$request_uri;
    }
    location /healthz {
        return 200 "healthy";
    }
}

Upvotes: 1

Related Questions