regex - 语言参数的 Nginx URL 重写
问题描述
我最近在运行 LEMP Debian 10 (PHP 7.3.27-1~deb10u1) 的 VPS 中使用 Gettext 本地化了我的 php 网页。页面的本地化版本具有以下 URL:
example.com/index.php?lang=es_ES
和
example.com/index.php?lang=en_GB
等等。
我正在尝试让 Nginx 通过以下方式重写对假文件夹的 URL 请求:
example.com/en/index.php
到=>example.com/index.php?lang=en_GB
example.com/es/index.php
到=>example.com/index.php?lang=es_ES
和
example.com/en/manage/index.php
到=>example.com/manage/index.php?lang=en_EN
example.com/es/manage/index.php
到=>example.com/manage/index.php?lang=es_ES
等等。我尝试了其他 解决方案但没有成功。我的 Nginx 服务器块配置如下:
server {
root /var/www/example.com;
index index.html index.htm index.php;
server_name example.com;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
}
location ~ /(.*)$ {
try_files $uri $uri/ /profiles.php?user-id=$1; #pretty urls for user profiles
}
listen 443 ssl;
}
已经有一个重写:example.com/123
=> example.com/profiles.php?user-id=123
。在不影响已经存在的重写的情况下,我会很感激一些关于使所需的重写工作的见解。谢谢
解决方案
你可以试试这个:
map $lang $locale {
en en_GB;
es es_ES;
}
server {
root /var/www/example.com;
index index.html index.htm index.php;
server_name example.com;
rewrite ^/(?<lang>en|es)(?<suffix>/.*) $suffix?lang=$locale;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
}
location ~ /(.*)$ {
try_files $uri $uri/ /profiles.php?user-id=$1; #pretty urls for user profiles
}
listen 443 ssl;
}
我删除location / { try_files $uri $uri/ =404; }
是因为
try_files $uri $uri/ =404;
是默认的 nginx 行为;location ~ /(.*)
将对任何请求进行数学运算(正则表达式位置的优先级高于前缀位置),并将超越除以结尾的请求之外的任何请求.php
(正则表达式位置从第一个到最后一个检查)。
推荐阅读
- java - 我的快速排序实现使用了太多的比较,但无法确定原因
- c++ - C++ 使用 atoi() 转换单个字符而不是多个字符
- php - 计算轮班工作时间并检测
- javascript - Javascript 从电子表格中读取数据
- kubernetes - 集群内流量的源 IP 地址转换
- java - 基于笛卡尔坐标点积的算法计算地理距离
- python - 找不到 Windows 注册表项,但它在 regedit 中可见
- r - 反应式与观察与观察事件的优势
- ios - 发送电子邮件后如何从 MFMailComposeViewController 获取收件人电子邮件
- python - python - 如何从带有时间戳的数组中获取-python中的年、月、日?