How to make Yii Application Secure to work only on HTTPS

I am using Yii 2.0, Apache and Debian. This howto take into assumption that you arleady have SSL certificate set up

on your machine.

First we create your apache configuration for your site. Replace xx.xx with your site. In this example I am using domain without www in the front of it.

In your apache conf site configuration add:

In /etc/apache2/site-enabled/mysite.conf

Redirect any traffic from 80 to https

1 <Virtualhost>
2 ServerName
3 Redirect “/” “;
4 </Virtualhost>

Create your site https configuration and connect it with SSL certificate
6 <VirtualHost>
7 ServerAdmin
8 DocumentRoot “/var/www/yourSite/web”
9 ServerName
10 ServerAlias *
11 SSLEngine On
12 SSLCertificateFile /etc/ssl/certs/xx.crt
13 SSLCertificateKeyFile /etc/ssl/private/xx.key
14 </VirtualHost>

restart apache service apache2 restart

In your site directory create .htaccess

touch .htaccess then edit vi .htaccess

then paste the following: (

RewriteEngine On
# prevent httpd from serving dotfiles (.htaccess, .svn, .git, etc.)
RedirectMatch 403 /\..*$
# 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
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

This configuration will allow only https access to your site and all the links will work if you generate them using Url class

<p><a class=”btn btn-lg btn-success” href=”<?php echo Url::to([‘login’]) ?>”>Click here to Login</a></p>

Hope this will work for you the same as it work for me.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s