Www.sitename.com and sitename.com HELP

Hi I have a website which uses Ajax to post data to the server.

But if people go to the site without the www. prefix (sitename.com) then the data doesn’t post to database because the post url is www.sitename.com /postdata.php

If the user goes to www.sitename.com with the prefix then everything works correctly.

How can i get the users to always go the site with the www. prefix or get the ajax post code to work with both www. and without the www. prefix.

Found the answer, I needed to edit the .htaccess file with the lines below and this now changed all http://sitename.com pages to http://www.sitename.com.

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

The window.location object is great for inspecting the URL, but unfortunately offers basically no help at all in detecting whether or not the user typed “www” or not.

So you’ll have to just parse it yourself. Here’s a good all-purpose way to do that:


var hasWWW = /^www\\./.test(location.host);

Then you can use that hasWWW variable when building the URL where you send your AJAX request:


var ajaxURL = hasWWW ? 'http://www.' : 'http://';
ajaxURL += 'sitename.com/postdata.php';

Edit

Or you can make a change in your .htaccess to force the www :smiley:

You might want to use relative urls so you never have this problem.