Sunday, 14 October 2012

A secure home gateway on the Raspberry Pi in four parts. Part two, setting up nginx on the Raspi

I have some very nifty devices lying around in my home:
  • A couple of computers
  • A very smart router with the Tomato firmware
  • A Raspberry Pi model B (the only one you can get right now)
  • A Popcorn Hour A200
Besides that, I have full control over a domain name (waleson.com.).

The amount of cool things you can do with this is enormous. However, until yesterday morning, these devices were working with most of their default settings (BOOOORING). Here's how I made it awesome in one evening.

Part two, nginx on the Raspberry Pi.

  1. Part one - Dynamic DNS
Objective: You want to access the devices inside from outside over the internet. 

Naturally any other linux machine will do, but I have a Raspi lying around. It is energy efficient and fun to play with. Also, the Raspberry Pi is hot on the web, so it does wonders for your Hacker News article or your SEO leads. So if you don't have a Raspberry Pi, please do the substitution to whatever you have yourself, in your head.

I take it you have set-up Debian on a Raspberry Pi. Please use ssh keys as well: http://raspberrypi.stackexchange.com/questions/1686/how-do-i-set-up-ssh-keys-to-log-into-my-rpi

Connect your Raspberry Pi to the network. In your router, assign a static IP lease to the raspberry pi. That is, each time the raspberry connects to the network, the DHCP server in the router will assign it the same IP. Then, still in your router, forward ports 80 and 443 to the IP of the raspberry pi. Now all incoming traffic to your domain name on port 80 (http://) and 443 (https://) will be handled by the raspberry pi. However it does not listen on those ports yet. We need to set up a web server: nginx. Why not apache? Nginx is simpler, faster and most important on the Raspi: it has a low memory profile.

The process is rather simple. Set up nginx (all commands prefixed with sudo, or run as root):
apt-get update
apt-get install nginx
Your /etc/nginx/nginx.conf file is good to go out of the box. Do this:
cd /etc/nginx
YOUR_EDITOR sites-available/YOUR_DOMAIN.conf
in my case I substitued YOUR_EDITOR for vim, and YOUR_DOMAIN for home.waleson.com. Put this in the file:
server {
        server_name YOUR_DOMAIN;
        listen 80;
        error_log /var/log/nginx/home.error;
        access_log /var/log/nginx/home.access;
        root /srv/www;
        index index.html /index.html;
}
restart nginx:
/etc/init.d/nginx restart

Create a /srv/www directory and put an index.html file in there.

Try it! Go to http://YOUR_DOMAIN to see the index.html page!

Objective two accomplished!

Read on: part three - free HTTPS to the rescue