Search code examples
.htaccesshttp-redirecthttp-status-code-301

How to redirect from non-www to www with correct page?


I am trying to 301-redirect example.com to www.example.com by .htaccess:

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

Problem: my-site.com/contact.html redirects to www.example.com/index.php instead of www.example.com/contact.html.

How can I accomplish that?

UPDATE: this is the complete .htaccess for my Joomla-site (comments stripped):

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
RewriteRule .* index.php [F]

###### this is the code in question...
RewriteCond %{HTTP_HOST} ^example$ [NC]
RewriteRule ^(.*)$ http://www.example/$1 [R=301,L]

# RewriteBase /

## Begin - Joomla! core SEF Section.
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteCond %{REQUEST_URI} /component/|(/[^.]*|\.(php|html?|feed|pdf|vcf|raw))$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]

# take care of sitemap.xml
RewriteCond %{REQUEST_URI} ^/sitemap.xml
RewriteRule .* /index.php?option=com_xmap&view=xml&tmpl=component&id=1&format=html [L]

I moved my two lines up just below RewriteEnigine On - but had the same problem again. Clueless.


Solution

  • Problem: example.com/contact.html redirects to www.example.com/index.php instead of www.example.com/contact.html.

    I'm going to guess that you have other rules in your htaccess file, one that routes everything to index.php. You need to make sure that your redirect rule is before any other rule that you have.


    After checking your htaccess file, you need to add an L flag at the end of your first rule:

    RewriteRule .* index.php [F,L]
    

    Because without it, the redirect gets applied even if the first rule gets applied (e.g. it gets rewritten to index.php with a 403 response waiting in the queue).