In certain scenarios, you might need to configure Nginx to listen on a custom port instead of the default ports like 80 for HTTP and 443 for HTTPS. This article will guide you through the process of configuring Nginx with a custom listening port.
Prerequisites
Before you begin, make sure you have:
- Nginx is installed on your server.
- Administrative access to edit Nginx configuration files.
Step 1: Open Nginx Configuration File
Use a text editor to open the Nginx configuration file. The location of the configuration file can vary depending on your system and setup. Common locations include /etc/nginx/nginx.conf
or /etc/nginx/sites-available/default
.
sudo nano /etc/nginx/nginx.conf
Step 2: Locate the listen
Directive
Within the configuration file, locate the listen
directive. This directive specifies the IP address and port on which Nginx should listen for incoming connections.
server {
listen 80;
# Your other configurations go here
}
In this example, Nginx is configured to listen on the default HTTP port 80.
Step 3: Change the Listening Port
Change the listen
directive to the desired custom port. Choose a port that is not in use by other services and is above the reserved ports range (usually above 1024).
server {
listen 8080;
# Your other configurations go here
}
Here, Nginx is configured to listen on port 8080. Adjust the port number based on your preferences and security considerations.
Save the changes to the configuration file and exit the text editor.
Step 4: Open the custom port through the firewall
Open the custom port you specified for Nginx through the firewall. Let’s use the UFW firewall configuration. Replace 8080
with your chosen custom port.
sudo ufw allow 8080
If you’re using iptables as your preferred firewall configuration, then run the following commands one by one:
sudo iptables -A INPUT -p tcp --dport 8080 -j ACCEPT
sudo service iptables save
sudo service iptables restart
Remember to replace 8080 with your own custom port you’ve defined for Nginx configuration
Step 5: Test Configuration and Reload Nginx
Before applying the changes, it’s crucial to test the configuration for syntax errors.
sudo nginx -t
If the test is successful, reload Nginx to apply the changes.
sudo systemctl reload nginx
Now, Nginx will be listening on the custom port you specified.
Conclusion
Configuring Nginx with a custom listening port is a straightforward process. By adjusting the listen
directive in the Nginx configuration file, you can customize the port to meet your specific requirements. Always ensure that the chosen port is available and does not conflict with other services running on the server.