【问题标题】:Serve a different index page based on a cookie根据 cookie 提供不同的索引页面
【发布时间】:2018-07-24 22:31:58
【问题描述】:

我正在为用户的语言设置一个 cookie,例如“lang=en”。我想将根或 index.htm 请求重写为本地化的 index.htm 文件。这样,如果用户向“/”或“/index.htm”发出请求,如果他设置了“lang=en”cookie,它将重写请求以返回“index_en.htm”文件。我也想有一个后备,所以如果没有设置 cookie,我可以指定一个默认的本地化页面并返回它。我该怎么做?

这是我当前的 NGINX 位置(site_root 是 ansible var):

    location / {
        root {{ site_root }};
        #index  /;
        try_files $uri $uri/ /;     
    }

编辑:

解决方案需要重写,而不是重定向,因为我希望用户仍然看到“example.com/index.htm”或“example.com”,而不是“example.com/index_en.htm”。重写也会阻止额外的请求。

另外,我想使用 cookie 的值,例如“index_{LANG_VALUE}.htm”,使其动态化,因为如果我必须添加新语言,目标是不必编辑此配置文件。

编辑 2:

这是一个可行的解决方案,可能有更好的选择,但这满足我的要求。

    location / {
        root {{ site_root }};

        try_files $uri
                  /index_$cookie_lang.html   #localized index if user cookie "lang" is set
                  /index_en.html             #default localized index
                  /index.html                #default index
                  =404;
    }

【问题讨论】:

    标签: nginx


    【解决方案1】:

    这样的事情应该可以工作。

    location ~ ^/$ {
    
        // for dynamic rewrite
        if ($http_cookie ~* "lang" ) {
            rewrite ^.*$ /index_$cookie_lang.html;
        }
    
        // for fixed redirects..
        if ($http_cookie ~* "lang=en") {
            return         302 https://example.com/index_en.html;
        }
        if ($http_cookie ~* "lang=fr") {
            return         302 https://example.com/index_fr.html;
        }
        ..
    }
    

    【讨论】:

    • 我尝试了你的动态解决方案,我得到了一个 404,并且存在正确的 index_LANG.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多