如何在Nginx配置文件中更智能地检测位置?

huangapple go评论67阅读模式
英文:

How to detect location more intelligently in Nginx config file?

问题

我正在尝试使用 location 来检测当前的区域设置并在我的Nginx配置文件中传输(重写)请求。

这是我的配置:

location /ru 
{
    rewrite ^/ru/(.*)$ /$1?local=ru;
	rewrite ^/ru /?local=ru;
}

因此,我打算将 domain.tld/ru/blog 更改为 domain.tld/blog?locale=ru

但我遇到了一个问题。例如,URL domain.tld/russell 会干扰这个配置博客。

我想要能够更具体地使用 location 语法。我想告诉Nginx只有当URL以两个字母 ru 路径段开头时才运行这个块。

我该怎么做呢?

英文:

I'm trying to use location to detect the current locale and transfer (rewrite) the request in my Nginx config file.

This is a my configuration:

location /ru 
{
    rewrite ^/ru/(.*)$ /$1?local=ru;
	rewrite ^/ru /?local=ru;
}

So, I intend to change domain.tld/ru/blog to domain.tld/blog?locale=ru.

But I have encountered one problem. As an example, the URL domain.tld/russell would interfere with this config blog.

I want to be able to get more specific for location syntax. I want to tell Nginx to run this block only and if only the URL starts with a two-letter ru path segment.

How can I do that?

答案1

得分: 2

匹配 /ru/ru/foo,但不匹配 /rufoo,你可以使用正则表达式位置。但要注意,正则表达式位置的评估顺序很重要。

location ~* /ru($|/) { ... }

或者,使用两个位置块:

location = /ru { rewrite ^ /?local=ru; }
location /ru/ { rewrite ^/ru/(.*)$ /$1?local=ru; }
英文:

To match /ru and /ru/foo but not /rufoo, you could use a regular expression location. But note that the evaluation order of regular expression locations is significant.

location ~* /ru($|/) { ... }

Alternatively, use two location blocks:

location = /ru { rewrite ^ /?local=ru; }
location /ru/ { rewrite ^/ru/(.*)$ /$1?local=ru; }

huangapple
  • 本文由 发表于 2023年5月21日 12:47:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定