YOURLS Multi Domain

Recently I wanted to convert all my link shorteners to YOURLS which is a pretty awesome, easy to use link shortener. I could have easily setup YOURLS 8 times, but that felt unnecessary since all the files are static and all the data is stored in MySQL. So I modified the config to allow for multiple databases based on the domain it is being accessed from.

First thing I did was create a DB for each domain with this naming convention

Next I created a user in MySQL with full access to DBs that match yourls%

Now I made the changes to the config file yourls-directory/user/config.php

Add this at the top of the file with all my domain names in the $allow_hosts array.

// Database name prefix $dbprefix = 'yourls_'; // Domains for YOURLs sites $allowed_hosts = array('', ''); if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) { die('This domain has not been set up yet.'); } else { $domain = $_SERVER['HTTP_HOST']; $dbname = $dbprefix.$domain; }

This will get the domain and make sure it is a domain in the $allowed_domains array. If it is not it will kill the script. You can change the message it outputs to whatever you want. If it is a valid domain it will create the DB name string and save it in the variable $dbname

Next I changed the global YOURLS_DB_NAME to be $dbname instead of being static

define( 'YOURLS_DB_NAME', 'yourls');


define( 'YOURLS_DB_NAME', $dbname );

The last thing I changed was the static site URL to the dynamic one.

define( 'YOURLS_SITE', '' );


define( 'YOURLS_SITE', 'http://'.$domain );

Finish the config file as if it was a a normal config file for YOURLS

Visit each domain and install YOURLS

You can find this file on GitHub

Leave a Comment