Configuring a port-based virtual host (also called a server block) in Nginx is similar to configuring a domain-based virtual host, but you need to specify the listening port. The following is an example port-based virtual host configuration:
Suppose we want to configure two different virtual hosts, one listening on port 8080 and the other listening on port 9090.
Create site configuration files : Create two configuration files in the /etc/nginx/sites-available/ directory, named site_port_8080 and site_port_9090:
sudo nano /etc/nginx/sites-available/site_port_8080
Add the following configuration to the file:
Then create another configuration file:
sudo nano /etc/nginx/sites-available/site_port_9090
Add the following configuration to the file:
Enable the site : Create a symbolic link to link the site configuration file to the enabled site:
sudo ln -s /etc/nginx/sites-available/site_port_8080 /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/site_port_9090 /etc/nginx/sites-enabled/
Check the configuration and restart Nginx : Use the following command to check whether the Nginx configuration is correct:
sudo nginx -t
If there are no errors, reload the Nginx configuration:
sudo systemctl reload nginx
In this example, we created two virtual host configurations with different ports, listening on ports 8080 and 9090 respectively. server_name _; in each virtual host configuration means that all hostnames are accepted. You can define a different server_name in each virtual host configuration as needed to achieve more specific virtual hosts.