Mount USB Memory Stick On Raspberry Pi

Find out how to mount a USB flash drive on your Raspberry Pi

If you are using your Raspberry Pi to play music or video you will soon run out of storage on the SD card which holds the operating system. The easiest way to increase the capacity of the Raspberry Pi to store your media files is with a USB flash drive memory stick. These are very cheap to buy and typically available in sizes up to 128GB; though at the time of writing (Aug 2013) the most cost effective size of good quality drives is 16GB or 32GB. (Click here for SanDisk 32GB Cruzer Blades from £13)

USB flash drive memory stick for Raspberry Pi

If you have a free USB port on your Raspberry Pi then insert your memory stick. If you do not have a free port (because of your mouse and keyboard) then you will need a USB hub. Plug the hub into your Raspberry Pi, and then plug the memory stick and other peripherals into the hub. If you are going to be inserting and extracting the memory stick frequently then it is better to use a USB hub even if you have a free port on the Raspberry Pi, to reduce wear and tear on the Raspberry Pi.

Assuming you are using the standard Raspbian (e.g. Raspbian “Wheezy“) version of Linux on your Raspberry Pi, the memory stick will automatically be detected and given the id sda1. You can check that your memory stick has been correctly identified by entering the command.

ls -l /dev/sda1

and you should see something like the following:

…if the USB memory stick has not been identified then you will instead see:

ls: cannot access /dev/sda1: No such file or directory

Next you need to create a sub-directory in the /media directory on your Raspberry Pi so that the memory stick can be mounted.

sudo mkdir /media/usb

…where you can replace usb with your choice of name if you want, but keep it short as you will probably end up typing it a lot.

Mount USB Flash Drive on Raspberry Pi

Assuming you are logged in as user pi, enter the following command to mount your USB memory stick to /media/usb:

sudo mount -t vfat -o uid=pi,gid=pi /dev/sda1 /media/usb

Now you can confirm you can see the contents of the memory stick with the command ls -l /media/usb which should generate a list of the files and directories on the stick.

To check how much memory you have available on the memory stick (and also on your Raspberry Pi SD card), enter the command df.

Using df command to check free storage space on Raspberry Pi USB memory

Look down the file system ID column to find the line with /dev/sda1 or look down the Mounted on column to find the line with /media/usb. In the example above an 8GB USB flash drive has been mounted and is shown to be 18% full. (Use the command df -BM for the same information on your file system but with all memory size values given in MB for better clarity.)

Unmount USB Flash Drive from Raspberry Pi

Before you disconnect the USB memory stick from the Raspberry Pi, you must first unmount it with the following command:

sudo umount /media/usb


Brief Notes on Rebooting

If you shutdown or reboot your Raspberry Pi, any USB memory sticks mounted in the way described above will be no longer be mounted when the Pi reboots – i.e. you will not be able to access the files on the memory stick until you enter the mounting command. If you plan to keep the USB memory stick permanently or semi-permanently attached to the Raspberry Pi, then it is better to have this occur automatically when the Pi reboots. There are many ways to achieve this, but here is a simple one using Cron.

Enter the command sudo crontab -e to edit your cron tasks file. Use the arrow keys to move down to the end of this file and add the following line:

@reboot mount -t vfat -o uid=pi,gid=pi /dev/sda1 /media/usbGet USB drive to mount automatically at reboot with Raspberry Pi using cron

Now press ctrl-x, then y, then enter to save the changes. This will automatically mount the attached USB drive /dev/sda1 to the directory /media/usb for the user pi when the Raspberry Pi is rebooted.


raspistill is the command line tool for capturing still photographs with the camera module.

Basic usage of raspistill

With the camera module connected and enabled, enter the following command in the Terminal to take a picture:

raspistill -o cam.jpg

Upside-down photo

In this example the camera has been positioned upside-down. If the camera is placed in this position, the image must be flipped to appear the right way up.

Vertical Flip & Horizontal Flip

With the camera placed upside-down, the image must be rotated 180° to be displayed correctly. The way to correct for this is to apply both a vertical and a horizontal flip by passing in the -vf and -hf flags:

raspistill -vf -hf -o cam2.jpg

Vertical and horizontal flipped photo

