dingalingchickenwiing
dingalingchickenwiing

Reputation: 1997

Nginx 301 Redirect by variable

I am setting up a 301 redirect server for the websites I host. When I get a new customer, I don't want to go edit the domain list in the server block below. Instead of a hard-coded domain in the nginx configuration, I want to redirect anydomain-here.com to 301 -> www.anydomain-here.com

All domains that are bare (ie domain.com) will be redirected to www.domain.com

server {
  server_name domain-requested.com;
  rewrite ^/(.*)$ http://www.domain-requested.com/$1 permanent;
}

In the example above, is it possible to change domain-requested to a variable? This would allow the server to redirect any site that doesn't have a subdomain, such as www.

Upvotes: 0

Views: 3059

Answers (2)

Cole Tierney
Cole Tierney

Reputation: 10314

You could use a map to set a variable if a bare domain was used:

map $host $anydomain_here {
    # capture bare domain & store in variable $anydomain_here
    ~^(?<anydomain>[^\.]+)\.com$ $anydomain;
}

server {
    listen  80  default_server;
    server_name _;

    if ($anydomain_here) {
        # redirect if a bare domain was matched
        return 301 $scheme://www.$anydomain_here.com$uri;
    }
}

Upvotes: 2

Mark Stosberg
Mark Stosberg

Reputation: 13381

You can get rid of at least one hardcoded domain name with Nginx 1.4.6:

 rewrite ^/(.*)$ http://www.$server_name/$1 permanent;

You could abstract that further by putting it an include file, which all server blocks include. You can't do better than that using Nginx alone, because rewrite is not allowed to be declared in the http context to apply to multiple server blocks.

Some other ideas to consider:

  • Use a templating system to manage your Nginx configs.
  • Many DNS provides provide HTTP redirection services, so their web servers would be the one receiving the request and receiving the redirects.

I have used both approaches above myself. The downside to using an DNS providers for HTTP redirection is they don't handle incoming SSL requests, but that's only a downside if you were going to buy and install a second SSL cert just to handle HTTPS redirects on the second domain yourself.

Upvotes: 0

Related Questions