How to do dynamic path routing requests to single root directory and url to /<country_zone>/<actual_url>/* .

I am able to retrive $country_zone value which can be any of (in|uk|us|other) using geoip module.


Request => Response 
/ => /
/ (with geoip country as US) => /us/
/path/ => /path
/path/ (with geoip country as US) => /us/path/
/us/path/ => /us/path/
/us/path/ (with geoip country as US) => /us/path/
/in/* => /*

My codebase is at : /var/www/html (All routes should consider this as a root directory after /

My current nginx config :

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;
    server_name _;

    location  ~  ^/$country_zone {
        alias /var/www/html;
        index index.html index.htm index.nginx-debian.html;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.

        if ($country_zone != in) {
                return 307 /$country_zone;

        add_header X_COUNTRY_ZONE_ID $country_zone;
        try_files $uri $uri/ =404;


PS : I will also proxy the request to another server some day


IFISEVIL (https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/)

Your solution looks rather OK for me. Honestly I don't have a clue what is wrong there.

I would rather code the application to recognise the users browsers default language and display the website or route them according to that. At least that is what we did. URL is always the same, except right after the main domain name where you can spot the country code like you are expecting it.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.