Top 5 Apache settings for a new Yii 2 app

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 application.

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 the following settings are pre-configured and already available.

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

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]

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

5. Increase cookie security

Just set this in your .htaccess file to enhance the cookie security settings for your application:

<IfModule php5_module>
    php_value session.cookie_httponly true

These key settings should help get you kick started with a secure Yii application for most scenarios. As mentioned earlier, you can choose to install one of these templates yii2-app-practical, yii2-app-practical-a, or yii2-app-practical-b, to automatically set these once your app is installed.