Forum Moderators: open

Message Too Old, No Replies

Force canonical domain

         

ocon

12:51 am on May 31, 2016 (gmt 0)

10+ Year Member Top Contributors Of The Month



I have to use javascript to force some redirects. I know this is not ideal, but due to technical limitations it is the only tool I can use.

I want to make sure all my users are on "https://www.example.com" while still allowing the page to be viewed locally (to make it easier to work with).

if(window.location.hostname !== 'www.example.com' && window.location.hostname !== '') window.location = 'https://www.example.com/';

I'm running into some problems I'm hoping someone would be able to help me with.

If the user is coming from http://example.net:80/?x=1#hash I'd like them to go to https://www.example.com/?x=1#hash but they're now just going to https://www.example.com/

I tried the following but was getting errors.

if(window.location.hostname !== 'www.example.com' && window.location.hostname !== '') window.location = window.location.replace(window.location.hostname, 'www.example.com');

Is there a better approach using javascript?

ocon

2:25 am on Jun 1, 2016 (gmt 0)

10+ Year Member Top Contributors Of The Month



I think I figured it out. Replace was being used on an object which resulted in an error.

I'm now using host instead of hostname in case users would specify a port in the url. I'm also specifying the domain rather than just replacing it.

Using the script below, are there any unexpected issues I might have?

if(window.location.protocol+'//'+window.location.host !== 'https://www.example.com' && window.location.host !== '') window.location = 'https://www.example.com'+window.location.pathname+window.location.search+window.location.hash;

robzilla

9:26 am on Jun 1, 2016 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You would've had to use window.location.href for the replace function, but your second script is probably the better one anyway. I assume you have rel=canonical to inform the search engines of the redirects, too?