【问题标题】:How can I make multi language config in Nginx?如何在 Nginx 中进行多语言配置?
【发布时间】:2018-02-28 15:50:56
【问题描述】:

我有关注 Nginx 配置 default.conf:

map $http_accept_language $browser_lang {
        default en;
        ~ru ru;
}
map $cookie_lang $lang {
    default $browser_lang;
    ~en en;
    ~ru ru;
}

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;

        try_files $uri $uri/ /index.html;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

我该怎么做:

1) 将所有/* 请求传递给/en/*/ru/*,具体取决于语言?

2) 将所有/en/* 传递给/usr/share/nginx/html/<request>?lang=en/ru/* 传递给/usr/share/nginx/html/<request>?lang=ru

3) 如果语言不是enru 的所有/* 请求到/en/*@ 的路径?

【问题讨论】:

    标签: redirect nginx multilingual proxypass


    【解决方案1】:

    您需要为根 url 和您的语言部分应用两个单独的 location 块,如下所示:

    location = / {
        rewrite ^ $scheme://$host/$lang$uri$is_args$args break;
    }
    
    location ~ '^/(?<lang_code>[\w-]{2})' {
        rewrite ^/(?<lang_code>[\w-]{2})/(.*)$ /$1?lang=$lang_code last;
    
        ...
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
        ...
    }
    

    第一个 location 块回答您的问题 1) 和 3),其中根 url 将用来自 map 部分的 $lang 变量重写,最后一个定义您将使用 @默认为 987654326@ 语言。

    第二个location 块是针对您的问题 2) 在哪里接受您的语言参数作为两个字符路径,然后重写您的 url 以满足您的需要。

    此代码可能不是 100% 工作,但它应该给你一个想法。

    更新

    嗯,实际上你可以一次性完成:

    location / {
        if ($uri !~ '^/([a-z]{2})(/.*)?$') {
            rewrite ^ $scheme://$host/$lang$uri permanent;
            rewrite ^/([a-z]{2})(/.*)?$ /$2?lang=$1;
        }
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-28
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多