Table of contents

.htaccess is a configuration file of apache, it privoides way for us to custome some behavious of apache.

.htaccess files provide a way to make configuration changes on a per-directory basis.

if you need to create a whole new .htaccess file in windows, you need save as ”.htaccess” with quots

In general, you should never use .htaccess files unless you don’t have access to the main server configuration file.


  1. Custom Error Pages
  2. Disabled Directory Listing
  3. Deny/Allow Certian IP Addresses
  4. Redirection
  5. Password Protection
  6. MIME Type Settings
  7. Index Pages Settings
  8. URL Rewrite
  9. Default Pages

Custom Error Pages

Using Redirect Pages

    ErrorDocument 400 404.html
    ErrorDocument 401 401.html
    ErrorDocument 402 402.html

Using inline html

    ErrorDocument 404 "<html><body>找不到</body></html>"

Using URL

    ErrorDocument 500

Disabled Directory Listing

    <Files ~ "^.(htaccess|htpasswd)$">
    deny from all
    Options Indexes
    order deny,allow

    <Files ~ "^.(htaccess|htpasswd)$">
    deny from all
    Options -Indexes
    order deny,allow

Access restrictions

    deny from all
    allow from all
    deny from
    deny from

Deny/Allow Certian IP Addresses


what’s difference between Moved Permanently and Moved Temporarily

301 Moved Permanently

    Redirect permanent old1 new1
    Redirect permanent /path/old2 /path/new2
    Redirect permanent /path/old3.html /path/old3.php

302 Moved Temporarily

    Redirect temp old1 new1
    Redirect temp /path/old2 /path/new2
    Redirect temp /path/old3.html /path/old3.php

Password Protection

Basic authentication

  • STEP 1 Create your .htpasswd
  • STEP 2 Point the path to the .htpasswd file
    <Files ~ "^.(htaccess|htpasswd)$">
    deny from all
    Options -Indexes
    AuthUserFile /home/foo/bar/.htpasswd
    AuthGroupFile /dev/null
    AuthName "Please enter your ID and password"
    AuthType Basic
    require valid-user
    order deny,allow

MIME Type Settings

Index Pages Settings

DirectoryIndex index.html index.htm index.cgi

URL Rewrite

Setup WWW

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^(mydomain\.com)(:80)? [NC]
    RewriteRule ^(.*)$1 [R=301,L]


RewriteEngine on
RewriteCond %{HTTP_REFERER} !^*$ [NC]
RewriteCond %{HTTP_REFERER} !^$ [NC]
RewriteRule .*\.(*)$ /content/no_hotlink.png [R,NC]

RewriteRule .*\.(*)$ /content/no_hotlink.png [R,NC] this means if somebody try to hot linking you resource, he will redirect to /content/no_hotlink.png

Default Pages

    DirectoryIndex index.php mypage.html