Now the photo has been captured correctly.


The camera module takes pictures at a resolution of 2592 x 1944 which is 5,038,848 pixels or 5 megapixels.

File size

A photo taken with the camera module will be around 2.4MB. This is about 425 photos per GB.

Taking 1 photo per minute would take up 1GB in about 7 hours. This is a rate of about 144MB per hour or 3.3GB per day.

Bash script

You can create a Bash script which takes a picture with the camera. To create a script, open up your editor of choice and write the following example code:


DATE=$(date +"%Y-%m-%d_%H%M")

raspistill -vf -hf -o /home/pi/camera/$DATE.jpg

This script will take a picture and name the file with a timestamp.

You’ll also need to make sure the path exists by creating the camera folder:

mkdir camera

Say we saved it as, we would first make the file executable:

chmod +x

Then run with:


More options

For a full list of possible options, run raspistill with no arguments. To scroll, redirect stderr to stdout and pipe the output to less:

raspistill 2>&1 | less

Use the arrow keys to scroll and type q to exit.

Full documentation

Full documentation of the camera can be found at hardware/camera.


To create a time-lapse video, you simply configure the Raspberry Pi to take a picture at a regular interval, such as every minute, then use an application to stitch the pictures together in a video.

A good way to automate taking a picture at a regular interval is using cron.

Open the cron table for editing:

crontab -e

This will either ask which editor you would like to use, or open in your default editor. Once you have the file open in an editor, add the following line to schedule taking a picture every minute (referring to the Bash script from the previous page):

* * * * * /home/pi/ 2>&1

Save and exit and you should see the message:

crontab: installing new crontab

Ensure your scipt does not save each picture taken with the same filename. This will overwrite the picture each time.

Stitching images together

Now you’ll need to stitch the photos together in to a video.

You can do this on the Pi using mencoder but the processing will be slow. You may prefer to transfer the image files to your desktop computer or laptop and processing the video there.

Navigate to the folder containing all your images and list the file names in to a text file. For example:

ls *.jpg > stills.txt

On Raspberry Pi or other Linux computer

Install the package mencoder:

sudo apt-get install mencoder

Now run the following command:

mencoder -nosound -ovc lavc -lavcopts vcodec=mpeg4:aspect=16/9:vbitrate=8000000 -vf scale=1920:1080 -o timelapse.avi -mf type=jpeg:fps=24 mf://@stills.txt

Once that’s completed, you should have a video file called timelapse.avi containing a time-lapse from your images.

Raspberry Pi Webcam

Esse artigo foi extraído do site em 14/10/2014. Transcrevi integralmente por considerar ser a melhor orientação para configurar um webserver integrado a uma camera.

How to turn your Raspberry Pi and its camera board into a constantly refreshing webcam with text overlay. Feedback welcomed at the Raspberry Pi Forum.


Install a web server and PHP including the php_gd extension. Use nohup to start raspistill in time-lapse mode. Create an index page that embeds the webcam image and a PHP script that generates the webcam image. Upon page request, grab the latest buffered image. Optionally overlay text before outputting.


  • Raspberry Pi computer.
  • SD card, 4 GB or larger, the faster the better but doesn’t have to be especially fast for this webcam.
  • Latest Raspbian operating system.
  • Internet connection to download and update the OS and additional software.
  • Raspberry Pi camera board.
  • To view on another computer: a LAN connection.
  • To view on the web: a public IPv4 or IPv6 address, or a modem/router with port forwarding.

Wireless adapters seem flaky on Linux; sometimes it is hard to get them to even work and in my experience they are often prone to drop the connection. My advice is to buy a Raspberry Pi model B with integrated USB-LAN adapter (ethernet port) and run a network cable to your modem or router. That way, the network connection will be stable and almost certainly a lot faster. Also, twice the amount of RAM in the Model B will not hurt wile having a camera attached and running a web server with PHP. Although I am sure this will work with a Model A.


Install the camera by following the official instructions. Be careful while handling bare circuit boards like the camera! Static electricity can easily ruin them and the flat cable and connectors are fairly fragile. Before turning on the computer, now is a good time to try and think of a clever way to fix the camera with a good view of its surroundings and maybe protect it from the elements and (further?) careless handling. Two 2 mm bolts will fit the holes. For my first try, I improvised by sticking one sturdy twist-tie through them, front to back, and wrapping the ends around a small stick.


