Sylvain
Sylvain

Reputation: 3100

Location ignored in nginx

I've a simple location in my nginx config but never catched

server {
    listen 80 default_server;
    server_name _;

    location /healthcheck {
        access_log off;
        add_header Content-Type "text/plain";
        return 200 "OK\n";
    }

    return 301 http://www.google.fr;
}

Everytime I go to http://xxx/healthcheck the location is not detected and I'm redirected to Google.

What did I do wrong in my file? Thanks

Upvotes: 0

Views: 843

Answers (3)

sagesolutions
sagesolutions

Reputation: 501

I had the same issue and figured it out! nginx's return doesn't return like in PHP (or other programming languages), it continues to read the file. So, your return is being overwritten with the next one. Instead, you need to add your other return in another location {}

server {
   listen 80 default_server;
   server_name _;

   location = /healthcheck {
      access_log off;
      add_header Content-Type "text/plain";
      return 200 "OK\n";
   }

   location / {
      return 301 http://www.google.fr;
   }
}

Upvotes: 0

Jakub Špunar
Jakub Špunar

Reputation: 11

Please switch 301 to 302 redirect code and use anon mode in browser, or better use curl to check healthcheck url. For example:

curl -IL http://xxx/healthcheck

301 is always a problem when you are testing something.

Change won't be imidiate. Please be patient. Let us know

Upvotes: 1

Arpit Jain
Arpit Jain

Reputation: 1315

The = prefix means that the location specified should exactly match the requested URL.

Here is the working setting

server {
    listen 80 default_server;
    server_name _;
    location = /healthcheck {
        access_log off;
        add_header Content-Type "text/plain";
        return 200 "OK\n";
    }

    return 301 http://www.google.fr;
}

OR

server {
    listen 80 default_server;
    server_name _;
    location /healthcheck {
        access_log off;
        add_header Content-Type "text/plain";
        return 200 "OK\n";
    }
}

Note: Don't forget to reload nginx after all the changes sudo nginx -s reload

Upvotes: 0

Related Questions