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 anhttpcontext. - We might not be needing the
eventscontext but we need to define it for nginx to work. - Inside
httpcontext we define theservercontext. rootdirective inside theservercontext 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-Typewill betext/plainwhere as it should betext/css.
- If we do that then it will be served but the
-
Inside the
httpcontext we can define the different types using thetypescontext -
But there are so many types that it would get cumbersome.
- Luckily nginx comes
mime.typesfile.
- Luckily nginx comes
-
Including
mime.typesin thenginx.conffolder -
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¶
locationcontext is inside theservercontext
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.
aliasdoesn'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.htmlbut we can specifytry_filesand 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.
rewritedirective is outside thelocationcontext
Last updated: 2022-11-05