Laravel .htaccess www, non-www,http and non-https redirection

Cyberac1d
0

 

In this turorial we will create a redirection of all non secure request to https://www and https://non-www type url for Laravel Projects.

For the SEO purpose most people prefer all the canonical URL to be start with "https://www", but we will cover both type of secure URL redirection in this tutorial.


For this to work you need create a .htaccess file in the public directory of your laravel project.

In the .htaccess file place the following code as it is to redirect all non secure URL to secure https://domainname.com/

    RewriteEngine On	
    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .	
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]	
    # Redirect Trailing Slashes If Not A Folder...	
    RewriteCond %{REQUEST_FILENAME} !-d	
    RewriteCond %{REQUEST_URI} (.+)/$	
    RewriteRule ^ %1 [L,R=301]	
    RewriteCond %{HTTPS}  !=on	
    RewriteRule ^/?(.*) https://domainname.com/$1 [R,L]	
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]	
    RewriteRule ^ %{REQUEST_SCHEME}://%1%{REQUEST_URI} [R=301,L]	
    # Send Requests To Front Controller...	
    RewriteCond %{REQUEST_FILENAME} !-d	
    RewriteCond %{REQUEST_FILENAME} !-f	
    RewriteRule ^ index.php [L]

In the .htaccess file place the following code as it is to redirect all non secure URL to secure https://www.domainname.com/

    RewriteEngine On
    # Start with www 
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
    RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]

    # 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}]
If you find this tutorial helpful please share it with others too.
Thanks

Post a Comment

0Comments

Thanks for sharing your feedback! It helps us grow.

Post a Comment (0)

Contact form