MacOS hosts file entry for only non-www url

899 views Asked by At

I'm running MacOSX 10.11.4.

I'd like to have example.com point to my locally running apache server, but have www.example.com point to the actual website.

Example: I have the following entry in my /etc/hosts file: 127.0.0.1 example.com If I ping example.com and www.example.com, they both hit 127.0.0.1 (I believe because the canonical URL is recognized as being the same).

Interesting note, Chrome will pull the URL's as I want, but Firefox will hit localhost for both.

-

Edit: I know that using something like example.local is more conventional and avoids this problem entirely; however, my work has been using the www/non-www method for a while now and would like to keep it, if possible.

2

There are 2 answers

4
serv-inc On

This might be too easy, but why don't you put

example.com     127.0.0.1
www.example.com 123.52.232.12

into your /etc/hosts file, with 123.52.232.12 being the IP address of the real example.com site?

why it's happening or how to stop both domains from going to my hosts file

This is the default resolution order, with the hosts file autoexpanding for subdomains. The solution by @fragmentedreality provides a workaround by using the dnsmasq resolver, which is also recommended at https://serverfault.com/questions/431605/dont-automatically-include-all-subdomains-in-dnsmasq-address and described at https://gist.github.com/ogrrd/5831371.

0
fragmentedreality On

As you are running OSX you can add a custom resolver for that.

Create the directory /etc/resolver/ and add a file for the domain, you want to resolve (i.e. example.com). Inside the file you can specifiy alternative nameservers to use for the specified domain. By default the filename defines the domain (see manpage for more details).

$ sudo mkdir -p /etc/resolver
$ echo "nameserver 127.0.0.1" | sudo tee /etc/resolver/example.com > /dev/null

You can check, if the resolver is applied with the command scutil --dns.

Now you just need to run a local nameserver like dnsmasq to resolve queries to 127.0.0.1. You can either install dnsmasq via homebrew or run it in a docker-container:

$ docker run -p 53:53/tcp -p 53:53/udp --cap-add=NET_ADMIN \
    andyshinn/dnsmasq:2.75 \
    --host-record=example.com,127.0.0.1

Find more information on the homebrew-solution here.