Warm tip: This article is reproduced from serverfault.com, please click

How to redirect site from www to non-www

发布于 2020-11-28 18:10:13

I have codeigniter project and I have .htaccess with the following :

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

Now I want to keep this as I do not want index.php in the address bar.

I have a domain example.com. Now when I try https://www.example.com then it must redirect to https://example.com.

How can I do that with the .htaccess file above?

Questioner
user3997016
Viewed
0
MrWhite 2020-11-29 04:44:54

Place the following directives before your existing rule to redirect everything from www to non-www.

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

The %1 backreference contains the hostname, less the www. prefix, from the preceding CondPattern ie. the value of (.+?).

The REQUEST_URI server variable contains the root-relative (starting with a slash) URL-path that was requested.

This also removes an optional trailing dot on the hostname, should a FQDN be requested, eg. www.example.com.. This requires the preceding capturing group to be non-greedy, ie. (.+?), as opposed to simply (.+) (which would capture the trailing dot).