2

I am using htaccess to rewrite any www url to a non-www version

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

When I type domain.com/about it works fine, however when I type www.domain.com/about it changes the URL to domain.com/index.php?p=about

I have 'omitScriptNameInUrls' => true, enabled. I also have this in my .htaccess file

RewriteEngine On

# 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]

What am I doing wrong here?

Edit: Here is the the vhost file.

<VirtualHost *:80>
    ServerName domain.com
    ServerAdmin [email protected]
    DocumentRoot /var/www/

    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
2

2 Answers 2

1

Check out the official Apache documentation on Canonical domain rewrites: https://httpd.apache.org/docs/2.4/rewrite/remapping.html#canonicalhost

1
  • Thanks. I have had a look through these, none of the changes I have made has fixed the issue. I am hosting the site on Digital Ocean, not sure if that affects anything in the vhost or htaccess setup
    – zizther
    Commented Jan 9, 2017 at 23:00
1

The answer to this question was the positioning of content in the .htaccess file.

Move:

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ %{ENV:PROTO}://%1%{REQUEST_URI} [R=301,L]

Before this:

# 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]

Although the L tag was in the previous statement, it should be the last rule applied, it doesn't work (probably because I was activating the RewriteEngine again later so it resets the rules, but if the L flag was active in the first rule, it wouldn't apply the www one anyway).

The rule of thumb is: first do your cosmetic changes to the domain, then apply the functional rules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.