Yii 2.0: Key web server settings after installing a fresh Yii 2 basic or advanced app

33 followers

So, you have installed a brand new Yii 2 app (basic) or (advanced). Here are a few tips for Apache web server users to get things running more secure and better with your yii2 app.

Note: If you are using one of these templates yii2-app-practical, yii2-app-practical-a, or yii2-app-practical-b to install your app, then whatever is discussed here is already pre-configured.

1. Pretty URL

The default install displays URL on address bar in the GET format. You may want to set it to pretty urls in a format more understandable by search engines (and also by many users).

Step 1a: Set the following in your yii configuration file:

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        // your url config rules
    ]
]

Step 1b: Next, configure the .htaccess file in your app root to set index.php rewrite.

# 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

2. Prevent Viewing Folders / Index of Directories

This is more a security you would like to enable with your fresh yii 2 app. You do not want users browsing directories on your app. Set the "-Indexes" which will make Apache block users from browsing folders without a default document. This will prevent allowing anybody to surf through every folder on your server. Just set this in your .htaccess file:

<IfModule mod_autoindex.c>
  Options -Indexes
</IfModule>

3. Block Accesses to Hidden Directories

Block access to "hidden" directories whose names begin with a period. This includes directories used by version control systems such as Subversion or Git. Just set this in your .htaccess file:

<IfModule mod_rewrite.c>
  RewriteCond %{SCRIPT_FILENAME} -d
  RewriteCond %{SCRIPT_FILENAME} -f
  RewriteRule "(^|/)\." - [F]
</IfModule>

4. Block Accesses to Backup/Source files

Block access to backup and source files, which may be left by some text/html editors and pose a great security danger, when someone can access them. Just set this in your .htaccess file:

<FilesMatch "(\.(bak|config|sql|fla|psd|ini|log|sh|inc|swp|dist)|~)$">
  Order allow,deny
  Deny from all
  Satisfy All
</FilesMatch>

5. Increase cookie security

Just set this in your .htaccess file:

<IfModule php5_module>
  php_value session.cookie_httponly true
</IfModule>

Wiki Translations

Total 2 comments

#18394 report it
TSLSS at 2014/10/23 10:37am
Thank you

Simple and easy to understand.

#18228 report it
junaidatari at 2014/09/30 11:46am
Very nice

I found it very useful, 10+

Leave a comment

Please to leave your comment.

Write new article