James John – Software Engineer

Using Nginx as Reverse Proxy for Apache in Ubuntu 14.04

For sure Apache is a cool Web Server because of mods being available to tweak to anything you want as long as you provide it’s food which is memory! But the evolving of Nginx seem to start knocking of Apache because it’s less memory consuming and faster, what if your site already run Apache and you still wanna keep Apache but you really need that Nginx to reduce your memory consumption. It’s easy, just place Nginx in front of Apache i.e. using Nginx as a reverse proxy for Apache since Nginx is good and fast in serving static files like client side files, we now tell Nginx to process all other files but send PHP to Apache, pretty cool ye? Now let’s do it 🙂

In this post I assume you are already have Apache and PHP set up, if not please read here

Now let’s install Nginx

sudo apt-get update && sudo apt-get install nginx

With a successful installation, we now move to configuration of the virtual host to process user’s request. Create this file

sudo nano /etc/nginx/sites-available/testing

then paste these into it

#lets start configuration
server {
#Set Nginx to listen to 80 which is the default webserver port
listen 80;

#Root directory for serving
root /var/www/html;

#Index files
index index.php index.html index.htm index.xhtml;

#Server name
server_name testing.com;

#Let Nginx server files requested by client
location / {
try_files $uri $uri/ /index.php;
}

#Pass PHP which is a dynamic page and can also be interpreted to Apache
location ~\.php$ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host;
#Finally pass the file to Apache on 8080
proxy_pass http://127.0.0.1:8080;
}

location ~/\.ht {
deny all;
}
}

Explanation was done inside the config file, now save and activate by creating a symbolic link of it in sites-enabled by running

sudo ln -s /etc/nginx/sites-available/testing /etc/nginx/sites-enabled/testing

Configuring Apache

Since Nginx is listening to 80 and we told it to pass the proxy to 8080 which should be where Apache is listening to receive a request. Let’s tell Apache to listen to 8080 and leave 80 for Nginx

sudo nano /etc/apache2/ports.conf

then change Listen 80 to Listen 8080 then save

Restart Apache and Nginx

sudo service apache2 restart && sudo service nginx restart

This

curl -I testing.com

Should return something similar to this

HTTP/1.1 200 OK
Server: nginx/1.4.6 (Ubuntu)
Date: Wed, 18 Feb 2015 21:35:42 GMT
Content-Type: text/html
Content-Length: 11510
Last-Modified: Wed, 18 Feb 2015 21:10:06 GMT
Connection: keep-alive
ETag: "54e4ffae-2cf6"
Accept-Ranges: bytes

Having Server as nginx/1.4.6 (Ubuntu) I hope this helps.

If you wish to manage port access or not making it publicly available, read up Configuring Simple Firewalls in Ubuntu 14.04 Using UFW

James John

Software Engineer