简体   繁体   中英

Redirect from the domain with www to the root domain - working but not completely properly

What I need is to redirect from www.my_website123.com to my_website123.com for any url www.my_website123.com/some_thing to my_website123.com/some_thing . I have this in the file /etc/apache2/sites-available/sub_domain123.main_domain123.com

<VirtualHost *:80>
  ServerName my_website123.com
  ServerAlias www.my_website123.com
  ServerAlias sub_domain123.my_website123.com
  ServerAlias files.my_website123.com
  ServerAdmin admin@my_website123.com
  #DocumentRoot /var/sub_domain123/public
  DocumentRoot /web/sub_domain123.my_website123.com/current/public
  ErrorLog /var/log/apache2/sub_domain123_errors.log
  LogLevel warn
  CustomLog /var/log/apache2/sub_domain123_access.log combined
  SetEnv RAILS_ENV production
  Header set Access-Control-Allow-Origin "http://sub_domain456.my_website123.com"
  Header set Access-Control-Allow-Credentials true
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^www\.my_website123\.com$ [NC]
  RewriteRule ^(.*)$ http://my_website123.com/$1 [R=301,L]

  <Directory /var/sub_domain123/public>
    Allow from all
    Options -MultiViews
  </Directory>
</VirtualHost>

<VirtualHost *:443>
 .....

Where

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

is what I added. Then I did this:

a2enmod rewrite
/etc/init.d/apache2 restart

It almost works properly. However:

curl -I http://www.my_website123.com
HTTP/1.1 302 Found
Date: Sun, 28 Dec 2014 04:12:04 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 3.0.21
Cache-Control: no-cache
  1. Do I have to delete ServerAlias www.my_website123.com ?
  2. Do I have to rename ServerName my_website123.com to be ServerName www.my_website123.com
  3. It redirects me www.my_website123.com/login to http://my_website123.com//login which is OK except the fact that it contains the double slash ( .com//login ). How do I remove it?
  4. Why does it return 302 status code instead of 301?

You will need to remove a trailing slash / in RewriteRule ( Reference ). Also, need a ServerName and ServerAlias as it is. So, updated rule will look like below.

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

Not sure why should it return 302 . But, try with the updated rule and see what response you get.

Good Luck!

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