Apache: Redirect requests where ServerName doesn't match
<p>I'm relatively new to Apache rewrite rules. What I need to do I think should be relatively easy, but I could use a bit of help.</p>

<p>I have a number of name based virtual hosts defined in my Apache configs, for developers to test new feature branches, and I have a wildcard DNS CNAME setup to direct traffic.</p>

<p>Everything works as it should when a request matches the ServerName in one of the virtual hosts. However if the hostname in the request doesn't match any explicitly defined virtual hosts, it automatically uses the first virtual host.</p>

<p>This is quite confusing, as a developer may think they're accessing the correct virtual host, when in fact they're not.</p>

<p>What I'd like to do, is define a rewrite rule in the first virtual host, so that if the hostname in the request doesn't exactly match the defined "ServerName", it will redirect it.</p>

<p>For example...</p>

<p>If I have 2 virtual hosts defined like so...</p>

<pre><code>&lt;VirtualHost *:443&gt;

    ServerName default.mydomain.com
    ...

&lt;/VirtualHost&gt;

&lt;VirtualHost *:443&gt;

    ServerName my-feature-1.mydomain.com
    ...

&lt;/VirtualHost&gt;
</code></pre>

<p>and a developer is trying to request the site for their new feature, but spell it incorrectly, i.e.</p>

<p><a href="https://feature-1.mydomain.com" rel="nofollow">https://feature-1.mydomain.com</a></p>

<p>The first virtualhost will silently serve the request, and they may be none the wiser, and wonder why their new feature code appears not to be working.</p>

<p>What I would like it to do instead. I'd like to redirect them to...</p>

<p><a href="https://default.mydomain.com" rel="nofollow">https://default.mydomain.com</a></p>

<p>so that it's obvious they've misstyped the URL.</p>