Getting www.mydomain to redirect to mydomain?

December 11, 2014 1.7k views

This must be a common question, but apparently I keep doing the wrong thing. I'm a new developer on a project, and the way the app was set up, a user can open ourproject.com and www.ourproject.com in two different tabs and run two different sessions - say, s/he starts with a tab open to ourproject.com, logs in and browses for a while, if s/he then opens another one to www.ourproject.com it won't know that s/he's logged in and will prompt him/her to do it again. What we would like is for both www.ourproject.com and ourproject.com to resolve to the same place, so that, whichever the user types in, the www would effectively be either stripped or appended (doesn't even much matter which) before the page loads, so the two are identical.

When I came on board there was a CNAME record set to www/@. I deleted that, and added one for */@, but all that's done is make so a user could now have an infinite number of sessions open by inventing arbitrary prefixes. I have now deleted that, but it seems like what that means is www.ourproject.com is going to stop working, which isn't great either, obviously - people tend to add www's to the fronts of domain names even when they're not needed, and we don't want those people to get an error page.

We're registered with Enom, and have the name servers there pointing to Digital Ocean's. The only thing I know about the project on the server side is that we're running Ubuntu and Unicorn.

What am I missing?

2 comments
  • Have you considered using 301 redirection via htaccess (apache mod) ??

    http://httpd.apache.org/docs/2.0/howto/htaccess.html

  • Hunky, we're using nginx, not apache, but I tried to proceed and do that. However, when I open up my server block (by sshing into our server as root and opening etc/nginx/sites-available/default) the server_name field in the server block doesn't list our domain name, it just says localhost. So now I'm unsure how to proceed. Any further insight would be greatly appreciated.

2 Answers

Your server is unicorn, that mean your project is a rails app?

If your session is handled by cookies, you may change all session cookies to shared cookies.
Then no matter which domain your user visit will have the same session.

Ref: http://api.rubyonrails.org/classes/ActionDispatch/Cookies.html

Alternatively you can rewrite www to non www or non www to www to ensure single point access.

Thanks for the replies. I opted to do a 301 redirect in Nginx and found this very clear stackoverflow post on how to do it: http://stackoverflow.com/questions/7947030/nginx-no-www-to-www-and-www-to-no-www

However, when I open up my server block (by sshing into our server as root and opening etc/nginx/sites-available/default) the server_name field in the server block doesn't list our domain name, it just says localhost. So now I'm unsure how to proceed. Anyone got any further help?

Have another answer? Share your knowledge.