Make *.example.com redirect to www.example.com

I want to make it so when people search for something.example.com, they’re redirected to www.example.com. However, I can’t create a page rule that redirects *.example.com to www.example.com since it would be a loop.

My site is only visible through www.example.com and not example.com, so I have a redirect from example.com to www.example.com, meaning I can’t make *.example.com redirect to just example.com. Is there a way to exclude the www subdomain from the page rule that redirects *.example.com to www.example.com?

Thanks for all help in advance!

Hi @pemigrade,

Are you on a Cloudflare Enterprise plan? If not then you can’t proxy wildcard records so you would have to add an :orange: DNS record for each subdomain you want to redirect.

Then with the page rule, probably the easiest way would be to create a dummy rule matching www.example.com/*, then below that one for *.example.com/* to forward to https://www.example.com. Because only one page rule fires per URL, www would not be redirected due to the dummy page rule.

1 Like

If the suggestion from dmojh isn’t an option you can also do it on the host, have a look at Mediacollege that might give you some pointers to do it with mod_rewrite.

Apache Configuration
To configure the redirects, add the following redirect rule either to the Apache config file if you have access to it, or to the .htaccess in the root of your site:

If instead of example.com you want the default URL to be www.example.com , then simply change the third and the fifth lines:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]
2 Likes

Thanks both of you! I think the two page rules that domjh suggested are the best solution.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.