Amendment to the official instructions: to get the latest firmware and camera code, don’t just run apt-get upgrade, but also rpi-update:

sudo apt-get update
sudo apt-get dist-upgrade
sudo rpi-update
sudo reboot

In the latest Raspbian OS release, the rpi-update package is included. In an older release, should apt-get dist-upgrade not fetch it automatically, try sudo apt-get install rpi-update before running rpi-update.

After updating, make sure you enable the camera by running

sudo raspi-config

and pressing Enter on the appropriate option:


After confirmation and return to the main screen, press Tab to get to the Select / Finish options, right arrow to move to Finish, Enter, and confirm reboot. Test to see if everything works so far:

raspistill -o ~/Desktop/cam.jpg

which should turn the camera on (check the light), display a preview if you are running the graphical desktop, wait 5 seconds and save a photo called cam.jpg on your Desktop. To disable the camera light, for stealth operation, edit config.txt:

sudo nano /boot/config.txt

and add this on a new line: disable_camera_led=1. Save and exit by typing Ctrl-x, y, Enter. Next, install the lighttpd web server and PHP:

sudo apt-get install lighttpd php5-cgi php5-gd

Apache would also work but is more of a resource hog. Enable PHP:

sudo lighty-enable-mod fastcgi
sudo lighty-enable-mod fastcgi-php
sudo service lighttpd force-reload
echo '<?php phpinfo(); ?>' | sudo tee /var/www/phpinfo.php

and check to see if it works by pointing the Midori browser on your RPi to http://localhost/phpinfo.php. From another computer on the LAN, use the IP address of your Raspberry Pi (check by running ifconfig) or its hostname if your router understands that (probably requires installing avahi-daemon on the RPi). E.g. or http://raspberrypi/phpinfo.php. If your modem / router provides IPv6 connectivity, try enabling it on the RPi:

sudo modprobe ipv6
sudo nano /etc/modules   # add a new line with: ipv6

Normally, having an IPv6 address would immediately make your computer accessible from the web, without having to configure port forwarding on your modem / router. This is good and bad. Good, because no configuration and people may surf to your webcam. Bad, because hackers. Whenever your computer is visible from the outside, make sure to at least change your standard password! Use the password option in raspi-config or run passwd. Enable your router’s IPv6 firewall but open port 80 for general web access or another port (1024 or higher) for semi-private access. Because this is a direct connection without any port translation (forwarding), if you use a port other than 80, reconfigure lighttpd to listen to that port.

Similar for the “normal” IPv4 connection: to make your webcam page accessible from the outside, configure port forwarding in the router from any address on the outside (all traffic for port 80 or otherwise 1024+) to port 80 on your RPi’s LAN address. Change the outside port for semi-private access. If you change the inside port, you’ll have to reconfigure your web server to listen to that port. Check your router manual for details :-). If that all went well, your RPi web server should be accessible to anyone surfing the web as http://your-public-internet-address:the-outside-port-you-opened/, e.g. (which is not a webcam, just the IP address of and port 8080).

Now to get the webcam up and running. You need to create two files in the web server root directory (/var/www) and copy text to them from the two code blocks below. In general, I find the easiest way to do that is to open an SSH session to the RPi from my Mac, run an editor on the RPi: sudo nano /var/www/index.html (sudo is needed because the /var/www directory is owned by user root) and on the Mac copy-paste the text from the web browser to Terminal where the editor is running via SSH. In this case I also provided download links so you may do:

sudo cp webcam-html-1.0.0.txt /var/www/index.html
sudo cp webcam-php-1.0.3.txt /var/www/webcam.php

If wget is not installed on your RPi, run this first: sudo apt-get install wget.

