Reputation: 45
301 Redirect by htaccess all URLs with any subdomains in a subdirectory to non-www
Examples:
https://www.example.com/forum
to https://example.com/forum
https://anysubdomains.example.com/forum
to https://example.com/forum
https://www.example.com/forum/anysubdiretory
to https://example.com/forum/anysubdirectory
https://anydubdomains.example.com/forum/anysubdiretory
to https://example.com/forum/anysubdirectory
The code below works only for www but how to make it work for all subdomains:
RewriteEngine on
#the directory the rule should apply to
RewriteCond %{REQUEST_URI} ^/forum/ [NC]
#check if the host string starts with "www"
RewriteCond %{HTTP_HOST} ^www\. [NC]
#redirect all www urls to non-www
RewriteRule (.*) https://example.com%{REQUEST_URI} [L,R=301]
Upvotes: 1
Views: 73
Reputation: 41219
To match any subdomains including www
, you can use a regex pattern that matches everything . Your RewruteCondition currently only matches a www
subdomain , replace it with a wildcard match RewriteCond %{HTTP_HOST} ^(.+)\.example\.com$ [NC]
.
You can use the following :
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/forum
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com$ [NC]
RewriteRule (.*) https://example.com%{REQUEST_URI} [L,R=301]
Make sure to clear your browser cache before testing this new redirect.
Upvotes: 1