title: Nginx Https Redirect with Trailing Slash and Query Parameters
body: <p>I have an Nginx server config that already redirects <code>http</code> requests to <code>https</code>, but I'm trying to figure out the proper way to modify this code or completely change it to redirect <code>http</code> requests to <code>https</code> <strong>and</strong> add a trailing forward slash <code>/</code>, when the url does not contain one. These redirects should also ensure that query parameters still exist despite the redirect. I have seen where most answers to similar questions to mine have referenced <code>^/(.*)/$</code> as the code for adding a forward slash, but I'm not sure how to use it and if I should use a <code>rewrite</code> over an <code>if</code>. Can anyone help clear up my confusion?</p>
  
  <p><strong>nginx.config:</strong></p>
  
  <pre><code>upstream nodejs {
      server 127.0.0.1:8081;
      keepalive 256;
  }
  
  server {
      listen 8080;
  
      if ($http_x_forwarded_proto = "http") { return 301 https://$host$request_uri; }
  
      location / {
          proxy_pass  http://nodejs;
          proxy_set_header   Connection "";
          proxy_http_version 1.1;
          proxy_set_header        Host            $host;
          proxy_set_header        X-Real-IP   $remote_addr;
          proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      }
  
      gzip on;
      gzip_comp_level 4;
      gzip_types text/html text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
  
  }
  </code></pre>
  
  <p><strong>Goal:</strong></p>
  
  <pre><code>http://www.example.com/page-one -&gt; http://example.com/page-one/
  http://example.com/page-two -&gt; https://www.example.com/page-two/
  https://www.example.com/page-three?page=2 -&gt; https://www.example.com/page-three/?page=2
  </code></pre>