Tutorial: Apache 2.4 as reverse proxy
The proxy will serve both web applications from their own virtual host configuration. These may be on the same machine as shown below using the loop-back addresses 127.0.0.1 and 127.0.0.2 or on different machines if you use their (internal) IP addresses.
1
2
3
| Site: http://www.yourwebsite.com/ App1: http://www.yourwebsite.com/app1 = http://127.0.0.1/app1 App2: http://www.yourwebsite.com/app2 = http://127.0.0.2/app2 |
1
2
3
4
5
6
7
| maurits@nuc:/var/www/html$ ll total 28 drwxr-xr-x 4 root root 4096 Dec 1 21:43 ./ drwxr-xr-x 3 root root 4096 Apr 21 2014 ../ -rw-r--r-- 1 root root 11510 Apr 21 2014 index.html drwxr-xr-x 2 root root 4096 Dec 1 21:45 app1/ drwxr-xr-x 2 root root 4096 Dec 1 21:45 app2/ |
Setting up the reverse proxy in Apache 2.4
What we are going to do is setup a reverse proxy. First we load the “proxy_http” module in Apache 2.4 using:
1
2
| sudo a2enmod proxy_http sudo service apache2 restart |
1
2
3
4
5
6
7
| <VirtualHost *:80> ServerName www.yourwebsite.com DocumentRoot /var/www/html ProxyPreserveHost On ProxyPass /app1 http://127.0.0.1/app1 ProxyPass /app2 http://127.0.0.2/app2 </VirtualHost> |
1
2
3
4
5
| <VirtualHost 127.0.0.1:80> ServerName www.yourwebsite.com DocumentRoot /var/www/html ... </VirtualHost> |
1
2
3
4
5
| <VirtualHost 127.0.0.2:80> ServerName www.yourwebsite.com DocumentRoot /var/www/html ... </VirtualHost> |
1
2
| sudo a2ensite yourwebsite-proxy yourwebsite-app1 yourwebsite-app2 sudo service apache2 reload |
Showing the correct remote IP address
It is important to understand that in the above setup, the proxied web application will only see a different “REMOTE_ADDR” environment variable, since there is absolutely no rewriting going on. The real visitor address is passed along in “X-Forwarded-For” header. This is a comma separated list and the last entry holds the real client IP address.If you are on Apache 2.4, like in Ubuntu 14.04, you can correct the reported remote address by loading the “remoteip” module like this:
1
2
| sudo a2enmod remoteip sudo service apache2 restart |
1
2
3
4
5
6
7
| <VirtualHost 127.0.0.1:80> ServerName www.yourwebsite.com DocumentRoot /var/www/html RemoteIPHeader X-Forwarded-For RemoteIPInternalProxy 127.0.0.0/8 ... </VirtualHost> |
Adding headers to the upstream request
We want to make Apache2 add upstream headers and therefor we need to load the “headers” module in Apache 2.4 using:
1
2
| sudo a2enmod headers sudo service apache2 restart |
1
2
3
4
5
6
7
8
9
| <VirtualHost *:80> ServerName www.yourwebsite.com DocumentRoot /var/www/html ProxyPreserveHost On RewriteEngine On RequestHeader add X-SSL off RewriteRule ^/app1/(.*) http://127.0.0.1/app1/$1 [P,L] RewriteRule ^/app2/(.*) http://127.0.0.2/app2/$1 [P,L] </VirtualHost> |
If you have any questions, please use the comments below.
No hay comentarios:
Publicar un comentario