4

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?

Alexander Tolkachev
  • 4,608
  • 3
  • 14
  • 23
Sirko.uhl
  • 43
  • 3
  • Duplicate?! The OP wanted to extract the top-level-domain portion without www part in the hostname. How can it relate to a redirect question? – Pothi Kalimuthu Jul 04 '19 at 02:50
  • By marking it as duplicate, serverfault is discouraging similar questions (I don't mean duplicate questions) and unique answers. If anyone comes across this question and this comment and if you feel that this question shouldn't be marked as duplicate, please click "reopen" link just below the tags ("nginx" and "configuration"). Thanks. – Pothi Kalimuthu Jul 04 '19 at 03:00

3 Answers3

4

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.

Pothi Kalimuthu
  • 6,117
  • 2
  • 26
  • 38
2

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
}
Alexander Tolkachev
  • 4,608
  • 3
  • 14
  • 23
0

This is the way I use and it works great:

server
{
    if ($host ~* ^www\.(.*)) {
        set $host_without_www $1;

        rewrite ^(.*) https://$host_without_www$1 permanent;
    }
}
Sinan Eldem
  • 101
  • 2