How to setup Nginx as a reverse proxy for Apache on Ubuntu
Today's tutorial, you will learn how to set up Nginx as a reverse proxy server for Apache server on Ubuntu and Debian. I will assume that already you have an existing Apache web server. Using Nginx as a reverse proxy for Apache will allow both servers to work together and allow you to take advantage of the benefits of both servers and hide the actual server. You can easily monitor what traffic goes in and out through the reverse proxy. At the end of this tutorial, you will have a properly configured Nginx reverse proxy server that will handle incoming requests and pass them along to Apache server via a socket.
Change Apache listen port
Firstlty, we need to change the port that Apache listens on. By default, most HTTP websites listen on port 80. If your website uses HTTPS, the default port is 443.
In this tutorial, we will be using port 8080. To change the port, we will use the following command:
1 | sudo vim /etc/apache2/ports.conf |
Then find the Listen 80 line and change it into Listen 8080, then save and close the file.
After that we need to edit the file “000-default.conf” and need to change the listening port to 8080, to edit this file, we will use the following command:
1 | sudo vim /etc/apache2/sites-available/000-default.conf |
Finally, Apply your changes by reloading the Apache web server.
1 | sudo systemctl reload apache2 |
Install and Configure Nginx Reverse Proxy Server
You can install Nginx with the apt package manager on Ubuntu and Debian. To install Nginx on Ubuntu and Debian, we will use the following command:
1
sudo apt install nginx
1 | sudo apt install nginx |
After, Nginx is installed, add the following proxy-related options to your Nginx configuration file. In here we use the default configuration files located at /etc/nginx/sites-available/default. To open this file in your text editor, we will use the following command:
1 | sudo vim /etc/nginx/sites-available/default |
Now, we need to add the following lines to the file:
1 | server { |
Apply your changes by reloading Nginx:
1 | systemctl restart nginx |
After restaring Nginx, you should check the Nginx status:
1 | sudo systemctl status nginx |
Test Out the Reverse Proxy Server
Navigate to your IP address or domain name. Examine the response header with your Network tab under browser’s developer tools. You will now see that your website is being served from Nginx instead of Apache.
You can still access your website using port 8080. So, we need to block port 8080 from Apache. To do this, we will use the following command:
1 | iptables -I INPUT -p tcp --dport 8080 ! -s {your ip or domain} -j REJECT --reject-with tcp-reset |