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
Best Answer
The
@handler
location will rewrite the URI to/index.php
which is then redirected to/en/index.php
, which (if it doesn't exist) invokes the@handler
location.Read this document because you need something to handle PHP. The redirect loop is caused because the file or handler does not exist. You need to define a location to handle PHP files, either another regex location or your named location.