Save this as /var/www/index.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
Version : 1.0.0
Date : 2013-08-11
File : /var/www/index.html
Info :
<html xmlns="" lang="en-gb" xml:lang="en-gb">
	<head profile="">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>My Webcam</title>
		<meta name="keywords" content="raspberry pi, camera, webcam, raspistill, php, javascript" />
		<meta name="description" lang="en-gb" content="This is my webcam. There are many like it, but this one is mine." />
		<meta name="author" content="Ewoud Dronkert" />
		<style type="text/css">
			img#view { display: block; }
		<script type="text/javascript">
			var shotinterval = 5;     // Seconds between shots
			var shottimer = null;     // Countdown timer to the next shot
			var shootingnow = false;  // To avoid parallel execution

			// Start the timer
			function start() {
				shottimer = window.setTimeout(shoot, 1000 * shotinterval);

			// Stop the timer
			// Return previous state (was it running? true/false)
			function stop() {
				if (shottimer) {
					shottimer = null;
					return true;
				return false;

			// Stop the timer when running, start when not running
			// Avoid undefined state by checking for image refresh in progress
			function toggle() {
				if (!shootingnow) {
					var wasrunning = stop(), node;
					if (node = document.getElementById("ctrl"))
						node.innerHTML = wasrunning ? "Start" : "Stop";
					if (!wasrunning)

			// Refresh the webcam image by re-setting the src attribute
			function shoot() {
				shootingnow = true;
				var img; 
				if (img = document.getElementById("view"))  
					img.src = "webcam.php?" +;
				shootingnow = false;
	<body onload="start()">
		<img id="view" src="webcam.php" alt="[webcam]" title="Webcam" />
		<a id="ctrl" href="#" onclick="toggle()">Stop</a>

Save this as /var/www/webcam.php. It is very important to not have any blank lines or spaces before the first <?php or after the last ?>.


/* Version : 1.0.3
 * Date : 2013-08-14
 * File : /var/www/webcam.php
 * Info :

$now = time();     // Current time on the server
clearstatcache();  // To get fresh results for all file-info functions
$cam = '/dev/shm/webcam.jpg';  // Where raspistill will save every image
$buf = '/dev/shm/buffer.jpg';  // Buffer to avoid read/write collisions, also added text
$err = '/dev/shm/error.jpg';   // Error message if reading $cam or $buf failed

// Get file modification time of the camera image
$t_cam = 0;
if (file_exists($cam))
	if (is_readable($cam))
		$t_cam = filemtime($cam);

// Get file modification time of the image buffer
$t_buf = 0;
if (file_exists($buf))
	if (is_readable($buf))
		$t_buf = filemtime($buf);

// If camera image not found or not accessible
if (!$t_cam)
	$t_cam = $now;  // For the file name time-stamp

// JPEG image headers, time-stamped file name
header('Content-Type: image/jpeg');
header('Content-Disposition: inline; filename="webcam_' . date('Ymd_His', $t_cam) . '.jpg"');

// If the camera image is newer than the buffer and can be read
if ($t_cam > $t_buf && $im = @imagecreatefromjpeg($cam)) {

	// Save a new buffer
	$black = @imagecolorallocate($im, 0, 0, 0);
	$white = @imagecolorallocate($im, 255, 255, 255);
	$font = 1;  // Small font
	$text = date('r', $t_cam);  // ISO format date/time
	@imagestring($im, $font, 2, 1, $text, $black);  // Bottom-right shadow
	@imagestring($im, $font, 1, 0, $text, $white);
	@imagejpeg($im, $buf);  // Save to disk
	@imagejpeg($im);  // Output to browser (avoid another disk read)
	exit();  // End program early

// We are here if camera image not newer than buffer (or both not found)
// or reading the camera image failed

// If buffer not found or not accessible
// or reading+outputting the old buffer fails
// or reading+outputting existing error image fails
if (!$t_buf || !@readfile($buf) || !@readfile($err)) {

	// Create an error image
	$width  = 800;  // Should ideally be the same size as raspistill output
	$height = 600;

	if ($im = @imagecreatetruecolor($width, $height)) {

		$white = @imagecolorallocate($im, 255, 255, 255);
		$black = @imagecolorallocate($im, 0, 0, 0);
		@imagefilledrectangle($im, 0, 0, $width - 1, $height - 1, $white);  // Background
		@imagerectangle($im, 0, 0, $width - 1, $height - 1, $black);  // Border
		$font = 3;  // Larger font
		$text = 'Read Error';  // Message
		$tw = @imagefontwidth($font) * strlen($text);  // Text width
		$th = @imagefontheight($font);
		$x = (int)round(($width - $tw) / 2);  // Top-left text position for centred text
		$y = (int)round(($height - $th) / 2);
		@imagestring($im, $font, $x, $y, $text, $black);  // Write message in image
		@imagejpeg($im, $err);  // Save to disk
		@imagejpeg($im);  // Output to browser



The last piece of the puzzle is to have the raspistill tool continuously save camera pictures in the background. When I first tried to build this webcam, I let every new page request run raspistill for a single new image. That was a bad idea for a number of reasons, foremost the fact that concurrent invocations of raspistill apparently made the camera board or the video processor crash, requiring a reboot of the RPi. So I separated the two file transfer paths as much as possible. There is only one process accessing the camera and saving camera images to disk. The webcam.php script on the server polls if there is an image newer than the previously saved buffer, and if so, copies the latest camera image to the buffer. That should happen only once, no matter how many clients are viewing your webcam.

If reading the camera image or the buffer fails, the script falls back to the old buffer image or an error image. This means that sometimes you won’t see the image refresh for a while. I have never seen it skip more than one time period, though.

Start the automated capture in a terminal window, at the console or via SSH:

nohup raspistill -n -e jpg -w 800 -h 600 -q 70 -t 2147483647 -tl 5000 -o /dev/shm/webcam.jpg &

where nohup lets the process continue even after you log off, -n prevents previews (I don’t have a monitor plugged in), -t 2147483647 makes it run for almost 25 days (largest number possible in this version of raspistill), -tl 5000 has it take a picture every 5 seconds, -o /dev/shm/webcam.jpg saves the image on RAM disk and & makes it all run in the background. Press Enter again to get the prompt back. The console will look like this:

pi@raspberrypi ~ $ nohup raspistill -n -e jpg -w 800 -h 600 -q 70 -t 2147483647 -tl 5000 -o /dev/shm/webcam.jpg &
[1] 3027
pi@raspberrypi ~ $ nohup: ignoring input and appending output to ‘nohup.out’

pi@raspberrypi ~ $ 

When you get back on the console or start a new SSH session, you can check if the raspistill process is still going by running ps ux or, if for some reason you used sudo, ps aux. To stop it: killall raspistill.

Last tip: three things have to be synchronised, in order of importance:

  • Essential: the file name (-o) in the raspistill command and the file name ($cam) in the webcam.php script.
  • Makes sense: The time-lapse (-tl) in the raspistill command and the time-lapse (shotinterval) in the javascript section of index.html.
  • For show: the size (-w, -h) in the raspistill command and the size ($width, $height) in the webcam.php script.

Install as a Start-Up Daemon

Copy this or download it and save as /etc/init.d/webcam:

# Provides:		webcam
# Required-Start:	$remote_fs $syslog
# Required-Stop:	$remote_fs $syslog
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	Control raspistill
# Description:		Control raspistill camera time lapse
#			and save images to RAM disk.

[ -x "$EXE" ] || exit 0

SCR="webcam"   # script / service name
ARG="-n -w 800 -h 600 -t 2147483647 -tl 5000 -o /run/shm/$SCR.jpg"
LCK="/var/run/$"   # lock file location

update_lockfile() {
	PID=$(pgrep "$BIN")
	if [ -z "$PID" ]; then
		[ -f "$LCK" ] && [ -w "$LCK" ] && rm -f "$LCK"
		[ -e "$LCK" ] || touch "$LCK"
		[ -f "$LCK" ] && [ -w "$LCK" ] && echo "$PID" > "$LCK"

do_start() {
	$EXE $ARG &

do_stop() {
	killall -q "$BIN"

case "$1" in
		echo -n "Service $SCR is "
		if [ -z "$PID" ]; then
			echo "not running." >&2
			exit 3
			echo "running."
		echo -n "Starting service $SCR..."
		if [ -n "$PID" ]; then
			echo "already started." >&2
			exit 4
			echo "done."
		echo -n "Stopping service $SCR..."
		if [ -z "$PID" ]; then
			echo "already stopped." >&2
			exit 5
			echo "done."
		echo -n "Restarting service $SCR..."
		if [ -n "$PID" ]; then
			echo "failed to stop." >&2
			exit 6
			if [ -z "$PID" ]; then
				echo "failed to start." >&2
				exit 7
				echo "done."
		echo "Usage: $0 {status|start|stop|restart|force-reload}" >&2
		exit 8
exit 0

Install as a service that will start at boot time:

sudo chmod 755 /etc/init.d/webcam
sudo update-rc.d webcam defaults 99 01
sudo reboot

Manual start/stop:

sudo service webcam start
sudo service webcam stop

Raspberry Pi Web Server

Extraído de

Running a lightweight webserver on the Raspberry Pi (lighttpd)

This guide covers setting up a light webserver on Linux using the lighttpd web server on the Raspberry Pi. Most of these instructions can also be applied to other Debian or Ubuntu based distributions (except the tasks using the raspi-config tool). I’ve already written a tutorial based on the “full-fat” Apache webserver (running a LAMP Apache based webserver on the Raspbbery Pi).

Lighttpd provides a way of setting up a web server without putting too much load on the limited processing capability. It’s ideal for providing web access to the Raspberry Pi as a monitoring tool, or as a lightweight webserver for a personal website.

Debian Linux

This is based on the Debian Raspberry Pi Raspbian.

One of the advantages of Debian Wheezy on the Raspberry Pi is that ssh is enabled by default and that the raspi-config tool provides a convenient way to increase the size of the root partition (useful if you have an SD card bigger than 2GB) and to change the default password for the pi user (essential for everyone). The raspi-config tool should run when you first start the system, otherwise use sudo raspi-config.

Using the command line and editing files

As we are going to be doing this through the command line it is useful to understand a little about the shell. Although this provides step-by-step instructions if you haven’t used the command line previously I suggest you read the basic shell reference guide, and then return to this point.

Throughout the install you will see many commands prefixed with sudo. The sudo command allows the user to issue a command as the superuser (or in certain circumstances as another user). Without using the sudo command many of the commands would fail stating insufficient permissions. This is a security feature that protects the system from other users, but also limits the amount of damage that a user can do by mistake (although if prefixed with the sudo command it will not help against accidents).

Static network IP address

The next step is to give the Raspberry Pi an static IP address. This is a little more complex as it depends upon your own setup and what router you have on how to achieve this.

By default the Raspberry Pi will request a dynamic IP address which is issued by your router as required. This however may change in future which would make it hard to connect to the webserver. Instead we provide it with an address that doesn’t change such as
Note that this address can be used on the local network, but not on the Internet – later we’ll look at providing access through your router / firewall from the Internet.

First find out what DHCP address has been allocated by using the ifconfig command – see the extract below


eth0      Link encap:Ethernet  HWaddr b8:27:eb:8a:71:a0

          inet addr:  Bcast:  Mask:


This is saying that the ethernet port 0 – has an IP address of

You will also need to find out what address your router is, using the route command

$ route

Kernel IP routing table

Destination     Gateway         Genmask         Flags Metric Ref    Use Iface

default         UG    0      0        0 eth0     *        U     0      0        0 eth0

This shows that the router IP address (Gateway) is and all traffic is sent via that router.

At this point you will also need to check on what address range is being issued by the router. This depends upon the individual router. In my case I have a Belkin Wireless Router which can be reached by pointing a web browser to the IP address of the router

The LAN settings are shown below:




In this case the local network has valid addresses from to The router is at address and any DHCP requests will be given entries between and (you can change the range of the DHCP addresses if required). I have used for this server.

To change to static IP address

cd /etc/network

sudo nano interfaces

replace the line “iface eth0 inet dhcp” with

iface eth0 inet static




You should also take a look at the file /etc/resolv.conf

and check it has a nameserver entry (probably pointing at your default gateway)

Alternatively you could point directly at your ISPs DNS servers rather.

Whilst you can dynamically reload the network interface I suggest a reboot at this stage to make sure that the configuration is correct.

sudo reboot

After logging in check using ifconfig to confirm that we have a static ip address


eth0      Link encap:Ethernet  HWaddr b8:27:eb:8a:71:a0

          inet addr:  Bcast:  Mask:


Using ssh

SSH (Secure Shell) is a network protocol that allows you to login and control the computer through the command line remotely. As the name suggests it is secure as it encrypts communication across the network (so that others cannot see your password etc). It also has some great features such as tunnelling, which we won’t go into here.

Using the Wheezy image ssh is turned on by default. This can be enabled / disabled through the raspi-config tool if required.

You can now connect to the Raspberry pi remotely (on the same network) via ssh.
If you have another linux computer on the network then from a terminal run

which will login with the same username. If you want to use a different username then prefix that before the ip address with an @ sign.
ssh pi@

If you want to connect from Windows then there are several options, but I suggest the open source software Putty.

Making the server available on the Internet

Next we are going to configure the router to allow ssh logins and web traffics through its firewall to the Raspberry Pi.

You did remember to change the default password for the pi username didn’t you! If you haven’t already changed the default password then do it now otherwise anyone will be able to login to your Raspberry Pi.

As a home user the ip address used on your local network is a private address range that will not work over the Internet. Instead your ISP will provide a single dynamic IP address which is used by the router. To allow traffic to flow from the Internet to your Raspberry Pi needs the IP address of the Pi to be made to look as though it is from the router. This is a process called Network Address Translation (NAT).

The ports that need to be allowed through are port 80 (http) and if you would like to be able to login to the computer from the Internet then port 22 (ssh).

To do this you will need to consult the instructions on your router. In the case of my Belkin router this is through the Firewall > Virtual servers settings (see below), but Netgear this is Advanced > Security > IP Forwarding.





The final stage is to have a DNS entry point at your router’s IP address. In my case I have cable Internet through Virgin Media. Although it does have a dynamic IP address the address does not normally change. I have a static DNS entry on a Internet DNS server. The entry only needs to be changed about once every year or when Virgin Media perform significance maintenance on the Internet connection.

If you have a dynamic IP address that changes on a more recent basis then you will need to register for a dynamic dns service.

Installing lighttpd

To install the lighttpd web server issue the command.
sudo apt-get install lighttpd

This will install the web server and also pull in any other packages (called dependencies) that are required. The server will be automatically started and set to start by default after a reboot.
[ ok ] Starting web server: lighttpd.

Install mysql database (optional)

Whilst you can have a perfectly good website without a database, database provide a good way of holding data and are a requirement for many content management systems (CMS) and web based applications. If you don’t need a databse the you can skip this and go straight to configuring php.

Mysql is the most popular database server, whilst there are other alternatives some of which may require less resources most third party software for Linux is designed to use Mysql.If required it can be installed using

sudo apt-get install mysql-server

During the install there is a prompt request for a password.
The password is for the mysql root user.

Install PHP

Perl is installed as part of the operating system so I will just be adding PHP, which is an interpretted programming language. Whilst this is optional it is recommended that it is installed as it is particularly useful.

The following commands will install PHP version 5.

sudo apt-get install php5-common php5-cgi php5
Note it’s important to install in the order listed above. If you try to install php5 without first installing the php5-cgi package then it will install Apache as well, which we don’t want for this light-weight lighttpd server.

If you installed mysql then you should also issue the following command to install the php mysql libraries to allow PHP to access the mysql database.
sudo apt-get install php5-mysql

To enable the server to handle php scripts the fastcgi-php module should be enabled by issuing in the command
sudo lighty-enable-mod fastcgi-php
Then reload the server using
sudo service lighttpd force-reload

Set permissions on the web directory /var/www/

It is useful to change the permissions on the www directory to allow your user to update the webpages without needing to be root.

Change the directory owner and group
sudo chown www-data:www-data /var/www
allow the group to write to the directory
sudo chmod 775 /var/www
Add the pi user to the www-data group
sudo usermod -a -G www-data pi

You should logout and back in – to pick up group permissions, or if running X you can just start a new terminal.

Testing the server

Once the setup is complete you can access the web page by pointing your browser to the router IP address or DNS entry.

You should get a page back stating that it works, but that there is no content loaded.

To test that the webserver and PHP are working correctly then delete the file /var/www/index.lighttpd.html and create a file /var/www/index.php with the contents of this page.

Note that the filename of the link ends in .txt to prevent my webserver from running this, you should have the file ending with .php so that the file is run as a PHP script.