I can not add www to the domain with htaccess

1

I'm using laravel, and I uploaded the project to the server and I can access the domain by both myDomain.com and www.myDomain.com. and I want you to always add the www.

The htaccess I have it in the following way ...

<IfModule mod_rewrite.c>    
  RewriteEngine On
  RewriteCond %{REQUEST_URI} !^/public/.*$    
  RewriteRule ^(.*)$ /public/$1 [QSA,L]
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
</IfModule>

I tried a thousand htaccess codes and can not automatically redirect to www.

    
asked by Juan Pablo 22.06.2016 в 19:44
source

2 answers

1

Regular expressions are correct and would be met, but your conditions prevent redirection from occurring.

  • RewriteCond %{REQUEST_URI} !^/public/.*$ - Check if the route /public/ appears in the requested URI,
  • RewriteRule ^(.*)$ /public/$1 [QSA,L] - If the condition is true, apply the rule, now look at the flags you place at the end of this condition:

    • [QSA] means adding, the condition is added to existing ones.
    • [L] means last , or last rule in English. After applying this rule, the .htaccess file stops processing.
  • It is no longer necessary for the following condition to be verified, because you have already found the L flag that stops everything.

  • On the other hand, the redirection always stops the processing of the following rules, because in strict sense example.com and www.example.com are two different domains.
  • Solution

    Remove the L tag from your first rule.

    <IfModule mod_rewrite.c>    
      RewriteEngine On
      RewriteCond %{REQUEST_URI} !^/public/.*$    
      RewriteRule ^(.*)$ /public/$1 [QSA]
      RewriteCond %{HTTP_HOST} !^www\. [NC]
      RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
    </IfModule>
    

    You can check all the options of the rediction rules in the official documentation .

    p>     
    answered by 22.06.2016 в 20:14
    0

    Try the second line to change it to RewriteBase

    <IfModule mod_rewrite.c>    
         RewriteEngine On
         RewriteBase %{REQUEST_URI} !^/public/.*$    
         RewriteRule ^(.*)$ /public/$1 [QSA,L]
         RewriteCond %{HTTP_HOST} !^www\. [NC]
         RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
    </IfModule>
    
        
    answered by 01.07.2016 в 01:02