Servidor web nginx con host virtuales y acceso https (Ubuntu server)

1. Instalar nginx

apt install nginx

systemctl status nginx

● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: enabled)
     Active: active (running) since Tue 2024-05-07 09:28:23 -05; 20min ago
       Docs: man:nginx(8)
    Process: 1526 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 1530 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 1531 (nginx)
      Tasks: 2 (limit: 1113)
     Memory: 1.8M (peak: 2.4M)
        CPU: 40ms
     CGroup: /system.slice/nginx.service
             ├─1531 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;"
             └─1532 "nginx: worker process"

May 07 09:28:23 py systemd[1]: Starting nginx.service - A high performance web server and a reverse proxy server...
May 07 09:28:23 py systemd[1]: Started nginx.service - A high performance web server and a reverse proxy server.

2. Configurar un host virtual

2.1. Crear archivo de configuración en sites-available

vim /etc/nginx/sites-available/hi.nethuber.com

server {
        listen 80; # Specify the listening port
        listen [::]:80; # The same thing for IPv6
        root /var/www/hi.nethuber.com/html; # The path to the website files
        index index.html index.htm; # Files to display if only the domain name is specified in the address
        server_name hi.nethuber.com; # Domain name of this site
        location / {
                try_files $uri $uri/ =404;
        }
}

2.2. Crear link en sites-enabled

ln -s /etc/nginx/sites-available/hi.nethuber.com /etc/nginx/sites-enabled/

2.3. Crear el HOME del sitio web (agregar cualquier archivo index.html)

mkdir -p /var/www/hi.nethuber.com/html
chmod -R 755 /var/www

echo "<h1>Hola Mundo</h1>" >  /var/www/hi.nethuber.com/html/index.html

2.4. Reiniciar nginx

systemctl restart nginx
systemctl status nginx

3. nginx como proxy server

Suponga que tenemos corriendo una aplicación python en el puerto 8080, pero ese puerto no está expuesto al público

3.1. Crear archivo de configuración en sites-available

vim /etc/nginx/sites-available/hipy.nethuber.com

server{
       server_name hipy.nethuber.com;
       location / {
           include proxy_params;
           proxy_pass http://127.0.0.1:8080;
       }
}

3.2. Reiniciar nginx

systemctl restart nginx
systemctl status nginx

3.3. Aplicación python basada en FastAPI y corriendo en el puerto 8080