TransWikia.com

htaccess www to non-www with subdomain

Craft CMS Asked by plaintxt on July 11, 2021

Our client has (sadly) presented a new site URL as www.foo.bar.com instead of foo.bar.com. I need to use .htaccess to remove the www. The site works correctly if www is not prepended to the URL.

This question comes close but implementing with a subdomain doesn’t work.

Here’s my .htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Redirect to non-www domain
    RewriteCond %{HTTP_HOST} !foo.bar.com$ [NC]
    RewriteRule ^(.*)$ http://foo.bar.com/$1 [R=301,L]

    # Send would-be 404 requests to Craft
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/(favicon.ico|apple-touch-icon.*.png)$ [NC]
    RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

To clarify, I would like to remove both www and index.php from all URLs. So:

http://www.foo.bar.com/yay -> http://foo.bar.com/yay

FWIW, this is hosted on Rackspace, which requires the Rewrite Base / directive.

One Answer

This question comes close but implementing with a subdomain doesn't work.

It should work as long as you modify the rewrite rule to account for the subdomain:

RewriteCond %{HTTP_HOST} !^foo.bar.com$ [NC]
RewriteRule ^(.*)$ http://foo.bar.com/$1 [R=301,L]

The code you posted was missing the ^ before foo.bar.com on the RewriteCond line. The purpose of that conditional is supposed to be to catch incoming requests where the domain isn’t exactly “foo.bar.com” (so that it can redirect them to the correct domain on the following line). However without that ^, the conditional would only catch requests where the domain doesn’t end with “foo.bar.com”. But “www.foo.bar.com” does in fact end with “foo.bar.com” so it’s not going to get caught.

Hope that makes sense.

Update:

Here’s a hostname-agnostic version that’s a little easier on the eyes:

RewriteCond %{HTTP_HOST} ^www.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Correct answer by Brandon Kelly on July 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP