Nginx with www and without www

willdanceforfun asked:

I have a server directive with nginx:

    server {
            listen 80;
            server_name mydomain.net;
            root /home/sites/mydomain.net;

            location ~ .php$ {
                    fastcgi_pass    127.0.0.1:9000;
                    include         fastcgi_params;
                    fastcgi_param SCRIPT_FILENAME /home/sites/mydomain.net$fastcgi_script_name;
                    fastcgi_index   index.php;
            }
}

This works great when I access mydomain.net. But nothing here says to apply the stuff if the user tries www.mydomain.net

The searching I have done shows people having a whole other directive listening with a server_name www.mydomain.net, which seems.. not great. e.g.

server {
            listen 80;
            server_name www.mydomain.net;
            root /home/sites/mydomain.net;

            location ~ .php$ {
                    fastcgi_pass    127.0.0.1:9000;
                    include         fastcgi_params;
                    fastcgi_param SCRIPT_FILENAME /home/sites/mydomain.net$fastcgi_script_name;
                    fastcgi_index   index.php;
            }
}

Basically doubling the config code. Or otherwise doing a rewrite.

Is there an lesser way of doing this?

My answer:


You can use multiple names in server_name and even repeat it.

For instance, to answer to three hostnames, you could do something like:

server {
        server_name example.com www.example.com;
        server_name api.example.com;

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.