【问题标题】:Rewrite URL for nginx with language option使用语言选项重写 nginx 的 URL
【发布时间】:2016-12-14 13:22:10
【问题描述】:

我有 url www.foo.com,它有两种语言 ENCN。我有about.phpproduct.php等页面。

我希望将 URL www.foo.com/about.php?lang=cn 写为 www.foo.com/cn/about 和同样的方式,www.foo.com/en/product 等。

我正在使用 nginx 为这个 php 网站提供服务。

我可以将 .php 文件隐藏为

location / {
    try_files $uri $uri/ $uri.php?$query_string;
}

我试着写这样的东西

location / {
    try_files $uri $uri/$query_string/ $uri.php?$query_string;
}

但不知何故似乎不起作用。

【问题讨论】:

  • 你尝试过类似location / { if ($arg_lang){ rewrite ^ /$arg_lang/$uri permanent; } } 的东西吗?
  • 我没试过。你能详细说明一下吗?我的意思是如何将 lang="cn" 值分配给 $arg_lang 等。
  • 据我所知,nginx 为查询字符串的每个部分提供了一个 $arg_ 变量。所以 $arg_lang 应该是开箱即用的。因此,当在查询字符串中设置 lang 时,应该进行重写。但目前我无法测试它。

标签: php .htaccess nginx url-rewriting nginx-location


【解决方案1】:

在您的文件夹中添加 .htaccess 文件。

.htaccess 文件:

RewriteEngine On    # Turn on the rewriting engine

RewriteRule    ^([A-Za-z0-9-]+)/about/?$    about.php?lang=$1    [NC,L]
RewriteRule    ^([A-Za-z0-9-]+)/product/?$    product.php?lang=$1    [NC,L]

【讨论】:

  • nginx 不支持 .htaccess
【解决方案2】:

我建议如下。在这个示例中,您“松散”了所有其他查询参数。

 location / {
        # for every query string parameter nginx provides a variable
        # $arg_<name>
        if ($arg_lang != ''){
          set $old_lang $arg_lang;
          set $args lang='';
          set $arg_lang '';
          # questionmark after $uri drops all query params
          rewrite ^ /$old_lang$uri? redirect; # or permanent
        }
    }

【讨论】:

  • 没用。但是,谢谢我知道$arg_变量
猜你喜欢
  • 2016-06-27
  • 1970-01-01
  • 2012-12-03
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
相关资源
最近更新 更多