I searched many articles on the internet but it could not work.
Probably because this is a strange requirement. I would be surprised if you could find any code that you could simply copy/paste that does this.
However, assuming you are constructing the correct absolute URL for all your internal links (since you must not internally link to a URL that redirects) then this is relatively trivial to implement in .htaccess
if you understand your existing directives.
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
The regex .*
in the RewriteRule
pattern matches everything. Specifically, it matches 0 or more of any character, as denoted by the *
quantifier. It matches the empty URL-path (ie. the "homepage") and every non-empty URL-path (ie. everything else).
You need to alter the above regex so that it matches a non-empty URL-path (ie. everything except the homepage). And create another rule (in the other direction) that matches an empty URL-path only.
(This uses the fact that mod_dir is serving index.php
for requests to the homepage, not the mod_rewrite directives that follow.)
To match 1 or more (ie. non-empty URL-path), you can use the +
(plus) quantifier, instead of *
(star/asterisk).
For example:
# Redirect everything except the homepage (from www to non-www)
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.+)$ https://example.com/$1 [L,R=301]
# Redirect the homepage only (from non-www to www)
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^$ https://www.example.com/ [L,R=301]
You will need to clear your browser cache before testing, since the earlier 301 (permanent) redirect that redirected the homepage from www to non-www will have been cached by the browser.
Test first with 302 (temporary) redirects to avoid potential caching issues.