1

Here is my Ruby on Rails code to redirect a request from https://example.com to https://www.example.com:

class ApplicationController < ActionController::Base
before_filter :add_www_subdomain

private

    def add_www_subdomain
      if Rails.env.production?
        unless /^www/.match(request.host)
          redirect_to("#{request.protocol}www.#{request.host_with_port}",status: 301)
        end
      end
    end
end

Now the issue is, when someone lands at https://example.com/product/abc they are being redirected to https://www.example.com supposedly, they should go to https://www.example.com/product/abc. Is there any trick for this? Thanks

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
d3bug3r
  • 2,492
  • 3
  • 34
  • 74

1 Answers1

2
redirect_to("#{request.protocol}www.#{request.host_with_port}#{request.fullpath}",status: 301)

I think this kind of redirect is more suited to the web server. These are the rules:

Apache

<VirtualHost *:80>
  ServerName example.com
  Redirect permanent / http://www.example.com/
</VirtualHost>

source

NGINX

server {
    listen 80;
    server_name www.domain.com;
    # $scheme will get the http protocol
    # and 301 is best practice for tablet, phone, desktop and seo
    return 301 $scheme://domain.com$request_uri;

}

server {
    listen 80;
    server_name domain.com;
    # here goes the rest of your config file
    # example 
    location / {

        rewrite ^/cp/login?$ /cp/login.php last;
        # etc etc...

    }
}

source

Community
  • 1
  • 1
amalrik maia
  • 478
  • 5
  • 11