How to Install and Configure Nginx on Ubuntu
Installing Nginx
Installing Nginx is easy. Use the following commands to install Nginx.
sudo apt update
sudo apt install nginx
Configuring Nginx
There are many ways for configuring Nginx depending on use cases. This article shows you how to configure Nginx as a reverse proxy mapping a certain port to another, e.g. port 80
to 8080
.
First, let's remove the default configuration.
sudo rm /etc/nginx/sites-enabled/default
Then, create a new configuration file in /etc/nginx/sites-available
directory. Let say we create mysite
file.
cd /etc/nginx/sites-available
touch mysite
Edit mysite
file using your favorite editor. My favorite one is the vim editor, thus I can use this command.
sudo vim mysite
In the file, add the configuration as follows.
server {
listen 80;
server_name mysite.com;
location / {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $http_host;
proxy_pass "http://127.0.0.1:8080";
}
}
In the above configuration, when someone visits mysite.com
, the request will be redirected to the application published in the port 8080
. You can change those parameters as you need.
Next, we have to create symlink of that file, to the '/etc/nginx/sites-enabled' directory using the following command.
sudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/mysite
Finally, to apply the configuration, restart the nginx service.
sudo service nginx restart
Now you can visit your website.