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.

up vote -1 down vote accepted

I thinks something along these lines should work:

set $primary_domain "xxx.example.com";
if ($host != $primary_domain) {
    rewrite ^ $scheme://$primary_domain permanent;
}

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:

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/

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.