Apache Canonical Rewrite with Passenger (mod_rails)

Posted on

Apache Canonical Rewrite with Passenger (mod_rails) – Managing your servers can streamline the performance of your team by allowing them to complete complex tasks faster. Plus, it can enable them to detect problems early on before they get out of hand and compromise your business. As a result, the risk of experiencing operational setbacks is drastically lower.

But the only way to make the most of your server management is to perform it correctly. And to help you do so, this article will share nine tips on improving your server management and fix some problem about apache-2.2, ruby-on-rails, phusion-passenger, virtualhost, .

I have a rails app served via Passenger (mod_rails) that I want to have a canonical URL.

I want all requests to go to http://mydomain.com (so, rewrite http://www.mydomain.com to http://mydomain.com).

On my other non-Rails apps, I accomplish this using mod_rewrite and an .htaccess file with the following:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(.+)mydomain.com$ [NC]
RewriteRule ^(.*)$ http://mydomain.com/$1 [R=301,L]

However, this doesn’t seem to work with Passenger. I’ve tried all sorts of combinations of placing the .htaccess file (in the public directory), and moving the directives around (in the vhost configuration), but I can’t get this to work.

How can I accomplish this?

Solution :

Try replacing that last line by the following:

RewriteRule ^(.*) http://mydomain.com%{REQUEST_URI} [R=permanent,QSA,L]

If that still fails, I recommend to use a separate virtual host for the URL www.mydomain.com that just does a Rewrite to mydomain.com. Passenger doesn’t play well with mod_rewrite.

Hope this helps.

UPDATE: Apparently I was running an older version of Passenger (don’t know how I missed that). I’m currently running Passenger 2.2.9 and putting the original rewrite in the vhost works as expected (and desired)!

Google group discussion on workarounds for older versions of Passenger: http://groups.google.com/group/phusion-passenger/browse_thread/thread/5e019e5d65beb54f

For older versions:

Host the www as a separate vhost and redirect (Jonathan Clarke’s suggestion)

RedirectMatch 301 ^(.*)$ http://mydomain.com$1

Do the rewrite in-app:

# before_filter :trim_www 
def trim_www 
  if request.subdomains.first == "www" 
    if request.subdomains == ["www"] 
      redirect_to "#{request.protocol}#{request. 
      subdomains = request.subdomains.shift.join(".") 
      subdomains << "." unless subdomains.blank? 
"#{request.protocol}#{subdomains}#{request.domain}#{request.port_string}#{r equest.path}" 

(Props to RSL in the original post for this code)

Leave a Reply

Your email address will not be published.