0

I'm trying to achieve some URL rewrite rules in nginx. I use similar regex to capture the interesting groups, it works perfectly in regex101, and in IIS rewrite rules' regex, but not working in nginx map. I don't know exactly if there is a specific syntax for nginx or not, I couldn't find out.

  map $request_uri $new_uri {        
      default '';
      
      # this works without the query string part
      #"~^/r/([\S]+)\.jpg$" http://www.jackli.space/$1.jpg;

      "~^/r/([\S]+).(png|jpg|jpeg)\?a=(\d+)$" http://www.jackli.space/$1.$2?x=$3;
  }

Sample image src url I test with

<img src="r/images/bridge.jpg?a=100" />

Regex 101 for same expression

Mustafa Magdy
  • 1,230
  • 5
  • 28
  • 44
  • Can you show rewrite rule you are trying to use? – Ivan Shatsky Jul 19 '21 at 19:27
  • here is the sample conf file for nginx ```map $request_uri $new_uri { default ''; "~^/r/([\S]+).(png|jpg|jpeg)\?a=(\d+)$" http://www.jackli.space/$1.$2?x=$3; } server { listen 4000; location / { if ($new_uri) { rewrite ^(.*)$ $new_uri permanent; } proxy_pass http://backend:5000; } }``` – Mustafa Magdy Jul 19 '21 at 19:41
  • Try `return 301 $new_uri;` instead of `rewrite` directive. And you'd better add that configuration fragment to your question, markdown formatting in comments isn't suited well for multiline code blocks. – Ivan Shatsky Jul 19 '21 at 20:08
  • @IvanShatsky, I tried this, it is not working. the reason I didn't put the configuration in the question because it is irrelevant, the problem is in the regex not in the configuration. – Mustafa Magdy Jul 19 '21 at 20:16
  • I don't see any errors in your regex. Tested this on my local machine, everything is working as expected (see used nginx config and curl log [here](https://pastebin.com/2Et43daE)). – Ivan Shatsky Jul 20 '21 at 03:45
  • An important update. As you can see in my example, the `Location` header content with the given config is `http://localhost/some/path/image.jpg?x=100?a=100`. Use `rewrite ^ $new_uri? permanent;` or `return 301 $new_uri;` to get correct `http://localhost/some/path/image.jpg?x=100` header value. – Ivan Shatsky Jul 20 '21 at 12:57

1 Answers1

0

You may try this block with named captured groups:

map $request_uri $new_uri {        
   default 0;
      
   # this works without the query string part
   #"~^/r/([\S]+)\.jpg$" http://www.jackli.space/$1.jpg;

   "~^/r/(?<file>\S+)\.(?<ext>png|jpg|jpe?g)\?a=((?<a>\d+)$" http://www.jackli.space/$file.$ext?x=$a;
}
anubhava
  • 761,203
  • 64
  • 569
  • 643