The .htaccess(hypertext access) is a directory level configuration file for Apache web server. Using the .htaccess file server administrator can manipulate the Apache’s main configuration. Configuration made in the root folder .htaccess file is applied to parent and all sub directories. The .htaccess configuration should be done with great care slight syntax error in configuration can result in severe server malfunction.

Add/Edit .htaccess file

The .htaccess file is hidden by default to show the .htaccess file so change the folder settings to view the file. Advised file permission of .htaccess file is 644.

Change default Index page

DirectoryIndex main.php

Using this snippet you can change the default index page to any other file you want.After this configuration request to FOLDER/ Apache will serve FOLDER/main.php

File/Folder Access Control

.htaccess configuration is the best option to control the control the direct access to file and folders

#disable direct access
deny from all

This snippet prevent the direct user access to the folder

Block Directory Listing

#Block Directory Browsing
Options All -Indexes

or

IndexIgnore * 

This configuration prevents the directory listing

Rewrite URLs using htaccess

Clean url gives a better search engine rankings.

Rewriting codelikeaboss.com/userprofile.php?user=adhunanand to codelikeaboss.com/adhunanand

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ userprofile.php?user=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ userprofile.php?user=$1

IP Blocking using .htaccess

Blocking IP in .htaccess is pretty simple add the below snippet in your .htaccess file.

allow from all
deny from 184.171.254.45 

Prevent Image Hotlinking using .htaccess

This snippet will show mydomain.com/images/default.jpg when somone tries to hot link the image hosted on your server.

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mydomain\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpg|gif|bmp|png)$ /images/default.jpg [L]

Password protect a directory

After adding this snippet server will ask for authentication

AuthType Basic
AuthName "Administration Area"
AuthUserFile /path/to/.htpasswd
Require valid-user

Create yout .htpasswd using This link

Password protect wordpress wp-admin directory

Add a .htaccess file with above directory protect snippet on wp-admin/ folder.

AuthType Basic
AuthName "Admins Area"
AuthUserFile /path/to/.htpasswd
Require valid-user

Some themes and plugins use admin-ajax.php for ajax actions so add exception for the file admin-ajax.php on .htaccess file.

<Files admin-ajax.php>
    Order allow,deny
    Allow from all
    Satisfy any 
</Files>

Remove index.php in codeigniter

Add this .htaccess snippet to remove index.php from url.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]  

Also add this line on application/config/config.php

$config['index_page'] = '';