diff --git a/domain_alias/domain_alias.admin.inc b/domain_alias/domain_alias.admin.inc
index ab119dd..f9b558d 100755
--- a/domain_alias/domain_alias.admin.inc
+++ b/domain_alias/domain_alias.admin.inc
@@ -332,3 +332,151 @@ function domain_alias_help_text() {
     to the domain record for <em>example.com</em>. NOTE: <em>Only one wildcard is allowed per alias.</em></p>');
   return $output;
 }
+
+function domain_alias_patterns_form($form, &$form_state) {
+  if (isset($form_state['aliases']['delete'])) {
+    $form['test_delete'] = array(
+      '#type' => 'item',
+      '#title' => t('Aliases to delete'),
+      '#markup' => '<p>' . t('The following aliases will be deleted.') . '</p>' . domain_alias_pattern_delete_results($form_state['aliases']['delete'], 'delete'),
+    );
+  }
+  if (isset($form_state['aliases']['create'])) {
+    $form['test_create'] = array(
+      '#type' => 'item',
+      '#title' => t('Aliases to create'),
+      '#markup' => '<p>' . t('The following aliases will be generated. Items marked as not valid will be skipped.') . '</p>' . domain_alias_pattern_create_results($form_state['aliases']['create'], 'create'),
+    );
+  }
+  $form['help'] = array(
+    '#markup' => domain_alias_help_text(),
+  );
+  $variables = array(
+    'items' => array(
+      '*.[hostname]',
+      '\2.example.com',
+      '\2.example.\1',
+      '?.[hostname]',
+      '[hostname]:*',
+    ),
+  );
+  $form['patterns'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Standard alias patterns when creating and updating domains.'),
+    '#rows' => 5,
+    '#cols' => 30,
+    '#default_value' => variable_get('domain_alias_patterns', NULL),
+    '#description' => t('Enter one pattern per line.  When creating or updating domains, an alias matching each pattern will be created.')
+      . domain_alias_patterns_help()
+      . '<p><em>' . t('Example patterns:') . '</em></p>'
+      . theme('item_list', $variables),
+  );
+  $form['update'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Create aliases for existing domains'),
+    '#description' => t('When submitting these changes, Domain Alias will create new aliases for all existing domains.'),
+    '#default_value' => 1,
+  );
+  $form['delete'] = array(
+    '#type' => 'checkbox',
+    '#title' => t('Delete aliases that do not match these patterns.'),
+    '#description' => t('Use with care. Recommended for expert users only.'),
+    '#default_value' => 0,
+  );
+  $form['actions']['test'] = array(
+    '#type' => 'submit',
+    '#value' => t('Test changes'),
+    '#submit' => array('domain_alias_patterns_test_submit'),
+  );
+  $form['actions']['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Save configuration'),
+    '#submit' => array('domain_alias_patterns_submit'),
+  );
+  return $form;
+}
+
+function domain_alias_patterns_help() {
+  $items = array();
+  foreach (domain_alias_pattern_list() as $key => $value) {
+    $items[] = t('<strong>!key</strong> !value', array('!key' => $key, '!value' => $value));
+  }
+  return '<p>' . t('The following replacements may be used in your alias patterns. Note that the order of numbered elements is right-to-left:')
+    . theme('item_list', array('items' => $items))
+    . t('Numbers up to 6 are allowed. Empty elements will be ignored.') . '</p>';
+}
+
+function domain_alias_pattern_list() {
+  return array(
+    '[hostname]' => t('The complete domain hostname, including a port, if provided. e.g. <em>example.com</em> or <em>foo.example.com:8080</em>.'),
+    '[port]' => t('The port identifier, if any. e.g. <em>8080</em>'),
+    '\1' => t('The first element of the domain. e.g. <em>com</em>.'),
+    '\2' => t('The second element of the domain. e.g. <em>example</em>.'),
+    '\3' => t('The third element of the domain, if present. e.g. <em>foo</em>.'),
+    '\4' => t('The fourth element of the domain, if present.'),
+  );
+}
+
+function domain_alias_patterns_form_validate($form, &$form_state) {
+  $patterns = $form_state['values']['patterns'];
+  $patterns = domain_alias_normalize_patterns($patterns);
+  foreach ($patterns as $pattern) {
+    $valid = domain_alias_valid_patterns();
+    $passed = FALSE;
+    foreach ($valid as $test) {
+      if ($test != '[hostname]' && $test != '[port]') {
+        if (substr_count($pattern, $test) > 0) {
+          $passed = TRUE;
+        }
+      }
+    }
+    if (!$passed && substr_count($pattern, '*') < 1 && substr_count($pattern, '?') < 1) {
+      form_set_error('patterns', t('Your patterns must each include at least one wildcard or token character.'));
+    }
+  }
+}
+
+function domain_alias_patterns_test_submit($form, &$form_state) {
+  $form_state['rebuild'] = TRUE;
+  $patterns = $form_state['values']['patterns'];
+  $aliases = domain_alias_build_patterns($patterns);
+  if (!empty($form_state['values']['update'])) {
+    $form_state['aliases']['create'] = $aliases;
+  }
+  if (!empty($form_state['values']['delete'])) {
+    $form_state['aliases']['delete'] = domain_alias_get_delete_patterns($aliases);
+  }
+}
+
+function domain_alias_patterns_submit($form, &$form_state) {
+  $patterns = $form_state['values']['patterns'];
+  variable_set('domain_alias_patterns', $patterns);
+  $patterns = domain_alias_build_patterns($patterns);
+  if (!empty($form_state['values']['delete'])) {
+    domain_alias_delete_patterns($patterns);
+  }
+  if (!empty($form_state['values']['update'])) {
+    domain_alias_save_patterns($patterns);
+  }
+
+}
+
+function domain_alias_server_form($form, &$form_state, $server = NULL) {
+  $form['domain_alias_servers'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Server matching patterns for domain aliases.'),
+    '#rows' => 5,
+    '#cols' => 30,
+    '#default_value' => variable_get('domain_alias_servers', NULL),
+  );
+  $form = system_settings_form($form);
+  return $form;
+}
+
+function domain_alias_overview_form($form, &$form_state) {
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('List changes'),
+  );
+  return $form;
+}
diff --git a/domain_alias/domain_alias.domain.inc b/domain_alias/domain_alias.domain.inc
index d599636..6db95ce 100644
--- a/domain_alias/domain_alias.domain.inc
+++ b/domain_alias/domain_alias.domain.inc
@@ -30,11 +30,53 @@ function domain_alias_domain_nav($domain) {
  * Adds a list of all aliases for the current domain.
  */
 function domain_alias_domain_load(&$domain) {
+  $active_alias = &drupal_static(__FUNCTION__);
   // Get the domain aliases
   $domain['aliases'] = domain_alias_list($domain['domain_id']);
   if (isset($domain['active_alias_id'])) {
+    $active_alias = $domain['active_alias_id'];
     $domain['aliases'][$domain['active_alias_id']]['active'] = TRUE;
   }
+  // Ensure that the active alias value stays set.
+  elseif (isset($active_alias)) {
+    $domain['aliases'][$active_alias]['active'] = TRUE;
+  }
+  // Don't run this too early in the process.
+  if (isset($domain['sitename']) && !empty($_SERVER['HTTP_HOST'])) {
+    domain_alias_match_servers($domain);
+  }
+}
+
+function domain_alias_match_servers($domain) {
+  $_domain = domain_get_domain();
+  $server_patterns = variable_get('domain_alias_servers', NULL);
+  if (!isset($_domain['active_alias_id']) || !isset($_domain['aliases']) || empty($server_patterns)) {
+    return;
+  }
+  $active = $_domain['active_alias_id'];
+  $alias = $_domain['aliases'][$active];
+  $rewrite = '[3].local';
+  domain_alias_server_replace($rewrite, $domain);
+}
+
+/**
+ * Implements hook_domain_insert().
+ *
+ * Creates any automatic aliases required by our settings.
+ */
+function domain_alias_domain_insert($domain, $form_values = array()) {
+  $patterns = variable_get('domain_alias_patterns', NULL);
+  $aliases = domain_alias_build_patterns($patterns, $domains = array($domain));
+  domain_alias_save_patterns($aliases);
+}
+
+/**
+ * Implements hook_domain_update().
+ *
+ * Creates any automatic aliases required by our settings.
+ */
+function domain_alias_domain_update($domain, $form_values = array()) {
+  domain_alias_domain_insert($domain, $form_values = array());
 }
 
 /**
@@ -47,3 +89,156 @@ function domain_alias_domain_delete($domain, $form_values = array()) {
     ->condition('domain_id', $domain['domain_id'])
     ->execute();
 }
+
+function domain_alias_build_patterns($patterns, $domains = array()) {
+  $aliases = array();
+  $patterns = domain_alias_normalize_patterns($patterns);
+  if (empty($domains)) {
+    $domains = domain_domains();
+  }
+  foreach ($patterns as $pattern) {
+    foreach ($domains as $domain) {
+      $alias = domain_alias_pattern_replace($pattern, $domain);
+      $aliases['entries'][] = array(
+        'alias' => $alias,
+        'domain_id' => $domain['domain_id'],
+        'pattern' => $pattern,
+      );
+      $aliases['list'][] = $alias;
+    }
+  }
+  return $aliases;
+}
+function domain_alias_normalize_patterns($patterns) {
+  $vars = preg_replace('/(\r\n|\n)/', "\r\n", $patterns);
+  $vars = explode("\r\n", $vars);
+  return $vars;
+}
+
+function domain_alias_pattern_replace($pattern, $domain) {
+  $find = domain_alias_valid_patterns();
+  $port = '';
+  $replace = array($domain['subdomain']);
+  $elements = explode(':', $domain['subdomain']);
+  if (isset($elements[1])) {
+    $port = array_pop($elements);
+  }
+  $replace[] = $port;
+  $items = array_reverse(explode('.', $elements[0]));
+  for ($i = 0; $i < 5; $i++) {
+    if (isset($items[$i])) {
+      $replace[] = $items[$i];
+    }
+    else {
+      $replace[] = '';
+    }
+  }
+  // Replace the strings.
+  $alias = str_replace($find, $replace, $pattern);
+  // Ensure we don't have multiple dots together.
+  $find = array('..', '...', '....', '.....');
+  $alias = trim(str_replace($find, '.', $alias));
+  // Prevent leading or trailing dot.
+  $alias = trim($alias, '.');
+  return $alias;
+}
+
+function domain_alias_valid_patterns() {
+  return array(
+    '[hostname]',
+    '[port]',
+    '\1',
+    '\2',
+    '\3',
+    '\4',
+    '\5',
+    '\6',
+  );
+}
+
+function domain_alias_get_create_patterns($patterns) {
+  $list = $patterns['list'];
+  foreach ($patterns['entries'] as $id => $data) {
+    // Set a temporary value so we don't check an item against itself.
+    $temp = $list[$id];
+    $list[$id] = NULL;
+    $patterns['entries'][$id]['errors'] = domain_alias_validate_alias($data, $list);
+    $list[$id] = $temp;
+  }
+  return $patterns;
+}
+
+function domain_alias_pattern_create_results($aliases) {
+  $aliases = domain_alias_get_create_patterns($aliases);
+  $variables['aliases'] = $aliases['entries'];
+  return theme('domain_alias_create_patterns', $variables);
+}
+
+function domain_alias_get_delete_patterns($patterns) {
+  $list = array();
+  $result = db_query("SELECT domain_id, alias_id, pattern, redirect FROM {domain_alias}", array(), array('fetch' => PDO::FETCH_ASSOC))->FetchAll();
+  foreach ($result as $data) {
+    $pattern = _domain_alias_placeholders_from_sql($data['pattern']);
+    if (!in_array($pattern, $patterns['list'])) {
+      $list[$pattern] = $data;
+    }
+  }
+  return $list;
+}
+
+function domain_alias_pattern_delete_results($aliases) {
+  $variables['aliases'] = $aliases;
+  return theme('domain_alias_delete_patterns', $variables);
+}
+
+function domain_alias_delete_patterns($patterns) {
+  $list = domain_alias_get_delete_patterns($patterns);
+  $ids = array();
+  foreach ($list as $data) {
+    $ids[] = $data['alias_id'];
+  }
+  if (!empty($ids)) {
+    db_delete('domain_alias')
+      ->condition('alias_id', $ids, 'IN')
+      ->execute();
+  }
+}
+
+function domain_alias_save_patterns($patterns) {
+  $aliases = domain_alias_get_create_patterns($patterns);
+  foreach ($aliases['entries'] as $alias) {
+    if (empty($alias['errors'])) {
+      $alias['pattern'] = _domain_alias_placeholders_to_sql($alias['alias']);
+      db_insert('domain_alias')
+        ->fields(array(
+          'domain_id' => $alias['domain_id'],
+          'pattern' => $alias['pattern'],
+          'redirect' => 0,
+        ))
+        ->execute();
+    }
+  }
+}
+
+function domain_alias_server_replace($pattern, &$domain) {
+  $host = $_SERVER['HTTP_HOST'];
+  $domain['canonical'] = $domain['subdomain'];
+  $parts = array_reverse(explode('.', $domain['canonical']));
+
+  for ($i = 0; $i < 6; $i++ ) {
+    $j = $i + 1;
+    $find[] = "[$j]";
+    if (isset($parts[$i])) {
+      $replace[] = $parts[$i];
+    }
+    else {
+      $replace[] = '';
+    }
+  }
+  $test = str_replace($find, $replace, $pattern);
+  $error = domain_valid_domain($test);
+  if (empty($error)) {
+    $domain['subdomain'] = $test;
+    $domain['path'] = domain_get_path($domain);
+  }
+}
diff --git a/domain_alias/domain_alias.module b/domain_alias/domain_alias.module
index 0447bf0..4e586d9 100755
--- a/domain_alias/domain_alias.module
+++ b/domain_alias/domain_alias.module
@@ -80,6 +80,37 @@ function domain_alias_menu() {
     'page arguments' => array(4),
     'file' => 'domain_alias.admin.inc',
   );
+  $items['admin/structure/domain/alias'] = array(
+    'title' => 'Alias patterns',
+    'access arguments' => array('administer domains'),
+    'type' => MENU_LOCAL_TASK,
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('domain_alias_patterns_form'),
+    'file' => 'domain_alias.admin.inc',
+  );
+  $items['admin/structure/domain/alias/settings'] = array(
+    'title' => 'Patterns',
+    'access arguments' => array('administer domains'),
+    'type' => MENU_DEFAULT_LOCAL_TASK,
+    'weight' => 10,
+  );
+  $items['admin/structure/domain/alias/servers'] = array(
+    'title' => 'Servers',
+    'access arguments' => array('administer domains'),
+    'type' => MENU_LOCAL_TASK,
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('domain_alias_server_form', 5),
+    'file' => 'domain_alias.admin.inc',
+  );
+  $items['admin/structure/domain/alias/list'] = array(
+    'title' => 'View aliases',
+    'access arguments' => array('administer domains'),
+    'type' => MENU_LOCAL_TASK,
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('domain_alias_overview_form', 5),
+    'file' => 'domain_alias.admin.inc',
+    'weight' => -5,
+  );
   return $items;
 }
 
@@ -95,6 +126,12 @@ function domain_alias_theme() {
     'domain_alias_block' => array(
       'variables' => array('domains' => array()),
     ),
+    'domain_alias_create_patterns' => array(
+      'variables' => array('aliases' => array()),
+    ),
+    'domain_alias_delete_patterns' => array(
+      'variables' => array('aliases' => array()),
+    ),
   );
 }
 
@@ -421,3 +458,114 @@ function domain_alias_features_api() {
   );
   return $components;
 }
+
+/**
+ * Theme a list of aliases to create.
+ */
+function theme_domain_alias_create_patterns($variables) {
+  $output = '';
+  $domains = domain_domains();
+  $aliases = $variables['aliases'];
+  $header = array(t('Domain'), t('Alias'), t('Pattern'), t('Create new alias'));
+  $rows = array();
+  foreach ($aliases as $alias) {
+    $row = array(
+      check_plain($domains[$alias['domain_id']]['subdomain']),
+      check_plain($alias['alias']),
+      check_plain($alias['pattern']),      
+      (empty($alias['errors'])) ? t('Yes') : t('No: !errors', array('!errors' => implode(' ', $alias['errors']))),
+    );
+    $rows[] = $row;
+  }
+  $variables['header'] = $header;
+  $variables['rows'] = $rows;
+  $output = theme('table', $variables);
+  return $output;
+}
+
+/**
+ * Theme a list of aliases to delete.
+ */
+function theme_domain_alias_delete_patterns($variables) {
+  $output = '';
+  $domains = domain_domains();
+  $aliases = $variables['aliases'];
+  $header = array(t('Domain'), t('Alias'));
+  $rows = array();
+  foreach ($aliases as $key => $alias) {
+    $row = array(
+      check_plain($domains[$alias['domain_id']]['subdomain']),
+      check_plain($key),
+    );
+    $rows[] = $row;
+  }
+  $variables['header'] = $header;
+  $variables['rows'] = $rows;
+  $output = theme('table', $variables);
+  return $output;
+}
+
+/**
+ * Helper function to validate alias entries.
+ *
+ * @param $alias
+ *  The alias pattern to test.
+ * @param $new_aliases
+ *  An array of aditional aliases that may be created during the requesting
+ *  action.
+ *
+ * @return
+ *   A valid alias string, or an error array.
+ */
+function domain_alias_validate_alias($pattern, $new_aliases = array()) {
+  $errors = array();
+  $alias = $pattern['alias'];
+  // 1) Check that the same alias is not entered twice.
+  if (in_array($alias, $new_aliases)) {
+    $errors[] = t('%name would be created more than once.', array('%name' => $alias));
+  }
+  // 2) Check that the alias only has one wildcard.
+  $count = substr_count($alias, '*') + substr_count($alias, '?');
+  if ($count > 1) {
+    $errors[] = t('You may only have one wildcard character in each alias.');
+  }
+  // 3) Only one colon allowed, and it must be followed by numbers only.
+  $count = substr_count($alias, ':');
+  if ($count > 1) {
+    $errors[] = t('You may only have one colon ":" character in each alias.');
+  }
+  elseif ($count == 1) {
+    $int = substr($alias, strpos($alias, ':') + 1);
+    if (!is_numeric($int) && $int != '*' && $int != '?') {
+      $errors[] = t('A colon may only be followed by an integer or a wildcard indicating the proper port.');
+    }
+  }
+  // 4) Check that the alias doesn't contain any invalid characters.
+  $check = preg_match('/^[a-z0-9\.\+\-\*\?:]*$/', $alias);
+  if ($check == 0) {
+    $errors[] = t('%name contains invalid characters.', array('%name' => $alias));
+  }
+  // 5) Check that the alias is not a direct match for a registered domain.
+  $check = preg_match('/[a-z0-9\.\+\-:]*$/', $alias);
+  if ($check == 1) {
+    $test = db_query("SELECT COUNT(domain_id) FROM {domain} WHERE subdomain = :alias", array(':alias' => $alias))->fetchField();
+    if ($test > 0) {
+      $errors[] = t('%name matches an existing domain record.', array('%name' => $alias));
+    }
+  }
+  // 6) Check that the alias or a pattern matching the same domain name does not exist.
+  $_pattern = _domain_alias_placeholders_to_sql($alias);
+  $_alias = db_query("SELECT alias_id, domain_id, pattern FROM {domain_alias} WHERE pattern = :pattern AND domain_id = :domain_id", array(':pattern' => $_pattern, ':domain_id' => $pattern['domain_id']))->fetchAssoc();
+  if (!empty($_alias)) {
+    $errors[] = t('%name matches <a href="!url" title="Edit aliases for domain !id">alias #!aid</a> (%existing).',
+      array(
+        '%name' => $alias,
+        '%existing' => _domain_alias_placeholders_from_sql($_alias['pattern']),
+        '!url' => url('admin/build/domain/alias/' . $_alias['domain_id']),
+        '!id' => $_alias['domain_id'],
+        '!aid' => $_alias['alias_id']
+      )
+    );
+  }
+  return $errors;
+}
