6

I am using $geoip_country_code module of nginx to redirect user based on IP. My config code is as given below-

server {
      listen 80;
      gzip on;
      server_name example.com;
      root html/example;
      location / {
        index index.html;
        try_files /$geoip_country_code/index.html /index.html;
      }
      location ~* \.(gif|jpg|jpeg|png|js|css)$ { }
  }

Idea is to redirect the user based on country for which I have localised otherwise the user goes to default index i.e generic for everyone else. It works perfectly when opened in browser from my country as I have localised for it. But when opened from a different country it shows internal server error. Its not going to default index page.

Can someone point me what am I doing wrong?

async_soul
  • 143
  • 1
  • 8

1 Answers1

4

The last element of the try_files statement is the default action, which is either a URI or a response code. The /index.html starts a search for a new location to process the request, and ends up back at the start, so you have a redirection loop.

You can fix the problem by making /index.html a file term instead. For example:

try_files /$geoip_country_code/index.html /index.html =404;

The =404 is never actioned, because /index.html always exists.

Personally, I would use a generic solution:

try_files /$geoip_country_code$uri $uri /index.html;

See this document for more.

Richard Smith
  • 45,711
  • 6
  • 82
  • 81
  • 1
    Nnginx is driving me nuts. It returns 404 when `/index.html` clearly exists, and outputs nothing in the error log. How exactly do you "make `/index.html` a **file** term instead"? The OP already had `try_files /$geoip_country_code/index.html /index.html;`. – Dan Dascalescu Jun 14 '20 at 06:08
  • 1
    @DanDascalescu Read the linked document. You will see that `try_files` accepts one or more *file* parameters which are processed within the same `location` block, but the **last** parameter is either a response code, named location or an internal URI. In the case of a URI, which looks the same as a file term, but causes Nginx to restart the search for a matching `location`. The problem with the OP was that the `try_files` statement caused a redirection loop. – Richard Smith Jun 14 '20 at 10:16