How to setup Nginx server blocks for multiple sites - Ubuntu
Setting up nginx server blocks is a process that allows you to host multiple websites on a single server. It is a useful technique for those who want to host multiple websites or applications on a single machine, as it allows you to use a single IP address and port to host multiple domains. In this article, we will explain how to set up nginx server blocks on a Ubuntu server.
Prerequisites
Step 1
Allow Nginx to pass through your firewall.
1sudo ufw allow 'Nginx HTTP'
Replace
Replace with your domain name to auto generate the correct commands for your system.
Step 2
Create a directory for your site and configuration files.
1sudo mkdir -p /var/www/@{domain}/html
Set the ownership of the directory to the $USER
environment variable.
1sudo chown -R $USER:$USER /var/www/@{domain}/html
This allows you to read, write, and execute the files and lets other users read and execute files.
1sudo chmod -R 755 /var/www/@{domain}
Make a sample page in the directory you just created.
1sudo nano /var/www/@{domain}/html/index.html
Add this sample HTML file
1<html>
2 <head>
3 <title>Welcome to @{domain}!!</title>
4 </head>
5 <body>
6 <h1>Success! The example.com server block is working!</h1>
7 </body>
8</html>
Step 3
Creating the server block
1sudo nano /etc/nginx/sites-available/@{domain}
Add this to the created file. Change the www
to any sub-domain you want.
Port
Replace with the correct port you want to be set.
1server {
2 listen 80;
3 listen [::]:80;
4
5 root /var/www/@{domain}/html;
6 index index.html index.htm index.nginx-debian.html;
7
8 server_name @{domain};
9
10 location / {
11 proxy_pass http://localhost:@{port};
12 proxy_http_version 1.1;
13 proxy_set_header Upgrade $http_upgrade;
14 proxy_set_header Connection 'upgrade';
15 proxy_set_header Host $host;
16 proxy_cache_bypass $http_upgrade;
17 }
18}
Once added save the file and then we need to link the configuration file to the sites-enabled
directory
1sudo ln -s /etc/nginx/sites-available/@{domain}/etc/nginx/sites-enabled/
This will keep both configuration files in sync between sites-available
and sites-enabled
Next to prevent a possible hash bucket memory problem, open /etc/nginx/nginx.conf
.
1sudo nano /etc/nginx/nginx.conf
un-comment the line below in the http
block
1server_names_hash_bucket_size 64;
Step 4
Now everything should be set up, you can run the command to make sure all the formatting is done properly.
1sudo nginx -t
If no warning show up you are good to restart the server.
1sudo systemctl restart nginx
Setting up multiple sites
To configure more than one domain on the same server just repeat steps 2-4.