October 31, 2023

Nginx multiple websites deployment under a single domain name

Preface

In this post, I will show you how to configure Nginx to host several web pages under a single domain name. I will use my blog and my portfolio as an example here.



Folder Structure



Domain name Structure



Nginx Config File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
server
{
listen 80;
listen 443 ssl http2;
server_name jinchuan.site;
index index.html index.htm default.htm default.html;
root /home/blog; # Web page 1 directory path

location ^ ~/portfolio {
alias /home/portfolio; # Web page 2 directory path
try_files $uri $uri/ /portfolio/index.html; # Web page 2 index page
index index.html;
}

# You can config as many web pages as you like in this way
location ^ ~/anothersite {
alias /home/anothersite; # Web page n directory path
try_files $uri $uri/ /anothersite/index.html; # Web page n index page
index index.html;
}
}

location xxx {…}: This defines a block that is used to match the request defined by xxx.

alias /home/portfolio: Sets the location of files that will be served. When a request matches this location block, Nginx will look for the requested file or directory within this directory.

try_files $uri $uri/ /portfolio/index.html: Tells Nginx how to handle different types of requests:

index index.html: This sets the default file to serve when a directory is requested which is index.html here.

~^: Case-sensitive regular expression match. Pattern after it will be interpreted as a regular expression and the location block will match if the regular expression is true. ^ means start with. Here, it will match any URL that starts with /portfolio.

^~: Case-sensitive exact non-regex that takes precedence over regular expressions. If a location block with ^~ matches, it will be used instead of any regular expression matches.


Eg.

1
2
3
4
5
6
7
8
9
10
11
12
13
# Block 1
location ~ ^/anothersite {
alias /home/anothersite1;
try_files $uri $uri/ /anothersite1/index.html;
index index.html;
}

# Block 2
location ^~/anothersite {
alias /home/anothersite2;
try_files $uri $uri/ /anothersite2/index.html;
index index.html;
}

If the user visits https://xxx.xxx/anothersite it will be matched with block 2 since block 2 uses the ^~ operator which takes precedence over regular expression matches.



Reference

About this Post

This post is written by Andy, licensed under CC BY-NC 4.0.

#Nginx