Skip to content

Instantly share code, notes, and snippets.

@radist2s
Last active February 1, 2019 20:21
Show Gist options
  • Save radist2s/9147d92f0c39433408c79ad55bc8e364 to your computer and use it in GitHub Desktop.
Save radist2s/9147d92f0c39433408c79ad55bc8e364 to your computer and use it in GitHub Desktop.
Valet / Valet+ any domains

Introduction

Allows to link any domain to use with Valet / Valet+. You a free to use any domain name, e.g.: dev.exmaple.com, google.com, etc. Not only .test domains.

Installation

Add new config file for Dnsmasq:

sudo echo "conf-file=$HOME/.valet/dnsmasq-extra-domains.conf" >> $(brew --prefix)/etc/dnsmasq.conf

Download script. By default script will be downloaded into /usr/local/sbin/dnsmasq-domain, you can specify script path by editing of variable SCRIPT_PATH bellow.

SCRIPT_PATH=/usr/local/sbin/dnsmasq-domain sh -c 'curl -o $SCRIPT_PATH https://gist.githubusercontent.com/radist2s/9147d92f0c39433408c79ad55bc8e364/raw/8fb140bb6e4bc74936595114efff90ea8cd8fa7a/dnsmasq-domain.sh && chmod +x $SCRIPT_PATH'

Usage

Link your current domain directory via valet:

valet link dev.exmaple.com

Add new Dnsmasq rule for domain and os resolver:

dnsmasq-domain add dev.exmaple.com

Remove domain from Dnsmasq:

dnsmasq-domain remove dev.exmaple.com

Do not forget to restart valet or dnsmasq:

valet restart
#!/bin/bash
[ "$UID" -eq 0 ] || exec sudo bash "$0" "$@"
readonly DOMAIN=$2 # [ dev.example.com ]
readonly COMMAND=$1 # [add | remove]
readonly DNSMASQ_CONFIG_FILE="$HOME/.valet/dnsmasq-extra-domains.conf"
readonly NAMESERVER="127.0.0.1"
readonly DNSMASQ_RULE="address=/.$DOMAIN/$NAMESERVER"
readonly RESOLVER_BASE_DIR="/etc/resolver"
readonly RESOLVER_FILE="$RESOLVER_BASE_DIR/$DOMAIN"
main() {
checkDomain || exit 1
if [ "$COMMAND" == "add" ]; then
add
elif [ "$COMMAND" == "remove" ]; then
remove
else
echo "Usage: $(basename $0) [add | remove] example-domain.com"
fi
}
add() {
mkdir -p $RESOLVER_BASE_DIR
sudo --user $SUDO_USER touch $DNSMASQ_CONFIG_FILE
grep "$DNSMASQ_RULE" $DNSMASQ_CONFIG_FILE >> /dev/null || echo $DNSMASQ_RULE >> $DNSMASQ_CONFIG_FILE
ls $RESOLVER_FILE 2> /dev/null >> /dev/null || \
sudo echo "nameserver $NAMESERVER" > $RESOLVER_FILE || exit 1
}
remove() {
local RULE="$(sedEscape $DNSMASQ_RULE)"
sed -i "" "/$RULE/d" $DNSMASQ_CONFIG_FILE
ls $RESOLVER_FILE 2> /dev/null >> /dev/null && sudo rm $RESOLVER_FILE
}
checkDomain() {
if [ -z "$DOMAIN" ]; then
echo "You have to specify domain. Example: $(basename $0) $COMMAND dev.exmaple.com"
exit 1
fi
}
sedEscape() {
echo $1 | sed 's/\//\\\//g'
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment