Alex
Alex

Reputation: 126

Nginx location regex generic

A static site has html files in directories per language http://example.com/en For example locations /en/ (english) /es/ (spanish) The static files includes css are directed to the site root, that works, /en/css/style.css -> directed to /css/style.css

        location ~ "^/en/(img|js|css)" {
            rewrite                   ^/en(.*)$ $1 last;
        }
        location ~ "^/es/(img|js|css)" {
            rewrite                   ^/es(.*)$ $1 last;
        }

If I now want to add 40 languages, i have to duplicate above location 40 times, How would i make this so that i do not have to duplicate the location for every language code, Is it possible to capture the /two letter lang code/ and reuse it in the rewrite?

Many Thanks!

Upvotes: 1

Views: 341

Answers (1)

Richard Smith
Richard Smith

Reputation: 49682

You can't use a capture in the location statement to construct the regular expression in the rewrite statement. Regular expressions are literals and cannot be constructed using variables.

However, you don't need to...

The rewrite statement inside your location block only sees URIs where the value between the first two /s should be ignored.

For example:

location ... {
    rewrite ^/[^/]+(/.*)$ $1 last;
}

If all of the language codes are two characters long, you could generalise further with:

location ~ "^/[a-z]{2}/(img|js|css)" {
    rewrite ^/[^/]+(/.*)$ $1 last;
}

But, there are many other solutions that will work. If these are static files, the rewrite may be unnecessary, for example:

location ~ "^/[a-z]{2}(/(img|js|css).*)$" {
    try_files $1 =404;
}

Upvotes: 1

Related Questions