Thursday, February 23, 2012

Configure nginx as a Reverse Proxy for Apache

In this tutorial, I will be setting up an Ubuntu 10.04 Server running Apache on port 8080 and nginx on 80. Apache will forbid connections from anything but localhost, and nginx will act as a reverse proxy and forward requests to Apache.

1) Modify /etc/apache2/ports.conf

Find the following lines in /etc/apache2/ports.conf:

NameVirtualHost *:80
Listen 8080


Change them to:

NameVirtualHost *:80
Listen 80


2) Modify /etc/apache2/sites-available/default

(Your distribution might just use apache2.conf, Ubuntu's a bit different, it keeps virtual hosts in separate files)

Change
<VirtualHost *:80>
to
<VirtualHost *:8080>

Now change
<Directory /var/www>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>
to
<Directory /var/www>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order deny,allow
    Deny from all
    allow from 127.0.0.1
</Directory>

(You may also wish to do the same for the "/usr/lib/cgi-bin" directory...)

3) Restart Apache

/etc/init.d/apache2 restart

If you try to access the server on 8080 remotely, you should get a 403 Forbidden.

4) Configure nginx

If you haven't already installed it...

sudo apt-get install nginx

Delete or move /etc/nginx/sites-available/default
Also, create the directory /etc/nginx/logs/

Now, create and edit /etc/nginx/sites-available/default

The file should look like this:

server {
    listen 80;
    access_log /etc/nginx/logs/access.log;

    location / {
        proxy_pass    http://127.0.0.1:8080;

    }
}



Reboot nginx
/etc/init.d/nginx restart

You should be good to go now, try browsing to port 80 on the server and you should get content from Apache, but the server will appear to be running nginx.

Attacks like keep-dead should be a lot less effective against your server now. You can also configure nginx for SSL and not have to worry about configuring SSL for Apache.

It would also be a good idea to drop any external traffic to port 8080 with a firewall, as Apache still responds with a 403 if the firewall doesn't block the port.

You can see the access log at /etc/nginx/logs/access.log


Also, here's some nice examples for nginx configuration, if you're interested in configuring it further: http://wiki.nginx.org/FullExample

No comments:

Post a Comment