Nginx – Configure domain and multiple subdmains pointing to same root

My wish is to configure my site in a such way that:

  • company.fr
  • collaborator1.company.fr
  • collaborator2.company.fr

the domain and associated subdomains point to the same directory root.

Under the hood I’ll use Symfony and the content displayed will depends on the domain or the subdomain requested.

To achieve this goal I’m wondering if I can have a single configuration file:

server {
    server_name company.fr collaborator1.company.fr collaborator2.company.fr;
    root /var/www/project/public;

    location / {
        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
    }

    location ~ \.php$ {
        return 404;
    }

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;
}

or if I need to split it into multiple server blocks with a similar configuration.

Answer

You might consider using a server_name which includes all possible subdomains, if you plan to add them frequently. This way you don’t have to change the nginx configuration in order to add a subdomain.

server_name *.company.fr;

This includes all subdomains, but does not include company.fr.

server_name .company.fr;

This includes all subdomains, and does include company.fr. Using this would serve any name in the entire domain from this server.

Attribution
Source : Link , Question Author : Adrien G , Answer Author : Michael Hampton

Leave a Comment