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?
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).
Thanks it works. And also thank you for giving me proper understanding of this rule. I learnt it with this answer. Once again thank you :)