4

I have a site that is about to launch and a request for URL Canonicalization has been made. I want to know what is the best way to have all requests for http://www.example.com to permanently redirect (301) to http://example.com within my RoR app? Or, asked another way, how can I strip the "www." from all generated urls, paths, requests?

FYI, this is a Rails 3 app.

Lance Roberts
  • 22,383
  • 32
  • 112
  • 130
Matt
  • 1,539
  • 1
  • 11
  • 16
  • Just noticed your requirement to do this within RoR app. You could do a before callback in the application controller and check the request's headers and redirect if it's the www version. However, I don't recommend doing it this way if not absolutely necessary, because the www requests are unnecessarily handled by your Rails stack when it could be processed by the (lightweight) front end web server like nginx or apache. – randomguy Feb 14 '11 at 23:23

2 Answers2

2

This is done using rewrite rules in the webserver.

For nginx: http://techtitbits.com/2010/07/wwwno-www-rewrite-rules-for-nginx/

For Apache: http://www.boutell.com/newfaq/creating/withoutwww.html

Also note that you should add two A records into your DNS zone file, like so

@ IN A 10.0.0.1
www IN A 10.0.0.1

with 10.0.0.1 replaced with your IP address.

randomguy
  • 12,042
  • 16
  • 71
  • 101
1

For Apache, You can add the code below to your /public/.htaccess file in your ROR app. I use this for most of my apps, because I don't like the 'www'

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

Hope this helps

David Barlow
  • 4,914
  • 1
  • 28
  • 24
  • I skipped trying to handle this within the Rails app itself and went for this standard .htaccess solution. Thanks – Matt Feb 21 '11 at 16:52