是否可以在Nginx中循环块并使用变量?

oalqel3c  于 2023-06-05  发布在  Nginx
关注(0)|答案(1)|浏览(190)

我想做的是将传入URL的/locale/部分替换为等效的查询字符串。我想在我的反向代理中做这件事,那就是Nginx。
考虑以下Nginx代码:

include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    location /
    {
        proxy_pass http://localhost:3500;
    }

    location = /fa
    {
        proxy_pass http://localhost:3500;

        rewrite ^/fa/(.*)$ /$1?locale=fa;
        rewrite ^/fa /?locale=fa;
    }

    location /fa/
    {
        proxy_pass http://localhost:3500;

        rewrite ^/fa/(.*)$ /$1?locale=fa;
        rewrite ^/fa /?locale=fa;
    }

    location = /en
    {
        proxy_pass http://localhost:3500;

        rewrite ^/en/(.*)$ /$1?locale=en;
        rewrite ^/en /?locale=en;
    }

    location /en/
    {
        proxy_pass http://localhost:3500;

        rewrite ^/en/(.*)$ /$1?locale=en;
        rewrite ^/en /?locale=en;
    }

    location = /ar
    {
        proxy_pass http://localhost:3500;

        rewrite ^/ar/(.*)$ /$1?locale=ar;
        rewrite ^/ar /?locale=ar;
    }

    location /ar/
    {
        proxy_pass http://localhost:3500;

        rewrite ^/ar/(.*)$ /$1?locale=ar;
        rewrite ^/ar /?locale=ar;
    }

    location = /ru
    {
        proxy_pass http://localhost:3500;

        rewrite ^/ru/(.*)$ /$1?locale=ru;
        rewrite ^/ru /?locale=ru;
    }

    location /ru/
    {
        proxy_pass http://localhost:3500;

        rewrite ^/ru/(.*)$ /$1?locale=ru;
        rewrite ^/ru /?locale=ru;
    }

    location = /tr
    {
        proxy_pass http://localhost:3500;

        rewrite ^/tr/(.*)$ /$1?locale=tr;
        rewrite ^/tr /?locale=tr;
    }

    location /tr/
    {
        proxy_pass http://localhost:3500;

        rewrite ^/tr/(.*)$ /$1?locale=tr;
        rewrite ^/tr /?locale=tr;
    }

正如你所看到的,很多代码都是重复的。这包括location块、regex和proxy_pass指令等。我想把这部分弄干。
基本上,这部分在每个区域设置中重复:

location = /tr
    {
        proxy_pass http://localhost:3500;

        rewrite ^/tr/(.*)$ /$1?locale=tr;
        rewrite ^/tr /?locale=tr;
    }

    location /tr/
    {
        proxy_pass http://localhost:3500;

        rewrite ^/tr/(.*)$ /$1?locale=tr;
        rewrite ^/tr /?locale=tr;
    }

有没有一种方法可以在区域设置上循环而不重复本节?

toiithl6

toiithl61#

rewrite语句可以捕获正则表达式中的locale,例如:

rewrite ^/(\w\w)/(.*)$ /$2?locale=$1 break;
rewrite ^/(\w\w)$ /?locale=$1 break;

使用正则表达式选择具有区域设置的任何URI,例如:

location ~ ^/(fa|en|ar|ru|tr)(/|$) { ... }

或者更一般地(如果这对你有效):

location ~ ^/\w\w(/|$) { ... }

示例:

location / {
    proxy_pass http://localhost:3500;
}
location ~ ^/\w\w(/|$) {
    rewrite ^/(\w\w)/(.*)$ /$2?locale=$1 break;
    rewrite ^/(\w\w)$ /?locale=$1 break;
    proxy_pass http://localhost:3500;
}

相关问题