Programming

Nginx

What is Nginx?

Nginx was written to hold many connections with little memory. It stands at the door of a site. The browser connects to it. It can serve a file from disk or forward the request to Node, PHP, or another port. An HTTPS certificate is often attached here too.

What is Nginx used for?

It is for opening several services neatly behind one domain.

  • Serving a static site
  • A proxy to Node or PHP
  • Ending TLS in one place
  • Separating several domains

What can you do with Nginx?

A server block describes one domain. location says which folder or proxy a path goes to. nginx -t tests the config. If there is an error, do not reload. A working config would break.

Is Nginx hard to learn?

A simple static site is short. The difficulty is the proxy header, a large file, and the certificate path. It can do the same job as Apache, but the config file is different. Do not copy one from the other’s example.

Advantages and limits

Advantage: it is light, strong at proxy and static files, and the docs are plentiful. Limit: a complex condition makes the config hard to read, and a wrong proxy can hide the app. The app’s own log is still needed.

Basic ideas

A worker process holds the connection. root is the static folder. proxy_pass is the address of the app behind it.

  • sites-available stores the config
  • sites-enabled is the active link
  • nginx -t checks
  • systemctl reload nginx refreshes without killing the process

A short example

This block accepts a domain on port 80 and forwards the request to local port 3000. Change the domain to your own name.

server {
    listen 80;
    server_name example.com;
    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

Common questions

  • Are Nginx and Apache the same? Both are web servers. The config and the model differ.
  • Is Nginx a programming language? No. It is the server that receives the request.
  • If you have Node, do you need Nginx? Not always. When there is a domain, TLS, and several services, you usually do.