IMHO

The Answers Depend On The Question

Serving Rails From A Subfolder

Hang on a minute. I’m guzzling a beer right now after several hours trying to serve a Rails application from a subfolder on an exiting web site. All I can say is that the implementation is definitely not worth the work I did to find out how to get it working.

Here’s the scenario. Let’s say I have a web site that is serving PHP pages (think WordPress) from the url http://www.davidoshiro.com. I built a Ruby on Rails app on the same server that I want my visitors to access via http://www.davidoshiro.com/mytest. This seems trivial enough for those of us who have used Apache’s mod_rewrite a million times. But alas, trivial it is not.

So here is my Apache VirtualHost config:

That looks pretty standard. When someone requests http://www.davidoshiro.com/mytest, Apache sends them to my Rails app which is running on the same machine on port 10001 and tacks on the REQUEST_URI. All looks good. But what happens is I am able to access the Rails root route and nothing else!

So, http://www.davidoshiro.com/mytest brings up my starting page but none of the assets can be found and all of my helper links are not working. Let’s say I have a link on my starting page “New User” that goes to the users#index, the HTML link generated is http://www.davidoshiro.com/users. This is obviously not going to work because everything should be under “/mytest”. GRRRRRR!!!!

After trying everything under the sun and moon (by that I mean Google), I found out that all I needed to do was place all of my routes in a scope block. Here’s an example of my config/routes.rb file:

Now, all my links are being generated properly and I think I’m good to go. Whoa there horsey! I bring up the app and none of my stylesheets, javascript or images are being loaded.

I searched high and low on Google and after hours of trial and error (minus the fits of rage) I reached enlightenment. After setting up my Apache configuration and route.rb files, there were two more things I need to do. First, is to add the following line to my config/application.rb file:

This tells Rails where all of your assets are. Now, the stylesheet and javascript helper methods will generate the correct paths. And lastly, I need to update all of my references to my image assets. For example, in my css files I need to make sure that all url(‘/assets/image.png’) are corrected to url(‘/mytest/assets/image.png’) and don’t forget those HTML image tags.

That’s it. Now, I’m sure I will run into some issues with my jQuery-UI themes, but editing those should be simple enough.

Time for another beer!

Leave a Reply

Your email address will not be published. Required fields are marked *