Using ngrok to expose local web server
Ngrok is a neat way to provide webdev clients or colleagues with a preview link to your local web server without having to deal with port forwarding or deploying to a separate dev environment.
I don't like writing lots of fluff just for the sake of exceeding the magic 500 word seo threshold, so let's look at some realistic scenarios for this tool.
Tunneling to a Virtual host
I often use custom whatever.local domains when I am developing new websites and applications, I point these domains to 127.0.0.1 in my HOSTS file on Windows and point these domains to my htdocs folder via apaches vhost config.
To create an ngrok tunnel to these internal domains you can specify a header rewrite option, like so:
c:\ngrok.exe http -host-header=my-local-domain.local 80
More info: https://ngrok.com/docs#host-header
Running multiple tunnels at once.
Each "ngrok link" is a tunnel, if you want to expose multiple tunnels at once (next-facebook.local and boring-business-app.local) you need to use a configuration file, this file is stored in ~/.ngrok.yml, ngrok uses a YAML file for its configuration, here is an example of a configuration file that expostes two tunnels to internal domains.
tunnels:
completely-arbitrary:
addr: 80
proto: http
host_header: awesome-webapp.local
next-facebook:
addr: 80
proto: http
host_header: next-facebook.local
auth: "demo:secret"
Under the key tunnels: we can create multiple named tunnels, the key is completely arbitrary but must be unique for each tunnel, you can specify the internal port via the addr key, the protocol via the "proto" key, and we specify the local domain with the host_header key as before.
You can also password protect your tunnel with "Basic Auth" with the "auth" key.
To expose these tunnels you run ngrok with the start argument like so:
ngrok start completely-arbitrary next-facebook
More info:
Reserved Domains
Ngrok has several paid plans that allow you to reserve an ngrok.io subdomain (example. mycompany.ngrok.io), or you can even reserve a wildcard CNAME so you can use your own domain name as the temporary domain, for example *.preview.mycompany.com, this is a great way for web agencies to give quick and functioning preview links to their clients.
More info: https://ngrok.com/product#pricing
Caveats
If you are using a framework that generates links to other pages by prefixing the local domain (aka generates absolute urls) ngrok might not work correctly as all links on a page will be pointing to a local domain that won't exist for a person trying out the site, if you're using WordPress, a great workaround for this is to use this plugin: https://wordpress.org/plugins/relative-url/
So a rule of thumb if you want to integrate ngrok into your workflow, use relative links.