【问题标题】:NGINX rewrite args without an IF?NGINX 在没有 IF 的情况下重写 args?
【发布时间】:2021-01-11 05:54:29
【问题描述】:

我想将使用 URL 的查询参数类型的旧链接重写为新的 URL 样式。

例如

  1. example.com/page?id=1 -> example.com/page/1
  2. example.com/otherpage?id=1 -> example.com/otherpage/1

目前我使用evil if进行以下配置。

if ($args ~* "id=(.*)") {
  set $w1 $1;
  rewrite .* $scheme://$host/page/$w1? permanent;
}

注意:我使用的是 CloudFront,并且依赖于上面的主机头。

如果上述内容在服务器块中,没有其他位置块 - 这是否符合在 NGINX 配置中对if 的非恶意使用?此外,以上仅支持/page/。使该部分适用于otherpage 和其他页面的任何更好的想法?

我看到了一些其他想法讨论使用地图,但我不太确定如何将它们组合在一起?我的想法是这样的:

map $args_id ?? {
  default ?
  ??
}

...
server {
   ...

   ???
   
}

更新: 根据@Ivan 的回答,这是我的最终解决方案:

server {
  listen 80;
  root /usr/share/nginx/html;

  index index.html index.htm;

  # Handle legacy requests
  if ($args ~* "id=(.*)") {
    set $w1 $1;
    rewrite ^ $scheme://$host$uri/$w1? permanent;
  }
}

【问题讨论】:

    标签: nginx url-rewriting nginx-config


    【解决方案1】:

    您的if 构造并不邪恶。你可以使用类似的东西

    rewrite ^ $scheme://$host$uri/$w1? permanent;
    

    适用于任何页面。如果您想同时处理example.com/page?id=1example.com/page/?id=1,则更复杂的示例:

    map $uri $maybe_slash {
        ~/$      "";
        default  "/";
    }
    ...
    server {
        ...
        rewrite ^ $scheme://$host$uri$maybe_slash$w1? permanent;
        ...
    }
    

    【讨论】:

    • 非常感谢您确认我对 IF 的使用没有恶意,并帮助我更好地理解 $uri 在这种情况下的使用。
    • @shawnjohnson 虽然官方文档说您可以在if 块内使用的唯一安全的东西是return ...rewrite ... last,实际上使用setrewrite ... permanent 或@987654332 @也可以。真正邪恶并且可能导致不可预测的结果是使用任何不属于 ngx_http_rewrite_module 的指令(您可以看到 setrewrite 都是来自该模块的指令)。
    猜你喜欢
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    相关资源
    最近更新 更多