how to redirect sub pages to www to non-www from htaccess

Viewed 40

I am trying to redirect my subpage to a non-www but I get duplicate URLs of the same page.

What I want to implement

https://www.example.com/category/webs => https://example.com/category/webs
http://example.com/category/webs => https://example.com/category/webs
http://www.example.com/category/webs => https://example.com/category/webs

.htaccess

Options -Indexes
RewriteEngine On

RewriteRule ^category/([a-zA-Z0-9-/]+) category-list.php?id=$1 [NC,L]

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
</IfModule>

With this current code, my root domain redirects perfectly. but not subpages! I read many articles but not helping

1 Answers

The rule you have posted already does this, but your rules are in the wrong order. You need to redirect the request before rewriting the request to category-list.php. Otherwise, "subpages" will be redirected to category-list.php, which is what I assume is happening.

Aside: You should escape the literal hyphen in the character class ([a-zA-Z0-9-/]+), or move this to the start or end of the character class, to negate its special meaning. You should also include the end-of-string anchor at the end of the regex, otherwise it will successfully match too much (potentially creating duplicate content).

Try it like this instead:

Options -Indexes

RewriteEngine On

# Canonical redirect
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]

# Rewrite request
RewriteRule ^category/([a-zA-Z0-9/-]+)$ category-list.php?id=$1 [NC,L]

No need to repeat the RewriteEngine directive. No need for the <IfModule> wrapper.

Related