tchap
tchap

Reputation: 3432

Redirect only the root of the top domain in a wildcard server block

I have a Nginx instance running, serving multiples sites under a common domain: cloud.example.org. For example, I serve website.cloud.example.org and admin.cloud.example.org.

I want to redirect cloud.example.org to website.cloud.example.org. But only the root /; So :

My configuration is as follows (I omit some irrelevant parts, like ssl):

    server {
        listen 443 ssl http2;

        server_name .cloud.example.org;

        location = / {
            if ($http_host = cloud.example.org) {
                return 301 https://website.cloud.example.org;
            }
            proxy_pass         http://my-upstream-server;
            proxy_redirect     off;
            proxy_set_header   Host $host;
        }

        location / {
            proxy_pass         http://my-upstream-server;
            proxy_redirect     off;
            proxy_set_header   Host $host;
        }
    }

This configuration achieves exactly what I want, but having twice the same proxy block seems to me quite a hack. Is there a better way to do it ?

And moreover, I use a if, and I know it's not ideal (https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/), so I would really like to find another solution if possible

Thanks a lot !

Upvotes: 1

Views: 50

Answers (1)

Richard Smith
Richard Smith

Reputation: 49772

You can avoid the if statement by using two server blocks. And to avoid duplicating code, use the include directive and place the common lines of code into a separate file.

For example:

server {
    server_name cloud.example.org;
    location = / {
        return 301 https://website.cloud.example.org;
    }
    include /path/to/common.conf;
}
server {
    server_name .cloud.example.org;
    include /path/to/common.conf;
}

And in the common.conf file:

listen 443 ssl http2;
location / {
    proxy_pass         http://my-upstream-server;
    proxy_redirect     off;
    proxy_set_header   Host $host;
}

Upvotes: 1

Related Questions