线上海外项目,配置了多语言版本和域名,项目后端的请求都是相同的,一开始每个子域名一个配置文件,要是修改配置,每个子域名配置文件都要修改,管理起来很是麻烦,于是查看 nginx官方文档,发现了 map指令,可以帮我优化成一个配置文件,日志文件也会按照子域名去生成。

nginx配置
使用map将不同的域名映射到对应的语言版本(下面的 test是我做了替换)
#$lang下面用于日志文件生成,当然也有其他用途
map $host $lang {
test.com en;
www.test.com en;
ar.test.com ar;
de.test.com de;
es.test.com es;
fr.test.com fr;
id.test.com id;
in.test.com in;
it.test.com it;
ja.test.com ja;
kr.test.com kr;
ms.test.com ms;
pl.test.com pl;
pt.test.com pt;
ru.test.com ru;
th.test.com th;
vn.test.com vn;
zh.test.com zh;
ph.test.com ph;
}
server {
listen 80 ;
server_name $host;
access_log logs/access-$lang.log main; #使用$lang,按语言生成日志文件
root /usr/local/data/www/;
location / {
index index.php index.html index.htm;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
include fastcgi.conf;
}
}

这样一搞,管理起来方便多了,经过测试完全 ok的,已经上线使用了很久了
后来想使用正则匹配再优化一下,如下
#使用正则匹配
map $host $lang {
defual en;
^(www\.)?(?<lang>[a-z]{2})\.test\.com$ $lang;
}
server {
listen 80;
server_name test.com *.test.com;
if ($lang = "") {
set $lang "en"; # 如果$lang为空,则设置默认值为 "en"
}
access_log logs/access_$lang.log main;
root /usr/local/data/www/;
location / {
index index.php index.html index.htm;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
include fastcgi.conf;
}
}
结果现实很残酷,nginx 版本不支持这种正则,语法检测一直报错,试了几次果断放弃了,还是继续使用上面的配置,不折腾了
nginx map模块文档https://nginx.org/en/docs/http/ngx_http_map_module.html
