July 26th, 2007 Cell phone safe redirecting with mod_rewrite
This is an update to Redirecting all ServerAliases to a preferred domain with mod_rewrite. In that article I solved a problem that I was having where I needed to redirect all ServerAlias options to just one domain, preserving the ssl preference. However, we have a lot of users on cell phones. Some of the simple cell phones (like the Motorolla Razr) do NOT like addresses that are missing the www. A simple url like http://mysite.com?u=user&p=password would not work, because it didn’t store the session cookie properly. Adding a www causes the cookies to work, but our ssl certificate is for mysite.com and having the www in that case causes warnings, and I still wanted to redirect our .net and .org TLDs. I ended up deciding that having the www would be ok as long as the user was NOT trying to use SSL. Here is how I did it:
<ifmodule> RewriteEngine On RewriteCond %{SERVER_PORT}%{HTTP_HOST} !^(443|80(www\.)?)?mysite\.com [NC] RewriteCond %{HTTP_HOST} ^(www\.)? RewriteCond %{SERVER_PORT}s%1 ^80s(www\.)?|443((s)(www\.))?$ RewriteRule ^(.*) http%3://%1mysite.com/$1 [L,R=301] </ifmodule>
Again, this is in the .htaccess file. In the end, a user using SSL is always sent to https://mysite.com. Standard connections are redirected to .com, but their www selection is preserved.