Beginner Fundamentals

The listen Directive and Ports

The listen directive tells a server block which address and port to accept connections on. It is one of the first things you set for any site.

Basic Ports

HTTP uses port 80 and HTTPS uses port 443:

server {
    listen 80;
    server_name example.com;
}

Binding to a Specific Address

By default Nginx listens on all network interfaces. You can restrict it to one IP:

listen 127.0.0.1:8080;
listen 192.168.1.10:80;

Listening on 127.0.0.1 makes the server reachable only from the local machine, which is handy for internal services.

The default_server

When several server blocks share a port, Nginx uses server_name to choose one. If no name matches, it falls back to the server marked default_server:

server {
    listen 80 default_server;
    server_name _;
    return 444;
}

server {
    listen 80;
    server_name example.com;
    root /var/www/example;
}

Here the first block catches any unknown host and closes the connection with 444. The second block handles real traffic for example.com.

IPv6

To accept IPv6 connections, add a second listen line:

listen 80;
listen [::]:80;

Only one server block per port should carry default_server.