If you’re working with WordPress Multisite in your local environment, you might have noticed that dealing with a subdomain install is a pain, because your hosts file doesn’t support wildcard entries for hosts, i.e. you cannot do something like this:
127.0.0.1 *.multisite.lo # will not work!
There are quite a few solutions though, first and easiest of which is to run multisite with a subdirectories setup. The second solution would be to manage you hosts file manually and create an entry for each subdomain in you installation. This could be a pain if you’re working with quite a large amount of subdomains, in fact you can end up spending most of your time editing you hosts file and flushing DNS cache.
I wrote a little snippet that you can use in a plugin file or functions.php which prints out a string you can copy and paste into your /etc/hosts file. It generates an entry out of all the existing domains in your WordPress multisite install and maps them to the IP address you specify.
add_action( 'wp_footer', 'print_entry_for_hosts_file' ); function print_entry_for_hosts_file() { global $wpdb; $domains = $wpdb->get_col( "SELECT domain FROM $wpdb->blogs;" ); echo "127.0.0.1 " . implode( ' ', $domains ); }
The wp_footer hook will get it to print the entry in your theme’s footer but you can attach it to any other hook if you like. When actually pasting the generated entry into your hosts file, make sure you remove the previous entry for your domain to keep the file clean and shiny. Comment out the add_action line to hide the mess until you add a few more sites to the network and need to update you hosts file again.
I agree it’s still a bit of a pain but it really helps! The third and probably most correct way of handling wildcard domains working locally would be to set up a DNS server. It’s not always worth the trouble though.
If you had experience dealing with wildcard domains in WordPress multisite, please share your thoughts in the comments section below. If you installed a local DNS server, feel free to link to any guide or tutorial on how to do that on your operating system. Thanks!
If you add
127.0.0.1 multisite.lo
won’t it redirect all subdomains also there?
It will not, because technically
multisite.lo
is one host name, whilewww .multisite.lo
is a different one, andftp .multisite.lo
is a third hostname. Unless you tried it and it works for you though :)No, I just tested it (on Mac) and as you said… doesn’t work. I was sure it’d work.
[…] WordPress Multisite with Wildcard Subdomains – Konstantin Kovshenin. This entry was posted in Tutorials and tagged developement, local, WordPress. […]
There’s a plugin for that: WP XAMPP Multisite Subdomains. It adds the needed lines to the hosts file automatically.
Unfortunately, there seems to be no English description.
Allowing Apache to write to the hosts file is highly insecure, but yeah, that can be an option :) Thanks for you comment!