繁体   English   中英

Nginx URL 重写语言参数

[英]Nginx URL rewrite for language parameters

我最近在运行 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

等等。 我尝试了其他解决方案但没有成功。 我的 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; } location / { try_files $uri $uri/ =404; }因为

  • try_files $uri $uri/ =404; 是默认的 nginx 行为;
  • location ~ /(.*)将对任何请求进行数学运算(正则表达式位置的优先级高于前缀位置),并将超越.php结尾的任何请求(正则表达式位置从头到尾检查)。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM