How Do I Add a WordPress Blog to My Rails App?

I wanted to have a robust blog for my Rails app, but I didn’t want to spend too much time on it. Initially I created a simple model (Articles) and added TinyMCE in it, but I ran into some challenges in how photos were displaying, and other styling aspects. I could’ve spent more time on it, but it was starting into eating into the time I was spending on developing enhancements to the app itself.

You can easily create a WordPress instance and map it to a subdomain. For example, blog.foo.com.

The problem with that, as discussed by SEO experts, Moz.com, is that it can hurt your search engine optimization efforts (SEO). Instead, it’s better to use a subdirectory like: foo.com/blog.

I was able to set-up my blog this way with the help of Dipesh Batheja’s article.

Here’s the exact steps I took:

(1) Added the domain (foo.com) to a WordPress hosting account on Siteground (my host)

(2) Using cPanel on Siteground, I created a subdomain, ‘blog’ for my domain (so I now could use blog.foo.com)

(3) In cPanel, I used “Let’s Encrypt” to add an SSL certificate to my subdomain (now I could use httpS://blog.foo.com)

(4) Installed WordPress (in cPanel) to my subdomain

(5) I went to my DNS records and added two A records – http://www.blog.foo.com, and blog.foo.com, each pointing to the IP address of my domain on Siteground. After the DNS propagated, I could go to the URL https://blog.foo.com and see my WordPress instance.

(6) In my Rails app, I added the Rack Reverse Proxy gem to my gemfile:

gem "rack-reverse-proxy", require: "rack/reverse_proxy"

(7) ‘bundle update’ to get the gem installed

(8) In config/application.rb, I added this:

config.middleware.insert(0, Rack::ReverseProxy) do 
  reverse_proxy_options force_ssl: true, replace_response_host: true

   reverse_proxy(/^\/blog(\/.*)$/, 'https://blog.foo.com$1', opts = { preserve_host: true })
end

(9) In routes.rb, I added this route:

get "/blog", to: redirect('https://www.foo.com/blog/', status: 301)

(10) In WordPress, in General Settings, I set:

WordPress Address (URL): https://blog.foo.com/

Site Address (URL): https://www.foo.com/blog (I’ve found that when I want to change a post, I need to change this temporarily to https://blog.foo.com/)

Now, every time someone goes to foo.com/blog, they’re redirected to my WordPress blog, and my SEO isn’t hurt.