.htaccess fix non www pointing to www

Recently I noticed one of my forums sometimes wasn’t saving users choices of remembering them or allowing them to stay logged in. This is due to the cookie thinking www.domain.com and doamin.com (without www) as 2 different sites.

Below are two pieces of code to fix this issue.


Note: Be sure to put it at the top of your .htaccess file under “RewriteEngine On” or you’ll notice it won’t work. Also change my-domain.com to your domain. 

Redirect non-www to www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Redirecting www to non-www

If you want to do the opposite, the code is very similar:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^my-domain\.com$ [NC] RewriteRule ^(.*)$ http://my-domain.com/$1 [R=301,L]


Example of one of mine.

htaccess file www to non www etc

Show More

Cory Fiala

Technology and outdoor enthusiast. Currently the sole systems administrator for a local K-12 school district with 800+ staff and 5,500+ students. I support windows servers, Linux systems (FreeBSD and Ubuntu), along with vSphere (4 node cluster). 60+ virtual machines and 8 physical servers. This doesn't include my personal homelab.

Leave a Reply

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

Back to top button