【问题标题】:NGINX regular expression to match location with optional parameterNGINX 正则表达式与可选参数匹配位置
【发布时间】:2019-06-28 09:36:12
【问题描述】:

我喜欢用两个可选参数匹配位置,所以它匹配

/images/my.jpg
/images/my.jpg/200
/images/my.jpg/200/
/images/my.jpg/200/400
/images/my.jpg/200/400/

我正在使用三个匹配组,以便可以在 $image、$width 和 $height 变量中获取匹配的部分。

我试过这个查询。它仅在给出完整位置时才有效,但如果缺少其中一个参数则不匹配

~ ^/images/(?<img>.+?)/(?<width>\d+)/(?<height>\d+)?$

我也试过了,完全不行

~ ^/images/(?<img>.+?)?(/?<width>\d+)?(/?<height>\d+)?$

请帮忙 - 我这里有输入数据。 https://regex101.com/r/qU7tI7/6

这里是nginx配置

 server {
    listen       80;
    server_name  f.myhost.com;
    set $sitename f.myhost.com;

    root $root_folder/myhost.com/files;
    set $path_info "";

    location / {
            root   /var/www/myhost.com/app/api/;
            include conf.d/site.template;
            add_header X-test "root";
    }

    location /files {
            root   /var/www/myhost.com/app/;
            include conf.d/site.template;
    }

    location ~ ^/images/(?<img>[^/]+)(/(?<width>\d*))?(/(?<height>\d*))?$ {
    #       root   /var/www/myhost.com/files/;
            alias   /var/www/myhost.com/app/test/$image;
    #       include conf.d/site.template;
            add_header X-test "test";
            add_header X-width "$width";
            add_header X-height "$height";
            add_header X-name "$image";
            image_filter resize $width -;
            image_filter_jpeg_quality 75;
            image_filter_buffer 8M;


    }

 }

【问题讨论】:

  • 试试:^/images/(?&lt;img&gt;[^/]+)(/(?&lt;width&gt;\d*))?(/(?&lt;height&gt;\d*))?$
  • 感谢 Richard,它匹配除了 regex101 的最后一个情况之外的所有情况,但又不匹配 nginx regex101.com/r/qU7tI7/8
  • 我错过了最后一个案例,它需要在 $ 之前再添加一个 /?。你是什​​么意思“不在 Nginx 中”?您的位置是否有冲突?
  • 用我的配置更新帖子
  • 您的配置中有一个错字 - 您在某些地方有 img,在其他地方有 image

标签: nginx nginx-location


【解决方案1】:

试试下面的正则表达式:

/^(\/images\/)([\da-z\.-]+\.[a-z\.]{2,6}|[\d\.]+)\/(\d+)\/(\d+)?$/igm

【讨论】:

    猜你喜欢
    • 2017-01-03
    • 2014-11-11
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多