5

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?

1
  • Post the logs that you see in the nginx access/error logs Commented Feb 5, 2018 at 9:18

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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;.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.