.htaccess – Snippets

What is .htaccess?
.htaccess is a configuration file for use on web servers running the Apache Web Server software.

When a .htaccess file is placed in a directory which is in turn ‘loaded via the Apache Web Server’, then the .htaccess file is detected and executed by the Apache Web Server software.

If you use a local Windows OS, you need:

1.Create a .txt file ‘name.htaccess’, write the code
2.Upload to a Apache Server
3.Rename it inside the server to ‘.htaccess’ (without name), using your sFTP program.

NOTICE: Windows OS does not allow a file without a name!

Folder Password Protection

Create .htpasswd
/home4/lucedigi/.htpasswd

NOTICE: The best way is to create .htpasswd outside the public folder (usually www)


myusername:mypassword

Create .htaccess in
/home4/lucedigi/public_html/blog/wp-admin/.htaccess


AuthType Basic
        AuthName "Restricted Area"
        AuthUserFile "/home/[username]/.htpasswds/public_html/passwd"
        require valid-user

The protection is limited to the folder where .htaccess is installed

File Protection

Create .htpasswd
/home4/lucedigi/.htpasswd


myusername:mypassword

Create .htaccess in
/home4/lucedigi/public_html/blog/wp-admin/.htaccess


AuthType Basic
        AuthName "Restricted Area"
        AuthUserFile "/home/[username]/.htpasswds/public_html/passwd"
        require valid-user

<Files "mypage.html">
  Require valid-user
</Files>

mypage.html and .htaccess have to be installed in the same folder!

For file list protection:


         <FilesMatch "(secure\.html)|(secure\.txt)">
          AuthType Basic
          AuthName "Restricted Area"
          AuthUserFile "/home/[username]/.htpasswds/public_html/passwd"
          Require valid-user
        </FilesMatch>

Blocking Requests from Particular User Agents


RewriteEngine On  
RewriteBase /  
SetEnvIfNoCase Referer "^$" bad_user
SetEnvIfNoCase User-Agent "^badbot1" bad_user
SetEnvIfNoCase User-Agent "^badbot2" bad_user
SetEnvIfNoCase User-Agent "^badbot3" bad_user
Deny from env=bad_user

Blocking Requests from Particular User Agents

You need to have mod_rewrite enabled


<IfModule mod_rewrite.c>
 
RewriteEngine on
 
RewriteCond %{HTTP_REFERER} bannedurl1.com [NC,OR]
 
RewriteCond %{HTTP_REFERER} bannedurl2.com [NC,OR]
 
RewriteRule .* - [F]
 
</ifModule>

Changing a Default Index Page


DirectoryIndex mypage.html

404 Redirect


# 404 Redirect

ErrorDocument 404 http://www.lucedigitale.com