Home > Software design >  How to redirect to HTTPS in htaccess file in my framework setup?
How to redirect to HTTPS in htaccess file in my framework setup?

Time:04-08

I've built a php website working all fine with all the redirects except for http:// versions.

So I'm trying to edit my main .htaccess file to prevent http:// showing the error "NOT SECURE", and forward the user to https://

I've used a framework called TraversyMVC while building my website and it has the setup below in the public_html directory .htaccess file.

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

And this is my .htaccess file in the /public directory

<IfModule mod_rewrite.c>
  Options -Multiviews
  RewriteEngine On
  RewriteBase /public
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule  ^(. )$ index.php?url=$1 [QSA,L]
</IfModule>

This is what I've tried in my public_html directory .htaccess file but it didn't work:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{SERVER_PORT} 80
  RewriteCond %{REQUEST_URI} public/ [L]
  RewriteRule ^(.*)$ https://www.mywebsite.com/public/$1 [L]
</IfModule>

Looking for the correct solution.

Thanks

CodePudding user response:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} public/ [L]
RewriteRule ^(.*)$ https://www.mywebsite.com/public/$1 [L]

You are redirecting the request before the internal rewrite to the /public subdirectory (so the second condition that checks for public/ will never match) and /public should not be in the visible URL you are redirecting to. You should also be explicit that this is an external redirect, not an internal rewrite. (As written this rule would result in an implicit 302 - temporary - redirect.)

This needs to go before the existing rules in the root .htaccess file. Try the following instead:

RewriteCond %{HTTPS} off
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

Test first with a 302 (temporary) redirect to avoid potential caching issues.

You do not need the <IfModule> wrapper.

  • Related