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
- Home
- Blog
- Portfolio
Domain name Structure
Nginx Config File
1 | server |
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:
- try_files $uri: Checks if the request URI is related to an actual file. If it does, Nginx will try to serve that file.
- $uri/: If the first check fails(meaning the requested URI is not a file), Nginx will then check if it relates to a directory. If it does, Nginx will try to serve an index file from that directory.
- /portfolio/index.html: If the first and the second check fails(meaning the requested URI is not a file and directory), Nginx will try to serve
index.html
from the/home/portfolio
directory.
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.