This solution allows you to use true HTTP redirects via .htaccess — however, nothing involving .htaccess will work on GitHub pages because they do not use Apache.
As of May 2014 GitHub Pages supports redirects, but according to the jekyll-redirect-from Gem documentation they are still based on HTTP-REFRESH (using <meta>
tags), which requires full a page load before redirection can occur.
I don't like the <meta>
approach so I whipped up a solution for anyone looking to provide real HTTP 301 redirects within an .htaccess file using Apache, which serves a pre-generated Jekyll site:
First, add .htaccess
to the include
property in _config.yml
include: [.htaccess]
Next, create an .htaccess file and be sure to include YAML front matter. Those dashes are important because now Jekyll will parse the file with Liquid, Jekyll's templating language:
---
---
DirectoryIndex index.html
RewriteEngine On
RewriteBase /
...
Make sure your posts that require redirects have two properties like so:
---
permalink: /my-new-path/
original: blog/my/old/path.php
---
Now in .htaccess, just add a loop:
{% for post in site.categories.post %}
RewriteRule ^{{ post.original }} {{ post.permalink }} [R=301,L]
{% endfor %}
This will dynamically generate .htaccess every time you build the site, and the include
in your config file ensures that .htaccess makes it into _site
directory.
RewriteRule ^blog/my/old/path.php /my-new-path/ [R=301,L]
From there, it's up to you to serve _site
using Apache. I normally clone the full Jekyll repo into a non-webroot directory, then my vhost is a symlink to the _site
folder:
ln -s /path/to/my-blog/_site /var/www/vhosts/my-blog.com
Tada! Now Apache can serve the _site folder from your virtual root, complete with .htaccess-powered redirects that use whichever HTTP response code you desire!
You could even get super fancy and use a redirect
property within each post's front matter to designate which redirect code to use in your .htaccess loop.