Block https via htaccess for registered users

I am trying to force https for all registered users. In most of my applications, the user needs to be logged in, but I still have many pages that should be http only and others that should be served through both http (guest) and https (registered users) depending on the login status.

I am using Yii framework and want to force https for all pages for logged in user. Users are controlled through the module.

Here is my current .htaccess

Options +FollowSymLinks

IndexIgnore */*

RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.mysite.com/$1 [R=301,L]

#RedirectMatch 301 ^/tk/(.*)$ http://admin.mysite.com/$1
#RewriteRule ([a-z0-9-]+)/? http://$1.mysite.com [R=301,NC,L]

# if a directory or a file exists, use it directly

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php

#RewriteRule . index.php
RewriteRule .* index.php [QSA,L]

      

+3


source to share


4 answers


If you are using sessions or cookies, you will need to check the sessions, and if they are valid, redirect the user to the https site.



This needs to be done in PHP. There is no way to do this in pure .htaccess form.

+1


source


Rewriting rules are not the right solution: it takes too many resources.

Best use:



RedirectPermanent / https://domain.tld

      

and, if possible, not in the file .htaccess

, but in the apache config directly.

+1


source


If you are using named cookie session

for your sessions you can use RewriteCond to validate your session cookie

RewriteCond %{HTTP_COOKIE} session
RewriteRule .* https://www.mysite.com/$0 [R,L]

      

0


source


You can do this with filters.

Yii CFilter Documentation

Filter class example:

class CHttpsCheckFilter extends CFilter {

protected function preFilter($filterChain) {
    //place your checking logic here.
    //$filterChain->controller is yor targer controller
    //other useful methods and fields you can find in official documentation.
    if ( !Yii::app()->getRequest()->isSecureConnection ) {            
        $url = 'https://your-new-path';
        Yii::app()->request->redirect($url);
        return false;
    } else
        return true;
}

protected function postFilter($filterChain) {
    return true;   
}

      

then you need to attach this filter to the controller by injecting the method into it filters

:

public function filters()
{
    return array(
        'accessControl', // perform access control for CRUD operations
        array(
            'CHttpsCheckFilter',
        ),
    );
}

      

This is the basic functionality. You can add additional logic for filtering that can check the target controller for your custom method for additional rules ... or it can contain all the security rules in it.

0


source







All Articles