How to redirect domain from http to https using .htacces and cakephp

Viewed 1678

My app is hosted on heroku, and I am using Cakephp API. I want it to be redirect to https://www. and enforcing the www. subdomain.

And, they have two domains point to the same app.

I have the follow code, in the /app/.htaccess

RewriteEngine on

RewriteBase /

#apply if no https
RewriteCond %{HTTPS} off    
#Ignore when is local env or any staging env
RewriteCond %{HTTP_HOST} !^local(.*) [NC]
RewriteCond %{HTTP_HOST} !^(.*)heroku(.*) [NC]

RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

#apply if https
RewriteCond %{HTTPS} on
#Ignore when is local env or any staging env or subdoamin is www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^local(.*) [NC]
RewriteCond %{HTTP_HOST} !^(.*)heroku(.*) [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

#default from cakephp
RewriteRule ^$ webroot/ [L]
RewriteRule (.*) webroot/$1 [L]

I have the follow code, in the /app/webroot/.htaccess

RewriteEngine On

RewriteBase /

#redirect any request from .poa.br to .com.br
RewriteCond %{HTTP_HOST} ^(.*)example\.poa\.br$ [NC]
RewriteRule ^(.*)$ https://www.example.com.br/$1 [NE,R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

But it doesn't work. Just the follows requests are redirect to https://www.example.com.br:

https://www.example.com.br 
https://www.example.poa.br 
http://www.example.poa.br 

This option go to domain, but without https prefix.

http://www.example.com.br 

The other options doesn't work (return DNS_PROBE_FINISHED_NXDOMAIN):

https://example.com.br 
http://example.com.br 
https://example.poa.br 
http://example.poa.br
5 Answers

In cakephp3 I struggled with this. My solution was to change the first .htaccess file from

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*)   webroot/$1    [L]
</IfModule>

TO

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP:X-Forwarded-Proto} =http
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302]
    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*) webroot/$1    [L]
</IfModule>

Notice the 302, the reason I struggled is that the .htaccess got cached and made testing very difficult, I even went as far as delete all the cakephp code in the index.php in the webroot and just echo out 'test' Once I got it working I changed the 302 to 301 so that the .htaccess can hard cache in the browser. ( To test if values like HTTP:X-Forwarded-Proto exist I var_dump($_SERVER) in the index.php file )

IF you are on a server without HTTP:X-Forwarded-Proto

<IfModule mod_rewrite.c>
    RewriteEngine On 
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302]

    RewriteRule    ^$    webroot/    [L]
    RewriteRule    (.*) webroot/$1    [L]
</IfModule>
Related