nginx location host without www

I have to redirect www.example.com/docs/....pdf to trader.example.com/docs/....pdf on an existing Project. The same applies to *.biz. I have no Idea how can i extract the wwww-Part from $host-Variable.

server {
        listen 80;
        server_name www.example.com www.example.biz;

        location /docs {
                        root /data/http/example/docs;
                        rewrite ^ $scheme://trader.$host$request_uri;
        }
}

Does anyone have any idea how I can solve this?


Welcome to ServerFault.

You may use map directive to extract part of the $host value, like the following...

map $host $tld {
    default $host;
    '~^www\.(?<domain>.*)$' $domain;
}

server {
    listen 80;
    server_name www.example.com www.example.biz;

    location /docs {
        root /data/http/example/docs;
        return $scheme://trader.$tld$request_uri;
    }
}

map directive helps to extract the value of $tld that doesn't contain www. part of the URL. As an off-topic, it is not necessary to use rewrite statement. Since, there is no evaluation of regular expression in the above code, return is preferred for faster execution of statement.


You could remove all www from your domains. This configuration should help.

server {
    server_name www.example.com;
    return 301 $scheme://example.com$request_uri;
}

server {
    server_name www.example.biz;
    return 301 $scheme://example.biz$request_uri;
}

server {
        listen 80;
        server_name example.com example.biz;

        location /docs {
                        root /data/http/example/docs;
                        rewrite ^ $scheme://trader.$host$request_uri;
        }
}

Update: If you prefer to drop the www from multiple host names, you can add into the server block that would catch the host names (note: where possible the above is better).

if ($host ~* www\.(.*)) {
  set $host_without_www $1;
  rewrite ^(.*)$ $scheme://$host_without_www$1 permanent; #1
  #rewrite ^ $scheme://$host_without_www$1request_uri permanent; #2
}