nginx http redirect wrongfully doubles the parameters (via AWS ELB)

Casper asked:

For example, when I browse

nginx redirects me to

Now if I continue to redirect, I get

It keeps doubling the parameters, not sure what did I do wrong.

My nginx config:

server {
  listen 80;
  listen 443 ssl;

  server_name {{ .SERVER_NAME }} www.{{ .SERVER_NAME }};

  ssl_certificate     /etc/ssl/nginx.crt;
  ssl_certificate_key /etc/ssl/nginx.key;

  if ($http_x_forwarded_proto != "https") {
      rewrite ^(.*)$ https://$server_name$REQUEST_URI permanent;

  # Nginx will reject anything not matching /
  location / {
    # Reject requests with unsupported HTTP method
    if ($request_method !~ ^(GET|POST|HEAD|OPTIONS|PUT|DELETE|PATCH)$) {
      return 405;

    # Only requests matching the whitelist expectations will
    # get sent to the application server
    proxy_pass http://site_container:5000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_redirect     off;
    proxy_set_header   Host                 $http_host;
    proxy_set_header   X-Real-IP            $remote_addr;
    proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Proto    $http_x_forwarded_proto;
    proxy_set_header   X-Forwarded-Port     $http_x_forwarded_port;
    proxy_cache_bypass $http_upgrade;

This is an ECS architecture with both nginx and app containers on the same EC2 instance.

My answer:

The rewrite directive appends the query string to the replacement URL by default, in a manner similar to Apache’s [QSA]. From the documentation:

If a replacement string includes the new request arguments, the previous request arguments are appended after them. If this is undesired, putting a question mark at the end of a replacement string avoids having them appended, for example:

rewrite ^/users/(.*)$ /show?user=$1? last;

But, that’s not how you should fix the problem.

This has a further problem, in that the http to https redirect is inefficient. This if has to be evaluated on every request, and the rewrite has a gratuitous regex. See Taxing Rewrites for more information.

Instead, you should have a completely separate server block for HTTP versus HTTPS, and remove the if/rewrite from the HTTPS server block entirely.

server {
  listen 80;
  listen [::]:80; # You also forgot this...

  server_name {{ .SERVER_NAME }} www.{{ .SERVER_NAME }};

  return 301 https://{{ .SERVER_NAME }}$request_uri;

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.