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.
PHP function to Redirect a user with a message
One of the common things that you need to do in PHP is redirect a user, and display a message on whatever page you are sending them to. There are a lot of reasons for this, but the most common is to avoid a user refresh from resubmitting a form. Instead, process the form data, and redirect the user (even if you redirect them to the same page). Here is a function I use for this very purpose. It requires that you are using sessions. It stores the message in the session, and passes a has in the URL. This way, you can use any length message you want, and display it only once.
Read more
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>


