I am hosting a Rails app on Nginx that is accessible through a defined set of domains. For each of these domains I also want to forward www to non-www. Right now my config file looks like this:
server {
listen 80;
server_name www.domain1.com;
rewrite ^ http://domain1.com$uri permanent;
}
server {
listen 80;
server_name www.domain2.com;
rewrite ^ http://domain2.com$uri permanent;
}
server {
listen 80;
server_name www.domain3.com;
rewrite ^ http://domain3.com$uri permanent;
}
server {
listen 80;
server_name domain1.com domain2.com domain3.com;
root /home/rails/apps/myapp/current/public;
passenger_enabled on;
}
So I have to repeat the part that forwards www to non-www for every domain and add that domain as a server_name to the last server {} directive. Right now I have about 15 domains configured like that and there are more to come, meaning it will get more and more cumbersome to maintain that list. What I would really like would be something like this: (pseudocode)
%domains = [domain1.com, domain2.com, domain3.com]
for each %domain in domains
server {
listen 80;
server_name www.%domain;
rewrite ^ http://%domain$uri permanent;
}
end
server {
listen 80;
server_name %domains;
root /home/rails/apps/myapp/current/public;
passenger_enabled on;
}
One thing I cannot do is use a wildcard for forwarding ALL domains to their non-www variant, since I host other domains on the same Nginx as well. It has to be a defined set of domains.
Is there any way to accomplish anything like that? Or another way I could clean up the config file? All suggestions welcome!
EDIT:
With the help of rzab's answer I could get it down to this:
map $http_host $non_www_host {
www.domain1.com domain1.com;
www.domain2.com domain2.com;
www.domain3.com domain3.com;
}
server {
listen 80;
server_name www.domain1.com www.domain2.com www.domain3.com;
rewrite ^ http://$non_www_host$uri permanent;
}
server {
listen 80;
server_name domain1.com domain2.com domain3.com;
root /home/rails/apps/myapp/current/public;
passenger_enabled on;
}
It's less to write (maybe not with 3 domains but with more than 5 or more definitely) but now I have to add a new domain to 3 places! Is there any way I can just have the list of domains in one place?