Remove www using .htaccess
-
I’d like to canonicalize my URLs by removing the leading “www”. I’ve managed to do this site-wide using a .htaccess in the root web directory (/home/me/example.com/). This reads:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301]It’s working everywhere except in the directory containing my WordPress installation (/home/me/example.com/blog/), presumably because WordPress has already created a .htaccess in that folder, which reads:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>
# END WordPressSo I tried combining my .htaccess and WordPress’s, and came up with:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ https://example.com/blog/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>
# END WordPressThis works for almost everything:
https://www.example.com/blog/ > https://example.com/blog/
https://www.example.com/blog/archives/69 > https://example.com/blog/archives/69and URLs without the leading “www” are untouched. Great! Except, one slight problem:
https://www.example.com/blog > https://example.com/blog//home/me/example.com/blog
(note absence of trailing slash on pre-rewritten URL.) So, I feel like I’m nearly there, but I’ve been futzing around with this file for hours and have been unable to figure this out. Does anyone have any ideas?
- The topic ‘Remove www using .htaccess’ is closed to new replies.