nginxlaravel-8ubuntu-20.04php-8.1

Adding Server Block on Nginx for WildCard domains


I have 2 domains as D1 "abc.com" and D2 "def.com". I have configured D1 as following sever block on Nginx.

server {
    listen 80;
    server_name *.abc.com,abc.com;
    root /var/www/abc/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
 
    index index.php;
 
    charset utf-8;
 
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
 
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }
 
    error_page 404 /index.php;
 
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }
 
    location ~ /\.(?!well-known).* {
        deny all;
    }
}

It works perfectly fine with D1.
But when configure the same D2 domain as following server block

server {
    listen 80;
    server_name *.def.com,def.com;
    root /var/www/def/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
 
    index index.php;
 
    charset utf-8;
 
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
 
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }
 
    error_page 404 /index.php;
 
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }
 
    location ~ /\.(?!well-known).* {
        deny all;
    }
}

after config running commands as follow:

sudo ln -s /etc/nginx/sites-available/abc.com /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/def.com /etc/nginx/sites-enabled/

sudo nginx -t //gives me ok as output

sudo systemctl reload nginx
sudo systemctl restart nginx

It is redirecting to D1 as "abc.com"
I am using Laravel8, php8.1 and Nginx

Is it required to host apps on 2 different servers? how to achieve this?


Solution

  • You need spacing between each domain name under server_name and not comma.

    Reason why it would work for abc.com is probably it's falling back to default/first config.