Redirecting all ServerAliases to a preferred domain with mod_rewrite

I had a domain that I owned three TLDs for. I had the .com, the .net, and the .org. These all go to the same site using ServerAlias directives in the apache config. As do the www versions of each. However, I preferred to have them all go to mysite.com with no www. To add to the confusion, the site allows (but does not require) SSL, so the user’s SSL state needed to be preserved during all this rewriting. Here is what I came up with, and it works great.

<ifmodule>
RewriteEngine On
RewriteCond %{HTTP_HOST}    !^mysite.com [NC]
RewriteCond %{HTTP_HOST}    !=""
RewriteCond %{SERVER_PORT}s ^(80s|443(s))$
RewriteRule ^(.*)          http%2://mysite.com/$1 [L,R=301]
</ifmodule>

About Aaron D. Campbell

Owner and lead developer at BlueDog, Aaron has 10+ years of web development experience, it a regular core contributor to the WordPress project, and has released many WordPress plugins.
This entry was posted in apache and tagged , , . Bookmark the permalink.

One thought on “Redirecting all ServerAliases to a preferred domain with mod_rewrite

  1. Y920.com says:

    ServerAlias directives in the apache config is one of the big source,

Leave a Reply

Your email address will not be published. Required fields are marked *

Note: If you are replying to another commenter, click the "Reply to {NAME} ↵" button under their comment!