shaam Posted November 29, 2010 Share Posted November 29, 2010 Hi, I want to redirect pages e,g 'http://mydomain.com/pagename.html' to 'http://www.mydomain.com/pagename.html",i.e if anyone access without www then it will be added automatically,how can i do this using javascript? plz help Thanks Quote Link to comment https://forums.phpfreaks.com/topic/220110-redirect-pages-to-www-using-javascript/ Share on other sites More sharing options...
haku Posted November 29, 2010 Share Posted November 29, 2010 In all honesty, this isn't something that should be done in javascript, it should be done at the server level. The reason is that if you do it in javascript, the person will have to download the javascript, the javascript will then redirect the user, which will then send another request to the server, and the user will have to download the page, including the javascript from before, all again. If it's done on the server side, the browser makes a request to the server, the server sees that the URL is wrong, and sends the user the data for the proper page. Much faster and better. You can do it in an .htaccess file with the following: RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301] (note: you will need to change both 'example.com' to your actual domain name) Quote Link to comment https://forums.phpfreaks.com/topic/220110-redirect-pages-to-www-using-javascript/#findComment-1140802 Share on other sites More sharing options...
shaam Posted November 29, 2010 Author Share Posted November 29, 2010 Thanks for your reply,yes u r right it should b through .htaccess but i have problem on server mod_rewrite is not enable that's y i want to do this using javascript. Is it possible using javascript ? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/220110-redirect-pages-to-www-using-javascript/#findComment-1140816 Share on other sites More sharing options...
haku Posted November 29, 2010 Share Posted November 29, 2010 If you can't do it through the .htaccess, then you'd be better off using a PHP redirect then. Basically, anything non-javascript or HTML is a better solution. Quote Link to comment https://forums.phpfreaks.com/topic/220110-redirect-pages-to-www-using-javascript/#findComment-1140848 Share on other sites More sharing options...
shaam Posted November 29, 2010 Author Share Posted November 29, 2010 Hi, after some googling i have found the solution and its working great,following is the code i have used, <!-- enURL = document.URL; if(enURL.indexOf("www") == -1 ) { location.href = enURL.replace("http://", "http://www."); } // --> Quote Link to comment https://forums.phpfreaks.com/topic/220110-redirect-pages-to-www-using-javascript/#findComment-1140850 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.