Wrong or misconfigured rewrite by nginx 1.8

OK9999 asked:

I have the 2 nginx’s conf files ssl.conf and default.conf under /etc/nginx/conf.d/. The first file handles incoming http request. It rewrites the http request to https. And the ssl.conf file handles the https based request.

Below is how, default.conf it looks like

server {
    listen       80 default_server;
    server_name  abc.example.com 123-abc.example.com;

    port_in_redirect off;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;


    set_real_ip_from 127.0.0.1;
    set_real_ip_from 10.0.0.0/8;
    real_ip_header X-Forwarded-For;
    real_ip_recursive on;   

    location /about {
      root /usr/share/nginx/html;
      add_header X-Frame-Options "DENY";
      try_files $uri /about.html;
    }

    location /webapi {
      add_header X-Frame-Options "DENY";
    }

    location / {
      rewrite        ^ https://$server_name$request_uri? permanent;
    }
}

The problem here is,
abc.example.com/to/some/path rewrites to https://abc.example.com/to/some/path This is the expected result.

But

123-abc.example.com/to/some/path also rewrites to https://abc.example.com/to/some/path and NOT to https://123-abc.example.com/to/some/path

I am trying to have 2 URL’s that works the same way by setting 2 different server_names as alias. They are not designed to serve different pages/websites.

My answer:


Here is your rewrite:

      rewrite        ^ https://$server_name$request_uri? permanent;

The problem is that you used $server_name, which is not the HTTP hostname the browser requested, but the first server_name defined in the server block.

To fix this, change it to $http_host, which is the hostname the browser requested.

      rewrite        ^ https://$http_host$request_uri? permanent;

Better yet, don’t use rewrite at all. It’s sufficient to return 301.

      return 301 https://$http_host$request_uri$is_args$args;

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.