Search code examples
ruby-on-railsvanity-url

In Ruby on Rails, how can you use vanity URLs and also redirect to 404s?


At the end of my routes.rb, I have a wildcard match for vanity urls. However, I can't figure out how to redirect unknown usernames to a 404. How can you do this?

~ in routes.rb ~

# Vanity URLs
match ':username', :to => "users#show"

~ in the users controller ~

@user = User.find_by_username(params[:username])
if @user.nil?
  render :status => 404
else
  ...
end

Solution

  • What you have will still render the default template but, with a 404 response code.

    Try this to render the default 404 page instead:

    render :file => "#{Rails.root}/public/404.html", :layout => false, :status => 404