0

Only today found out that the two are not the same site and infact copies of eachother.

The error i am currently having is i am setting on login sessions in the normal way:

$_SESSION['logged'] = 1;

This session can be received and works on

domain.com

But doesnt work when the user navigates to any:

www.domain.com

How should i handle this? I like to use absolute links for my navigation e.g:

http://www.domain.com/about

But this causes the issue of users not using www. all the time etc.

Is there a way to allow cookies to be set on both www. and non www or is there a better way of handling this? Possibly a htaccess type redirect to the non www. page everytime?

Thanks for any insight. Craig.

Lovelock
  • 7,689
  • 19
  • 86
  • 186

1 Answers1

3

You shouldn't use both example.com and www.example.com. You should select one and redirect the other. For example if you want to use www.example.com, then redirect example.com to www.example.com. You can do this easily in .htaccess:

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

Or in Nginx:

server {
    listen       80;
    server_name  example.com;
    return       301 http://www.example.com$request_uri;
}

If you want to redirect www.example.com to example.com, then you can use this:

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
  • Perfect! Works as expected. Quick question, if im choosing the non www. is it good practice to still keep the http:// for the rule? Or doesnt make a blind difference? – Lovelock Jun 12 '14 at 23:21
  • @user2921557 Added an example to my answer. There are many ways to do this, see the answers here: http://stackoverflow.com/questions/234723/generic-htaccess-redirect-www-to-non-www – Gergo Erdosi Jun 12 '14 at 23:25