Ben
Ben

Reputation: 3357

Multiple subdomain redirect in server block with Nginx

I would like to redirect multiple subdomains on my server to another with Nginx. Here is what I am doing so far:

server {
        listen 80;
        server_name firstsub.example.com;
        return 301 $scheme://firstsub.anothersite.co$request_uri;
}
server {
        listen 80;
        server_name secondsub.example.com;
        return 301 $scheme://secondsub.anothersite.co$request_uri;
}

because I have about 10 subdomains, adding it like that would be really ugly. Is there a way to write several domain redirects in one server block? How?

Upvotes: 1

Views: 1107

Answers (1)

Richard Smith
Richard Smith

Reputation: 49742

If all of the domains have a consistent pattern, you can use a regular expression with the server_name directive.

For example:

server {
    listen 80;
    server_name ~^(www\.)?(?<domain>.+)\.example\.com$;
    return 301 $scheme://$domain.anothersite.co$request_uri;
}

See this document for details.

Upvotes: 2

Related Questions