I have a Rails application that uses a static_pages controller to render static pages within the application and I am looking for the best solution to perform a 301 redirect of specific pages – an example would be /dentist redirected to /dentist-london
I am using Rails 2.3.8.
The static_pages controller looks like this:
class StaticPagesController < ApplicationController
def display
if static_page_exists?
render_static_page
else
raise ActiveRecord::RecordNotFound
end
end
protected
def static_page_exists?
File.exists? template_path
end
def template_path
File.join('app', 'views', 'static_pages', file_name)
end
def render_static_page
render :template => File.join('static_pages', file_name)
end
def file_name
File.join(params[:path]) + '.html.haml'
end
end
This controller matches the pages to the name of the static page and renders the content.
The route looks like this:
map.static_page '*path', :controller => 'static_pages', :action => 'display'
I can rename the page app/views/static_pages/dentist.html.haml file to app/views/static_pages/dentist-london.html.haml however I am not sure how to perform the 301 redirect on this change.
Can anyone offer any advice?
I think I have included all the relevant code but feel free to ask if anything is missing/doesn’t make sense.
Thanks in advance
If your static mapping set is known and you can infer it via a regex than I would put them in some file of your own devising and then use some Rack middleware to load the file, parse it, and then inspect all incoming requests.
It sounds like there isnt much of a reason for it to go all the way through your Rails stack, hence a middleware approach is more optimal.
Maybe your mapping file is something like:
Where if you split on
,than the first column is the “source” and the second column is the “destination” to be redirected to. Put that in a Hash for quick lookups and you’re off.