Nginx Web server
Links: 112 Nginx Index
Nginx as a web server¶
- It is typically used as a web server for serving static files.
- It is treated as a web server but the technical term for this is a reverse proxy.
- Gets the content from other servers.
Serving static content.¶
- Since we will be dealing with
http
, we will need anhttp
context. - We might not be needing the
events
context but we need to define it for nginx to work. - Inside
http
context we define theserver
context. root
directive inside theserver
context is the location of a bunch of different files that we would like to serve.- This is all we need to do serve the static content.
-
We cannot directly serve CSS by just including it in the root folder.
- If we do that then it will be served but the
Content-Type
will betext/plain
where as it should betext/css
.
- If we do that then it will be served but the
-
Inside the
http
context we can define the different types using thetypes
context -
But there are so many types that it would get cumbersome.
- Luckily nginx comes
mime.types
file.
- Luckily nginx comes
-
Including
mime.types
in thenginx.conf
folder -
Since they are in the same folder we can just specify the file name but the absolute path of the file at any location like
include /etc/nginx/mime.types;
will also work.
Location Context¶
location
context is inside theserver
context
http {
server {
listen 80;
root /somepath/abc;
location /fruits {
root /somepath/abc;
# location of fruits folder (/somepath/abc/fruits)
}
location /carbs {
alias /somepath/abc/fruits;
}
# now /carbs and /fruits will serve the same thing
}
}
- Location path is automatically appended to root.
alias
doesn't append to the end.
root
appends path, alias
doesn't.
In the above examples we were assuming that we have an index.html
in the folders specified by root
or alias
.
- By default it looks for
index.html
but we can specifytry_files
and specify a bunch of different directories we want it to specify.
http {
server {
location /vegetables {
root /somelocation;
try_files /vegetables/veggies.html /index.html =404;
# if we don't get veggies.html, index.html then give a 404
}
}
}
Redirects and Rewrites¶
- Redirect someone when he goes to a particular path
In a redirect the URL changes but in a rewrite the URL remains the same but different content is served.
rewrite
directive is outside thelocation
context
Last updated: 2022-11-05