Configure multiple domains(virtualhost) on nginx webserver
This post assumes that nginx already installed on the server. If its not installed, please refer the following post to install nginx. We assumes that host is ubuntu and installation path is /etc/nginx. You can follow the same post incase of different OS or installation path is different. You may need to alter a bit on the implementation plan.
Assumption:
- Ubuntu Host
- LEMP setup.
- Domain Names(2 or more domains)
Implementation:
Let’s create the required directories first for both the domains
mkdir -p /var/www/domain1.tld/html
mkdir -p /var/www/domain2.tld/html
Change the ownership of the directory. Find out which user nginx service is running on the host.
# grep user /etc/nginx/nginx.conf
www-data
user ;
We may need to modify below command based on output previous output.
chown www-data. /var/www/domain1.tld/html
chown www-data. /var/www/domain2.tld/html
Create virtualhost configuration for both the domains.
cd /etc/nginx/sites-available/
cp default domain1.tld
cp default domain2.tld
Modify each domain virtual host(server blocks) as per our domain. we need to update each domain configuration as per domain name. The following is the configuration of domain1.tld
vi domain1.tld
server {
listen 80;
listen [::]:80;root /var/www/domain1.tld/html; # Modify the documentroot for each domain
index index.html index.php index.htm index.nginx-debian.html;server_name domain1.tld; # Modify the domain name for each domain
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}}
Similarly, the following configuration is for domain2.tld.
vi domain2.tld
server {
listen 80;
listen [::]:80;root /var/www/domain2.tld/html; # Modify the documentroot for each domain
index index.html index.php index.htm index.nginx-debian.html;server_name domain2.tld; # Modify the domain name for each domain
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}}
Create symlink configuration for domain1.tld and domain2.tld.
ln -s /etc/nginx/sites-available/
domain1.tld /etc/nginx/sites-enabled/
ln -s /etc/nginx/sites-available/
domain2.tld /etc/nginx/sites-enabled/
Check for any nginx configuration error.
nginx -t
Once, we confirm that there is no error then we can restart nginx service.
systemctl restart nginx
Create/upload files to domain documentroot( /var/www/domain1.tld/html & /var/www/domain2.tld/html).