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.

3 Answers 3

1

I thinks something along these lines should work:

set $primary_domain "xxx.example.com";
if ($host != $primary_domain) {
    rewrite ^ $scheme://$primary_domain permanent;
}
2
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:

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/

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .