Static WordPress Community

Redirects set in Yoast Plugin

We have 2 sites we’re converting over to static. The smaller on is currently using the Static HTML Output plugin and using a manual script to sync to s3 via crontab. On both sites we use the Yoast SEO Premium plugin to set redirects - for example once events are past they often get renamed and a redirect created from the old to new URL.

We discovered that the redirects do not work on the static site export, and I didn’t see any way to handle them in the plugin itself, so I wanted to share this quick-n-dirty script I wrote to export the Yoast redirects to S3.

Anyone have an easier way to do this?

  1. Configure the Yoast plugin to redirect via .htaccess and not via PHP

  2. If switching from PHP to .htaccess, edit at least one redirect so it will update the file.

  3. Run this ruby script (no, not PHP or bash - I’m faster in Ruby, so that’s how I did it). YMMV. You’ll need to make sure the ‘aws’ command line script is also installed and configured.

     # Read all the redirect commands from the htaccess file, then loop through and update s3 for each
     STATIC_SITE_NAME = '' # should also match your S3 bucket name
     ROOT_DIR = '/path/to/your/site/public_html'
     raw_redirects=`grep Redirect #{ROOT_DIR}/.htaccess`
     raw_redirects.split("\n").each do |r|
       rp = r.chomp.split(" ")
       type = rp[1].to_i
       next if type != 301 # only looking for 301s for now, but may expand later
       from = rp[2].gsub(/\"/,'').gsub(/^\//,'')
       to = rp[3].gsub(/\"/,'').gsub(/^\//,'')
       dir = "#{ROOT_DIR}/wp-content/uploads/static-html-output/#{from}"
       file_path = "#{dir}/index.html"
       # remove the original file and create an empty one to re-upload
       cmd = "rm -rf #{dir} && mkdir -p #{dir} && touch #{file_path}"
       puts cmd
       # upload the empty file to s3 with the redirect command
       cmd = %(aws s3 cp --website-redirect https://#{STATIC_SITE_NAME}/#{to} \
              #{file_path} \
       puts cmd
1 Like

Brilliant, @ncrosno, thanks for sharing this!

Whilst not in Static HTML Output, the WP2Static repo on GitHub got some support for redirects a little while back.

I need to update the docs for all projects (thinking ReadTheDocs), but you can find the WP2STATIC_REDIRECT_CODES reference in the src.

There was a pull request also in that repo that didn’t get merged in, but was doing something with htaccess to S3 rewrites specifically.

As I get back into the coding groove and update the docs, I may be able to pull the redirect handler/hooks from WP2Static into Static HTML Output.

In the new docs, it would be great to have a section specific for user-contributed “recipes” such as this.