微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

语言参数的 Nginx URL 重写

如何解决语言参数的 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 to=> example.com/index.PHP?lang=en_GB

example.com/es/index.PHP to=> example.com/index.PHP?lang=es_ES

example.com/en/manage/index.PHP to=> example.com/manage/index.PHP?lang=en_EN

example.com/es/manage/index.PHP to=> example.com/manage/index.PHP?lang=es_ES

等等。 我试过 other solutions 没有成功。我的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 ~ /(.*) 将对 any 请求进行数学运算(正则表达式位置比前缀位置具有更高的优先级)并且会超越除以 .php 结尾的请求之外的任何请求(正则表达式位置从第一个开始检查到最后)。
,

使用重写语句删除前缀并添加语言参数。您可能需要两个重写语句,因为语言参数是唯一的。

有多种方法可以构建此结构,例如使用单独的前缀位置:

location ^~ /en/ {
    rewrite ^/en(/.*)$ $1?lang=en_GB last;
}
location ^~ /es/ {
    rewrite ^/es(/.*)$ $1?lang=es_ES last;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。