5

I do have an nginx server which responds to several domains and I do want to redirect all request to the main domain.

Example: website responding for xxx xxx.example.com yyy.example.com $hostname for both http and https.

I want to configure the server in such way that all requests to the other domain names will be redirected to xxx.example.com.

sorin
  • 8,016
  • 24
  • 79
  • 103

3 Answers3

26

Most efficient and clean way to do this is to configure two separate server{} blocks - one to do redirects, and another one (with canonical name) to actually handle requests.

Example configuration:

server {
    listen 80;
    listen 443 ssl;

    server_name xxx yyy.example.com $hostname;

    ssl_certificate ...
    ssl_certificate_key ...

    return 302 $scheme://xxx.example.com$request_uri;
}

server {
    listen 80;
    listen 443 ssl;

    server_name xxx.example.com;

    ssl_certificate ...
    ssl_certificate_key ...

    ...
}

Documentation:

Maxim Dounin
  • 3,596
  • 19
  • 23
1

I thinks something along these lines should work:

set $primary_domain "xxx.example.com";
if ($host != $primary_domain) {
    rewrite ^ $scheme://$primary_domain permanent;
}
sorin
  • 8,016
  • 24
  • 79
  • 103
Brenton Alker
  • 470
  • 1
  • 4
  • 7
  • 4
    This is the worst way to solve the problem. http://wiki.nginx.org/Pitfalls#Server_Name and http://nginx.org/en/docs/http/converting_rewrite_rules.html – VBart Nov 08 '12 at 19:24
  • Marking down for the reasons already stated by VBart. In my opinion this should not be the correct answer. – inspirednz Mar 26 '18 at 00:44
1

Here's a variant on Brenton Alker's anser, using the $server_name variable to reuse the value of the server_name directive.

    server_name primary.tld secondary.tld;
    if ($host != $server_name) {
        rewrite ^ $scheme://$server_name permanent;
    }

Or, to keep any query parameters:

    server_name primary.tld secondary.tld;
    if ($host != $server_name) {
        rewrite ^/(.*) $scheme://$server_name/$1 permanent;
    }

Here, $server_name refers to primary server name, which is the first name in the server_name directive, while $host refers to the hostname given in the HTTP request.

Note that the if statement in nginx configuration does not always do what you would expect and its use is discouraged by some. See also https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/