2013-02-15 186 views
3

我想強制所有登錄用戶的https。我的大多數應用程序都需要用戶登錄,但我仍然有許多頁面只能是http和其他應該通過http(guest)和https(登錄用戶)提供的頁面,具體取決於登錄狀態。通過htaccess強制https登錄用戶

我正在使用Yii框架並希望強制https登錄用戶的所有頁面。用戶通過一個模塊進行控制。

這裏是我當前的.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] 
+2

考慮到您已經設置了證書,有沒有任何理由不對所有用戶一直使用https? – Jerry 2013-02-15 21:07:05

+0

是的,我已經設置了證書,所有用戶都一直在使用https進行下載嗎? – enfield 2013-02-15 21:23:18

+0

性能受到影響,但除非您的網站非常繁忙,否則您不會注意到它。 – Jerry 2013-02-15 21:27:37

回答

1

如果使用會話或cookies,您將需要檢查的會話,如果它們是有效的,然後將用戶重定向到HTTPS站點。

這需要在PHP中完成。沒有辦法在純粹的.htaccess中做到這一點。

+0

感謝您的反饋,是的,我正在使用會話,這是我希望登錄用戶保留在https上的原因之一。我不確定如何執行您所指的檢查會話然後重定向到https。除非你的意思是做這樣的事情? 'Yii :: app() - > user-> isGuest'我的關注是在閱讀了這個[在Yii中強制HTTPS]之後出現的(http://www.yiiframework.com/forum/index.php/topic/25407-forcing- https-in-yii/page__view__findpost__p__124744) – enfield 2013-02-15 21:26:31

0

如果你使用你的會話命名session的cookie,你可以使用的RewriteCond來測試您的會話cookie

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

重寫規則不正確的解決方案:它需要太多資源。

更好地利用:

RedirectPermanent/https://domain.tld 

如果可能的話,不是在.htaccess文件,而是直接在Apache的配置。

+1

回顧過去並做一些測試,我最喜歡這種方法。我會在接受更多測試後接受答案。感謝您的意見。 – enfield 2013-02-17 21:32:48

0

你可以用過濾器做到這一點。

Yii CFilter documentation

樣品過濾器類:

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; 
} 

然後,你需要這個過濾器連接到控制器,通過實施它filters方法:

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

這是基本功能。您可以添加額外的邏輯來過濾,這可以檢查您的自定義方法的目標控制器的額外規則...或者它可能包含其中的所有安全規則。