Search code examples
regexapache.htaccesshttp-redirectmod-rewrite

htaccess redirect from www to non-www


I am new to this.

Code from my .htaccess file goes like this:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L] 

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

Redirect 301 /abc/ /abcnew/

I want this to redirect from www to non-www i.e., from http://www.example.com to http://example.com

I copied:

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

this code from here Generic htaccess redirect www to non-www.

I also checked in /etc/apache2/mods-enabled folder on my linux server. There "rewrite.load" this module is present.(I think this might mean that rewrite is enabled on my server, but correct me if I am wrong.)

Redirect 301 /abc/ /abcnew/

and just FYI this above code works fine(its redirecting my old links to new links).

I also tried this.

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

Doesn't work for me.

Please help. Thanks in advance...

Edit:

this link I found this. But not sure what should be edited. Can anyone please point out.?


Solution

  • You need to place external (full) redirect rules before internal rewrite ones and also make sure to use mod_rewrite rules only.

    Try this:

    RewriteEngine on
    RewriteBase /
    
    RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
    RewriteRule ^(.*) http://%1/$1 [R=301,NE,L]
    
    RewriteRule ^abc/?$ /abcnew/ [L,NC,R=301]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule .* index.php/$0 [PT,L]