基于 $request_uri 的 nginx 重定向

Avi*_*hat 5 nginx request

在我的默认站点配置文件中,我有以下重定向来强制执行 https :

 server {
    listen       80;
    server_name  www.example.com example.com;
    return       301 https://example.com$request_uri;
 }
Run Code Online (Sandbox Code Playgroud)

我想添加一个子域,但将其重定向到带有参数的站点。例如 fr.example.com --> https://example.com?lang=fr

如果我做:

return       301 https://example.com$request_uri&lang=fr;
Run Code Online (Sandbox Code Playgroud)

无论$request_uri中是否有其他参数,它都会添加 '&lang=fr' 。

如何有条件地定义“?” 或“&”,基于 $request_uri 的内容?

我尝试了以下方法:

server {
    listen       80;
    server_name  fr.example.com;
       if ($request_uri ~ ""){
           return       301 https://example.com?tlang=fr;
       }
        return       301 https://example.com$request_uri&tlang=fr;
}
Run Code Online (Sandbox Code Playgroud)

但就像这样,该网站彻底失败了。

谢谢

Ter*_*nen 1

首先,$request_uri不包含请求的查询参数。

有两种选择:

  1. $args在参数后面添加一个 return lang

return 301 https://example.com?lang=fr&$args:

  1. 使用地图:

http关卡中,您定义地图:

map $args $redirargs {
    "~.+" $args&lang=fr;
    default lang=fr;
}
Run Code Online (Sandbox Code Playgroud)

然后使用

return 301 http://example.com$request_uri?$redirargs;
Run Code Online (Sandbox Code Playgroud)