简体   繁体   中英

Redirect www to the main domain without www with 301

I have a main domain "my_domain.com" and a few sub domains ("sub1.my_domain.com", "sub2.my_domain.com"...). It's possible to request a main domain as "my_domain.com" and "www.my_domain.com".

I need to redirect all the requests from "www.domain.com/.../any_url" to "domain.com" with the status 301. Or, preferably, all the requests from "www.domain.com/.../any_url" to "domain.com/.../any_url".

I've read some tutorials but didn't understand what's the standard and simplest way to do that. The web site is working on Rails, Passenger, Apache and Linux.

Here's what I have in /etc/apache2

root@my_user# ls -al 
total 88
drwxr-xr-x   7 root root  4096 Dec 26 19:22 .
drwxr-xr-x 111 root root  4096 Dec 23 03:27 ..
-rw-r--r--   1 root root  8346 Feb  6  2012 apache2.conf
drwxr-xr-x   2 root root  4096 Dec 26 19:09 conf.d
-rw-r--r--   1 root root  1322 Feb  6  2012 envvars
-rw-r--r--   1 root root     0 Dec 26  2013 httpd.conf
-rw-r--r--   1 root root 31063 Feb  6  2012 magic
drwxr-xr-x   2 root root 12288 Apr 16  2014 mods-available
drwxr-xr-x   2 root root  4096 Dec 30  2013 mods-enabled
-rw-r--r--   1 root root   750 Feb  6  2012 ports.conf
drwxr-xr-x   2 root root  4096 Sep 22 13:22 sites-available
drwxr-xr-x   2 root root  4096 Sep 22 13:22 sites-enabled

How can I do that? How do it by mod_rewrite, apache2.conf, /etc/apache2/sites-available/my_domain.com or using some other way? I'm confused.

update:

# ls -al /etc/apache2/sites-available
total 32
drwxr-xr-x 2 root root 4096 Sep 22 13:22 .
drwxr-xr-x 7 root root 4096 Dec 26 19:22 ..
-rw-r--r-- 1 root root 2716 May 16  2014 my_site-old
-rw-r--r-- 1 root root 1499 Sep 22 13:22 my_site.my_domain123.com
-rw-r--r-- 1 root root  950 Feb  6  2012 default
-rw-r--r-- 1 root root 7469 Feb  6  2012 default-ssl
-rw-r--r-- 1 root root 1511 Dec 30  2013 puppetmaster

Refer this to load mod_rewrite.

Use below rule where you have defined ServerName www.domain.com

<VirtualHost *:80>

  ServerName www.domain.com
  # Your existing customizations
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
  RewriteRule ^(.*)$ http://domain.com$1 [R=301,L]

</VirtualHost>

I did it like this: edit the application_controller.rb , so you can apply the "filter" to all other controllers.

root@Ecommerce:/# nano /home/NAMEAPP/app/controllers/application_controller.rb

into the file, put this:

class ApplicationController < ActionController::Base
before_filter :redirect_subdomain

    def redirect_subdomain
      if request.host == 'www.dominio.cl'
        redirect_to 'http://dominio.cl' + request.fullpath
      end
    end
end

您可以尝试使用rack-rewrite gem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM