Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

301 redirect non-www to www

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

like image 377
Fenn-CS Avatar asked Nov 17 '17 16:11

Fenn-CS


People also ask

Do I need to redirect to non-www?

For most users, it is not of particular importance whether they access a website via a www or a non-www link. However, the fact that a website is accessible with or without the input of “www” can seriously impact a website's search engine ranking.


1 Answers

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.

like image 188
Croises Avatar answered Oct 12 '22 10:10

Croises