Thursday, January 27, 2011

Wildcard records with Nginx to handle custom domains.

Here's my 4, going on 5 hour problem:

I've set up a WordPress multisite instance that's going to be handling sites at domain.com, subdomain.domain.com and customdomain.com. There will be N number of sites using customdomain.com, so I'd prefer not creating records for each. On the server, I have Nginx in front of Apache.

What I'd like to do is set up a wildcard record in Nginx to handle all of the custom domains. Right now, it looks something like this:

server {
    listen 80;
    server_name _;
    root /home/server_user/web/production;
    client_max_body_size 50M;
    client_body_buffer_size 128k;

    location / {
        access_log      off;
        proxy_pass http://localhost:8080;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Host $proxy_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}

With this setup, it will pass requests to Apache and serve the dynamic content but returns 404s for all of the static content. If I change 'server_name' to 'customdomain.com', Nginx starts serving static content again. When I change 'server_name' to '_' or any other catch-all pattern, Nginx falls on its face.

Any ideas?

  • Referring to the official documentation, you have the following possibilities :

    server {
      server_name   example.com  *.example.com  www.example.*;
    }
    
    server {
      server_name _ *;
    }
    
    server {
      server_name example.com *;
    }
    

    Note that this has changed in 0.6.x and is now:

    server {
      server_name _;
    }
    

    Since nginx 0.7.12, an empty server name is supported, to catch the requests without "Host" header:

    server {
      server_name "";
    }
    
    Daniel Bachhuber : Yes, I've read the documentation. When trying an asterisk, though, I get the following validation error: Restarting nginx: [emerg]: server name "*" is invalid in /etc/nginx/nginx.conf:127 configuration file /etc/nginx/nginx.conf test failed
    Martin F : Was outdated information. * cannot be used as of 0.6 and if you use anything older than that then update ASAP!
    From Studer
  • The solution (at least with my configuration):

    In your wildcard record, the 'listen' directive should also include 'default':

    listen 80 default;
    

    Don't add a 'server_name' directive because that will cause things to break in ugly, unexpected ways.

    Props to Max Cutler for helping me figure this out.

0 comments:

Post a Comment