Fast Nginx Configuration

This is a presentation of how to rapidly configure nginx.

This product is one of the fastest and most used web server on the market. It works mainly on linux installations, but you can pretty much install it everywhere. Unlike apache, while nginx can be used as well as a full fledged web server, it is consistently used as a front service for nodejs installations.

Typical Use

  • One machine
  • Virtual server configured for various urls
  • A number of underlying nodejs applications listening at non privileged port

Requirement: incoming connection to port 80 for each of the virtual url shall go to one of the nodejs applications, as desired.

This is a perfect situation for nginx. It is the only application listening to a privileged port and it is extremely fast in redirecting the requests to other underlying http applications.

For our example, I chose the following:

  • server1.com and server2.com configured in /etc/hosts to point to the current machine
  • nginx exposes two servers, both at port 80, for server1.com and server2.com
  • Also for the sake of the example nginx exposes two servers listening to ports 8081 and 8082 where the actual content resides
  • The two servers listening at port 80 forward to the other two servers that actually serve the content

In real life application, the severs lisening to ports 8081 and 8082 will not be configured under nginx but will be separate nodejs applications

Here is the nginx.conf

  1.  
  2. worker_processes 1;
  3.  
  4. events {
  5. worker_connections 1024;
  6. }
  7.  
  8.  
  9. http {
  10. include mime.types;
  11. default_type text/html;
  12.  
  13. sendfile on;
  14. keepalive_timeout 65;
  15.  
  16. gzip on;
  17.  
  18. server {
  19. listen 8081;
  20. server_name localhost;
  21.  
  22. location / {
  23. root content/server1;
  24. index index.html;
  25. }
  26. }
  27.  
  28. server {
  29. listen 8082;
  30. server_name localhost;
  31.  
  32. location / {
  33. root content/server2;
  34. index index.html;
  35. }
  36. }
  37.  
  38.  
  39. server {
  40. listen server1.com:80;
  41. server_name server1.com www.server1.com;
  42.  
  43. location / {
  44. proxy_pass http://localhost:8081;
  45. }
  46.  
  47. }
  48.  
  49. server {
  50. listen server2.com:80;
  51. server_name server2.com www.server2.com;
  52.  
  53. location / {
  54. proxy_pass http://localhost:8082;
  55. }
  56.  
  57. }
  58.  
  59.  
  60.  
  61. }
  62.