Sunday, November 26, 2017

301 redirect non-www to www

Leave a Comment

I am trying to redirect all non-www to www on my website! My SSL is already configured to redirect all http to https but all what I have found is working only partially for me!

if I type mysite.com/en/articles/12/how-to-code, for example I am redirected to www.mysite.com/index.php which should have been www.mysite.com/en/articles/12/how-to-code

I have tried solutions to this SO question, I know this question is a possible repeat but other solutions have not worked for me! Am using apache2.

This my .htaccess in the /public folder

<IfModule mod_rewrite.c>     <IfModule mod_negotiation.c>         Options -MultiViews     </IfModule>      RewriteEngine On      # Redirect Trailing Slashes If Not A Folder...     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule ^(.*)/$ /$1 [L,R=301]      # Handle Front Controller...     RewriteCond %{REQUEST_FILENAME} !-d     RewriteCond %{REQUEST_FILENAME} !-f     RewriteRule ^ index.php [L]      # Handle Authorization Header     RewriteCond %{HTTP:Authorization} .     RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]      # Redirect to www     RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$     RewriteCond %{HTTPS}s ^on(s)|     RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule> 

Thanks in advance

1 Answers

Answers 1

Change the order, and redirect before rewrite:

<IfModule mod_rewrite.c>     <IfModule mod_negotiation.c>         Options -MultiViews     </IfModule>      RewriteEngine On      # Redirect Trailing Slashes If Not A Folder...     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule ^(.*)/$ /$1 [L,R=301]      # Redirect to www     RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$     RewriteCond %{HTTPS}s ^on(s)|     RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]      # Handle Front Controller...     RewriteCond %{REQUEST_FILENAME} !-d     RewriteCond %{REQUEST_FILENAME} !-f     RewriteRule ^ index.php [L]      # Handle Authorization Header     RewriteCond %{HTTP:Authorization} .     RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] </IfModule> 

Because if you redirect after rewriting the URL, this is the last version that will be modified and returned for the redirection request.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment