views:

40

answers:

2

Hi,

I have a Rails+Apache+Passenger setup and my app serves wildcard subdomains. I need all www URLs to redirect to their non www equivalents.

  • www.example.net should redirect to example.net
  • www.subdomain.example.net should redirect to subdomain.example.net

My current vhost config is as below

<VirtualHost *:80>

  ServerName  example.net
  ServerAlias *.example.net

  DocumentRoot /home/public_html/example.net/current/public

  RailsEnv staging

</VirtualHost>

I tried an assortment of rewrite rules in various locations but none took effect. I've checked to make sure that the apache rewrite module is enabled and RewriteEngine is on. Not sure what I'm missing. All help much appreciated!

A: 

You can use moderewrite in your .htaccess file.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.net [NC]
RewriteRule ^(.*)$ http://example.net/$1 [R=301,NC]

RewriteCond %{HTTP_HOST} ^www\.subdomain\.example\.net [NC]
RewriteRule ^(.*)$ http://subdomain.example.net/$1 [R=301,NC]

This should work in but I not test it.
or this

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,NC,L]
jcubic
I tried putting these conditions in an .htaccess file under the public folder of my rails app but it dint work. Also, I'm serving wildcard subdomains so how should the rewrite condition and rule look for that?
Vinay
A: 

I solved this issue in my app, as I have logic based on the domain anyway. Place this code in your ApplicationController

class ApplicationController < ActionController::Base
    before_filter :check_host

    def check_host
        if request.host.split('.')[0] == 'www'
            redirect_to "http://" + request.host.gsub('www.','')
        end
    end
end

Could have special cases if some of your hostnames contain "www." for any other reason that you'd have to code for.

Joshua
I'd like to avoid doing this on a code level simply because it should ideally occur before the code is hit.
Vinay