NGINX正则表达式,以使用可选参数

时间:2019-02-04 15:47:28

标签: nginx nginx-location

我喜欢使用两个可选参数来匹配位置,因此它可以匹配

/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;


    }

 }

1 个答案:

答案 0 :(得分:0)

尝试尝试以下正则表达式:

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