SSH port forwards

Here are the commands I use for ssh port forwards. If you add the -N flag it *won't* open an ssh session, but that's almost aesthetic. Imagine I'm running all of these from my laptop.

1) This creates an ssh tunnel from port 8000 on my laptop to port 80 on The -L refers to forwarding my laptop's local port 8000. Then there are two more arguments tacked on: localhost and 80. These both are from the perspective of the remote machine, so in this case localhost means and port 80 means whatever is serving on port 80 (this website, in fact!).

ssh -N -L 8000:localhost:80


2) The same example as #1, but by omitting the -N flag I get an ssh tunnel AND an ssh session on If I close the ssh session, I lose my tunnel. I prefer #1 to this method but there are uses in more complicated setups for this kind of thing.

ssh -L 8000:localhost:80


3) Now imagine I've got two servers at home. I'm still on my laptop, maybe at the library. One has an ssh port open to the world (call it homeserver). The other is cut off from the world entirely, but is serving web pages on port 80 inside my home network. Let's call this second server homeserver2, and say it's got a static IP on my home router of So I can run this tricky command:

ssh -N -L 8000:

What this does is pretty cool:

  • -L 8000 -> this starts forwarding requests on my laptop at the library that are sent to http://localhost:8000.
  • : -> this means those requests ultimately end up forwarded to homeserver2! Cool!
  • -> and of course, homeserver acts as the broker by sending the traffic through itself.

If someone at the library were eavesdropping on this session, they'd only see encrypted traffic going out from my computer on port 22. There might be exceptions to this if homeserver2 was hosting a complex website that made requests to external websites.

4) Even better: let's update our /etc/hosts file and add the following line:

Now requests in my laptop's browser to will go to my laptop on port 80. I can slightly modify the command above by changing the local port to 80 (prefixing with sudo so I can use local port 80):

sudo ssh -N -L 80:

Now. whenever I have my ssh tunnel open I can access homeserver2 by tying directly into my browser! The downside to this approach is that at home I'll have issues if I don't open this tunnel. My approach so far when using these commands has been to edit /etc/hosts manually each time I open a tunnel.


Add new comment