Wildcard subdomains can be used to create a new subdomain on the fly, without having to configure it on the server and as well used as a unique identifier for each user or organization in a multi-tenant application.
For example, if you have a multi-tenant application and you want to give each user a unique subdomain, you can use the wildcard subdomain to proxy the request to the server and then the server can use the subdomain to identify the user.
But do be able to do that, you need to configure your local network to proxy all subdomains to the server and then configure the server to handle the subdomain.
That is what this guide is about.
1. add host to /etc/hosts
sudo nano /etc/hosts
add this line to the end of the file
127.0.0.1 example.test
2. install nginx and configure it
brew update
brew install nginx
check the config file path by running
nginx -t
it should be something like
nginx: the configuration file /opt/homebrew/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /opt/homebrew/etc/nginx/nginx.conf test is successful
open the config file
sudo nano /opt/homebrew/etc/nginx/nginx.conf
and add this to the end of the file
server {
listen 80;
listen [::]:80;
server_name ~^(?<subdomain>.+).example.test$ example.test;
access_log /opt/homebrew/etc/nginx/$host-access.log;
error_log /opt/homebrew/etc/nginx/$host-error.log;
location / {
proxy_pass http://127.0.0.1:4000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection βupgradeβ;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Subdomain "$subdomain";
}
}
restart nginx
brew services restart nginx
At this point you should be able to access your local server at http://example.test but not at http://subdomain.example.test yet.
See the next step to configure dnsmasq to proxy all subdomains to the server.
3. install dnsmasq
brew install dnsmasq
4. configure dnsmasq
sudo mkdir -p $(brew --prefix)/etc/dnsmasq.d
sudo echo 'address=/.test/127.0.0.1' > $(brew --prefix)/etc/dnsmasq.d/test.conf
sudo brew services restart dnsmasq
tell macOS to forward all .test domains to dnsmasq
sudo mkdir -p /etc/resolver
sudo bash -c 'echo "nameserver 127.0.0.1" > /etc/resolver/test'
done! now you can access your local server at http://example.test, and any subdomain will be proxied to the server as well (e.g. http://subdomain.example.test)
Top comments (2)
thanks, Your post helps me a lot
Nice one Boss... looking forward to applying this