Lovelock
Lovelock

Reputation: 8085

Correct way of handling www. and non www. when working with sessions

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.

Upvotes: 0

Views: 706

Answers (1)

Gergo Erdosi
Gergo Erdosi

Reputation: 42063

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]

Upvotes: 3

Related Questions