8

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

Community
  • 1
  • 1
Fenn-CS
  • 863
  • 1
  • 13
  • 30

1 Answers1

6

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.

Croises
  • 18,570
  • 4
  • 30
  • 47
  • 1
    Thanks Croises! You just got 50 more points! lol now please can you explain why it works in this order but does not work in the other which I placed it? Maybe like an update to your answer. – Fenn-CS Nov 19 '17 at 22:52
  • Can someone please help me with question in https://stackoverflow.com/questions/47475677/redirect-to-a-new-domain-using-apache-vhost-configuration – ThinkGeek Nov 26 '17 at 06:16