英文:
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; }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论