nginx根据客户浏览器语言跳转不同的页面

nginx 文章 2023-01-09 09:27 842 0 全屏看文

AI助手支持GPT4.0

这是一段可以实现根据客户端浏览器语言跳转到不同页面的 Nginx 代码:

# Redirect based on client browser language
map $http_accept_language $lang {
    default en;
    ~zh zh;
    ~fr fr;
    ~de de;
    ~es es;
}

server {
    listen 80;
    server_name example.com;
    root /path/to/root;

    location / {
        if ($lang = en) {
            return 301 /en/index.html;
        }
        if ($lang = zh) {
            return 301 /zh/index.html;
        }
        if ($lang = fr) {
            return 301 /fr/index.html;
        }
        if ($lang = de) {
            return 301 /de/index.html;
        }
        if ($lang = es) {
            return 301 /es/index.html;
        }
    }
}

该代码首先使用 map 指令将客户端的 Accept-Language HTTP 头部映射到一个变量 $lang,然后使用 if 指令在不同的语言设置下进行重定向。


请注意,这段代码是在 server 块中使用的,因此它只会影响单个服务器。如果你想要在所有服务器中使用该代码,你需要将它放在 http 块中。


-EOF-

AI助手支持GPT4.0