Nginx is a lightweight web server that has been proven to serve static files faster than Apache. This tutorial will guide you how to install Nginx as reverse proxy over Apache web server.
Requirements
You have installed Apache on your server. Apache is already running a site on port 80.
Change Apache listening port
Edit /etc/apache2/ports.conf
to make Apache listening to port 8080 instead of default port 80.
Find following line:
1 2 3 |
NameVirtualHost *:80 Listen 80 |
Change it to:
1 2 3 |
NameVirtualHost *:8080 Listen 8080 |
Do not forget to your existing vhost listening port in /etc/apache2/sites-enabled/*
Change:
1 2 |
<VirtualHost *:80> |
To:
1 2 |
<VirtualHost *:8080> |
Disable Unuse modules in Apache
Since HTTP requests is now handled by Nginx, we can disable KeepAlive in Apache. Edit /etc/apache2/apache2.conf
and change:
1 2 |
KeepAlive Off |
Also, run following commands to disable unused modules.
1 2 3 4 5 6 |
a2dismod deflate a2dismod cgi a2dismod autoindex a2dismod negotiation a2dismod ssl |
Install forward module
Install mod_rpaf in Apache to forward visitor IP to Apache. Otherwise, your scripts will read REMOTE_ADDR values as server IP.
1 2 |
apt-get install libapache2-mod-rpaf |
Stop Apache service
1 2 |
/etc/init.d/apache2 restart |
Setup Nginx
Install Nginx.
1 2 |
apt-get install nginx |
Remove default vhost to prevent conflicts.
1 2 |
rm -rf /etc/nginx/sites-enabled/* |
Create a new default vhost:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
cat >/etc/nginx/sites-available/000-default <<EOF server { access_log off; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_pass http://127.0.0.1:8080; } } EOF ln -s /etc/nginx/sites-available/000-default /etc/nginx/sites-enabled/000-default |
Create vhost for existing website to forward request to Apache:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
cat >/etc/nginx/sites-available/domain.com <<EOF server { server_name www.domain.com domain.com; root /var/www/domain.com/; access_log off; # Static contents location ~* ^.+.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$ { expires max; } # Dynamic content, forward to Apache location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_pass http://127.0.0.1:8080; } } EOF ln -s /etc/nginx/sites-available/domain.com /etc/nginx/sites-enabled/domain.com |
Restart Nginx and it’s done.
1 2 |
/etc/init.d/nginx restart |