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?
-
Configure the Yoast plugin to redirect via .htaccess and not via PHP
-
If switching from PHP to .htaccess, edit at least one redirect so it will update the file.
-
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.
#!/usr/bin/ruby # Read all the redirect commands from the htaccess file, then loop through and update s3 for each # STATIC_SITE_NAME = 'www.example.com' # 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 `#{cmd}` # upload the empty file to s3 with the redirect command cmd = %(aws s3 cp --website-redirect https://#{STATIC_SITE_NAME}/#{to} \ #{file_path} \ s3://#{STATIC_SITE_NAME}/#{from}/index.html ) puts cmd `#{cmd}` end