简体   繁体   中英

GitHub Project Pages: auto-redirect from sub-directory to sub-domain

I posted this question about a month ago regarding custom domains with Github Pages. I've since gotten everything set up and working correctly for both user/organization pages, as well as project pages.

My question this time is this: now that I have project page correctly set up to be available at both www.domain.com/project/ and project.domain.com is there a way to redirect users who may visit "sub-directory" to the more desirable "sub-domain" URL?

I spoke with GitHub support and they said that I could accomplish this redirect with javascript, but didn't offer any further information. They obviously don't allow .htaccess files or any other type of server-side redirects. Anyone have any ideas?

EDIT: I'm aware that this should be done with window.location.replace(); so what I really need to know is where in the repo this snippet should go.

If you are looking to redirect the user from www.domain.com/project/ to project.domain.com via JavaScript, you can add the following snippet to whatever resource exists at the URL:

var location = window.location;
if (
       location.hostname == "www.domain.com"
    && location.pathname.indexOf("/project") == 0
) {
    location.replace("http://project.domain.com");
}

(This is assuming that the resource at www.domain.com/project/ is an HTML page that can have JavaScript.) You'll want to add this as close to the top of the page as possible to reduce the amount of time before the redirect (when it does happen).

As an aside: I would recommend not redirecting the user and using canonical URLs to inform web crawlers what URL you like best. That is, adding the following to your <head> :

<link rel="canonical" href="http://project.domain.com">

Redirecting the user, especially after the whole page has loaded and JS has had time to execute is quite a poor user experience.

While you could do this with JavaScript, it may be better to use META tags for SEO purposes . You would add these tags to the head section of your www.domain.com/project/ page:

  <link rel="canonical" href="http://project.domain.com"/>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <meta http-equiv="refresh" content="0;url=http://project.domain.com" />

These tags will specify a canonical page (helps prevent "Duplicate Content" SEO penalties from Google), and initiate a redirect via page refresh with delay of 0 seconds.

Here's a sample page (generated by Jekyll Alias Generator plugin ) that uses this technique to redirect visitors who land on /register2 to the intended destination, /register

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM