As mentioned above, we can configure multiple server contexts in the same Configuration File, so how do we configure it to help nginx understand and handle requests as we want.
First, we will use the listen directive to determine which server context is operating on which port. Follow the example below:
http {
server {
listen 80;
server_name nglearns.test;
return 200 "hello from port 80!\n";
}
server {
listen 8080;
server_name nglearns.test;
return 200 "hello from port 8080!\n";
}
}
In the above example, we use the following Directives:
With the above config, we will experiment with the following command for PORT 80
curl nglearns.test:80
Result
# hello from port 80!
Similarly, we experiment with PORT 8080
curl nglearns.test:8080
Result
# hello from port 8080!
After the above example, we see that nginx has handled well for both PORT 80 and 8080.
In addition to using listen, we can also use server_name as a replacement.
Follow the example below:
http {
server {
listen 80;
server_name nglearns.test;
return 200 "your local nglearns!\n";
}
server {
listen 80;
server_name ws.nglearns.test;
return 200 "welcome dear ws.nglearns!\n";
}
}
With the above config, we will experiment with the following command for "nglearns.test"
curl http://nglearns.test
result
# your local nglearns!
Similarly, we experiment with "ws.nglearns.test"
curl http://ws.nglearns.test
result
# welcome dear ws.nglearns!
If there is a domain error, you need to check the hosts file to add two domains to allow them to operate on the system.
192.168.20.20 nglearns.test
192.168.20.20 ws.nglearns.test