Nginx Config Location Regex With Language Code In

2019-07-14 06:48发布

问题:

Trying to achieve constant language code in url's 1st segment with nginx regex location configuration and could not find the correct syntax.

Necessary result:

  • example.com stays example.com
  • example.com/en stays example.com/en
  • example.com/en/ stays example.com/en or example.com/en/ (don't care)
  • example.com/en/etc stays example.com/en/etc

  • example.com/etc changes to example.com/en/etc
  • example.com/etc/segment changes to example.com/en/etc/segment



    Currently I have found out this code but it still stuck in somewhere. It makes permanent loop and doesn't not use $1 argument.

    location ~ "^/(?![a-z]{2}/)(.+)$" {
        rewrite / /en/$1 permanent;
    }
    
    #Using handler here for removing index.php in uri (example.com/index.php -> example.com);
    location / {
        index index.htm index.html index.php;
        try_files $uri $uri/ @handler;
    }
    
    location @handler {
        rewrite / /index.php?$query_string;
    }
    



UPDATE: Answer can be found in this question: https://stackoverflow.com/a/33913261/2662849