Skip to content

Instantly share code, notes, and snippets.

@exupero
Last active March 29, 2024 21:10
Show Gist options
  • Save exupero/3228103 to your computer and use it in GitHub Desktop.
Save exupero/3228103 to your computer and use it in GitHub Desktop.
Alias a domain to a local port (Mac)

I run a lot of web servers for different projects, all of them on different ports. Generally I start with port 8000 and increment from there as I spin up new servers, but it became tiresome to remember what projects were running on which ports and what the next available port was.

/etc/hosts won't let you specify a port, but a combination of aliasing 127.0.0.1 to 127.0.0.X, forwarding ports from 8000 to 80, and adding the 127.0.0.X IP under an alias in /etc/hosts did work.

This script finds the next available value of X, aliases it with ifconfig, forwards the given port to port 80 with ipfw, and adds a new entry to /etc/hosts that aliases the IP to the domain you want.

Now I can add a server alias with sudo domain-alias funproject 8000, run the web server at 127.0.0.X:8000, and load up http://funproject/ in my browser.

(Because I needed it to work on a Mac, I couldn't use iptables. pfctl seems to work.)

I've written more about this on Atomic Object's blog Spin.

#!/bin/bash
# Usage: sudo domain-alias.sh myapp 8000
domain=$1
port=$2
if [ -z "$domain" ] || [ -z "$port" ]; then
echo "Usage: domain-alias.sh <domain> <port>"
exit 1
fi
existing=$(cat /etc/hosts | grep $domain | cut -d' ' -f1)
if [ -n "$existing" ]; then
localip=$existing
else
last=$(cat /etc/hosts | grep -oE "127.0.0.\d" | cut -d'.' -f4 | sort -n | tail -1)
next=$(expr $last + 1)
localip="127.0.0.$next"
fi
{
ifconfig lo0 alias $localip
echo "rdr pass on lo0 inet proto tcp from any to $localip port 80 -> $localip port $port" | pfctl -ef -
echo "$localip $domain" >> /etc/hosts
} && echo "Done. Run apps at $localip port $port and view them at http://$domain/."
@anayanaze
Copy link

Can you please write this command for MAC yosemite as ipfw command is not supported there

Kindly pinging @exupero

@exupero
Copy link
Author

exupero commented Jul 2, 2023

Based on this comment, I was able to add localhost port forwarding using this command:

echo 'rdr pass on lo0 inet proto tcp from any to 127.0.0.1 port 8888 -> 127.0.0.1 port 8286' | sudo pfctl -ef -

(where localhost:8888 is the port to open in the browser and localhost:8286 is the port to load content from)

I'll see if I can update the script this week.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment