title: Nginx rewrite rule: add trailing slash before question mark
body: <p>In Nginx, how do I add trailing slash before question mark in rewrite rule?</p>
  
  <p>I have succeeded with adding slashes to the end of the URL. A follows:    </p>
  
  <pre><code>http://test/xx --&gt; http://test/xx/
  </code></pre>
  
  <p>But I can't implement adding trailing slash before the question mark. As Follows:</p>
  
  <pre><code>http://test/xx?id=2 --&gt; http://test/xx/?id=2
  </code></pre>
  
  <p>I've tried the following:</p>
  
  <pre><code>server {
  
    listen 34044;
  
    # add trailing slash to url end
    rewrite ^([^.\?]*[^/])$ $1/ permanent;
  
    # add trailing slash before question mark
    rewrite "^(.*)([^/]{1})\?(.*)$" $1$2/?$3 permanent;
  
    location / {
      ...
    }
  }
  </code></pre>
  
  <p>But it doesn't add slash before question mark. </p>
  
  <p>I think, I have a bug in the second regex, but I can't see it. Please help</p>