List of .htaccess Examples

Some Good Official Tutorials

Sample .htaccess file from htaccess Google Group

#=============================================================================#
#          MAIN SETTINGS AND OPTIONS
#=============================================================================#
# Options: ALL,FollowSymLinks,Includes,IncludesNOEXEC,SymLinksIfOwnerMatch
###########

### MAIN DEFAULTS ###
Options +ExecCGI -Indexes
DirectoryIndex index.html index.htm index.php
DefaultLanguage en-US
AddDefaultCharset UTF-8
ServerSignature Off

### ENVIRONMENT VARIABLES ###
#SetEnv PHPRC /webroot/includes
#SetEnv TZ America/Indianapolis
#SetEnv SERVER_ADMIN webmaster@domain.tld

### MIME TYPES ###
AddType video/x-flv .flv
AddType application/x-shockwave-flash .swf
AddType image/x-icon .ico

### FORCE FILE TO DOWNLOAD INSTEAD OF APPEAR IN BROWSER ###
#-> http://www.htaccesselite.com/htaccess/addtype-addhandler-action-vf6.html
#AddType application/octet-stream .mov .mp3 .zip 

### ERRORDOCUMENTS ###
ErrorDocument 404 "404 error"
ErrorDocument 400 "400 error"
ErrorDocument 401 "401 error"
ErrorDocument 403 "403 error"
ErrorDocument 405 "405 error"
ErrorDocument 406 "406 error"
ErrorDocument 409 "409 error"
ErrorDocument 413 "413 error"
ErrorDocument 414 "414 error"
ErrorDocument 500 "500 error"
ErrorDocument 501 "501 error"

#=============================================================================#
#          SCRIPTING, ACTION, ADDHANDLER
#=============================================================================#
# Handlers be builtin, included in a module, or added with Action directive
# default-handler: default, handles static content (core)
#      send-as-is: Send file with HTTP headers (mod_asis)
#      cgi-script: treat file as CGI script (mod_cgi)
#       imap-file: Parse as an imagemap rule file (mod_imap)
#     server-info: Get server config info (mod_info)
#   server-status: Get server status report (mod_status)
#        type-map: type map file for content negotiation (mod_negotiation)
#  fastcgi-script: treat file as fastcgi script (mod_fastcgi)
###########

### PARSE AS CGI ###
#AddHandler cgi-script .cgi .pl .spl

### RUN PHP AS APACHE MODULE ###
#AddHandler application/x-httpd-php .php .htm

### RUN PHP AS CGI ###
#AddHandler php-cgi .php .htm

### CGI PHP WRAPPER FOR CUSTOM PHP.INI ###
#AddHandler phpini-cgi .php .htm
#Action phpini-cgi /cgi-bin/php5-custom-ini.cgi

### FAST-CGI SETUP WITH PHP-CGI WRAPPER FOR CUSTOM PHP.INI ###
#AddHandler fastcgi-script .fcgi
#AddHandler php-cgi .php .htm
#Action php-cgi /cgi-bin/php5-wrapper.fcgi

### CUSTOM PHP CGI BINARY SETUP ###
#AddHandler php-cgi .php .htm
#Action php-cgi /cgi-bin/php.cgi

### PROCESS SPECIFIC FILETYPES WITH CGI-SCRIPT ###
#Action image/gif /cgi-bin/img-create.cgi

### CREATE CUSTOM HANDLER FOR SPECIFIC FILE EXTENSIONS ###
#AddHandler custom-processor .ssp
#Action custom-processor /cgi-bin/myprocessor.cgi

#=============================================================================#
#          HEADERS, CACHING AND OPTIMIZATION
#=============================================================================#
#-> http://www.htaccesselite.com/htaccess/cache-control-http-headers-vt65.html
#      300   5 M
#     2700  45 M
#     3600   1 H
#    54000  15 H
#    86400   1 D
#   518400   6 D
#   604800   1 W
#  1814400   3 W
#  2419200   1 M
# 26611200  11 M
# 29030400   1 Y (never expire)
###########

#### HEADER CACHING ####
#-> http://www.htaccesselite.com/htaccess/caching-using-header-vt2.html
#<FilesMatch "\.(flv|gif|jpg|jpeg|png|ico)$">
#   Header set Cache-Control "max-age=2592000"
#</FilesMatch>
#<FilesMatch "\.(js|css|pdf|swf)$">
#   Header set Cache-Control "max-age=604800"
#</FilesMatch>
#<FilesMatch "\.(html|htm|txt)$">
#   Header set Cache-Control "max-age=600"
#</FilesMatch>
#<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
#   Header unset Cache-Control
#</FilesMatch>

### ALTERNATE EXPIRES CACHING ###
#-> htaccesselite.com/d/use-htaccess-to-speed-up-your-site-discussion-vt67.html
#ExpiresActive On
#ExpiresDefault A604800
#ExpiresByType image/x-icon A2592000
#ExpiresByType application/x-javascript A2592000
#ExpiresByType text/css A2592000
#ExpiresByType text/html A300
#<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
#   ExpiresActive Off
#</FilesMatch>

### META HTTP-EQUIV REPLACEMENTS ###
#<FilesMatch "\.(html|htm|php)$">
#   Header set imagetoolbar "no"
#</FilesMatch>

#=============================================================================#
#          REWRITES AND REDIRECTS
#=============================================================================#
# REQUEST METHODS: GET,POST,PUT,DELETE,CONNECT,OPTIONS,PATCH,PROPFIND,
#                  PROPPATCH,MKCOL,COPY,MOVE,LOCK,UNLOCK
###########

### REWRITE DEFAULTS ###
#RewriteEngine On
#RewriteBase /

### REQUIRE SUBDOMAIN ###
#RewriteCond %{HTTP_HOST} !^$
#RewriteCond %{HTTP_HOST} !^subdomain\.domain\.tld$ [NC]
#RewriteRule ^/(.*)$ http://subdomain.domain.tld/$1 [L,R=301]

### SEO REWRITES ###
#RewriteRule ^(.*)/ve/(.*)$    $1/voluntary-employee/$2 [L,R=301]
#RewriteRule ^(.*)/hsa/(.*)$     $1/health-saving-account/$2 [L,R=301]

### WORDPRESS ###
#RewriteCond %{REQUEST_FILENAME} !-f    # Existing File
#RewriteCond %{REQUEST_FILENAME} !-d    # Existing Directory
#RewriteRule . /index.php [L]

### ALTERNATIVE ANTI-HOTLINKING ###
#RewriteCond %{HTTP_REFERER} !^$
#RewriteCond %{HTTP_REFERER} !^http://(subdomain\.)?domain.tld/.*$ [NC]
#RewriteRule ^.*\.(bmp|tif|gif|jpg|jpeg|jpe|png)$ - [F] 

### REDIRECT HOTLINKERS ###
#RewriteCond %{HTTP_REFERER} !^$
#RewriteCond %{HTTP_REFERER} !^http://(subdomain\.)?domain.tld/.*$ [NC]
#RewriteRule ^.*\.(bmp|tif|gif|jpg|jpeg|jpe|png)$ http://google.com [R] 

### DENY REQUEST BASED ON REQUEST METHOD ###
#RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK|OPTIONS|HEAD)$ [NC]
#RewriteRule ^.*$ - [F] 

### REDIRECT UPLOADS ###
#RewriteCond %{REQUEST_METHOD} ^(PUT|POST)$ [NC]
#RewriteRule ^(.*)$ /cgi-bin/form-upload-processor.cgi?p=$1 [L,QSA] 

### REQUIRE SSL EVEN WHEN MOD_SSL IS NOT LOADED ###
#RewriteCond %{HTTPS} !=on [NC]
#RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

#### ALTERNATATIVE TO USING ERRORDOCUMENT ###
#-> http://www.htaccesselite.com/d/htaccess-errordocument-examples-vt11.html
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule ^.*$ /error.php [L]

### SEO REDIRECTS ###
#Redirect 301 /2006/oldfile.html http://subdomain.domain.tld/newfile.html
#RedirectMatch 301 /o/(.*)$ http://subdomain.domain.tld/s/dl/$1

#=============================================================================#
#          AUTHENTICATION AND SECURITY
#=============================================================================#
# http://www.htaccesselite.com/htaccess/basic-authentication-example-vt17.html
#
# Require (user|group|valid-user) (username|groupname)
###########

### BASIC PASSWORD PROTECTION ###
#AuthType basic
#AuthName "prompt"
#AuthUserFile /.htpasswd
#AuthGroupFile /dev/null
#Require valid-user

### ALLOW FROM IP OR VALID PASSWORD ###
#Require valid-user
#Allow from 192.168.1.23
#Satisfy Any

### PROTECT FILES ###
#<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
#  Order Allow,Deny
#  Deny from all
#</FilesMatch>

### PREVENT HOTLINKING ###
#SetEnvIfNoCase Referer "^http://subdomain.domain.tld/" good
#SetEnvIfNoCase Referer "^$" good
#<FilesMatch "\.(png|jpg|jpeg|gif|bmp|swf|flv)$">
#   Order Deny,Allow
#   Deny from all
#   Allow from env=good
#   ErrorDocument 403 http://www.google.com/intl/en_ALL/images/logo.gif
#   ErrorDocument 403 /images/you_bad_hotlinker.gif
#</FilesMatch>

### LIMIT UPLOAD FILE SIZE TO PROTECT AGAINST DOS ATTACK ###
#LimitRequestBody 10240000 #bytes, 0-2147483647(2GB) 

#=============================================================================#
#          SSL SECURITY
#=============================================================================#
#-> http://htaccesselite.com/d/redirecting-all-or-part-of-a-server-to-ssl-vt61
###########

### MOST SECURE WAY TO REQUIRE SSL ###
#-> http://www.askapache.com/htaccess/apache-ssl-in-htaccess-examples.html
#SSLOptions +StrictRequire
#SSLRequireSSL
#SSLRequire %{HTTP_HOST} eq "domain.tld"
#ErrorDocument 403 https://domain.tld 

#=============================================================================#
#          SITE UNDER CONSTRUCTION
#=============================================================================#
# Heres some awesome htaccess to use when you are developing a site
###########

### COMBINED DEVELOPER HTACCESS CODE-USE THIS ###
#<FilesMatch "\.(flv|gif|jpg|jpeg|png|ico|js|css|pdf|swf|html|htm|txt)$">
#   Header set Cache-Control "max-age=5"
#</FilesMatch>
#AuthType basic
#AuthName "Ooops! Temporarily Under Construction..."
#AuthUserFile /.htpasswd
#AuthGroupFile /dev/null
#Require valid-user           # password prompt for everyone else
#Order Deny,Allow
#Deny from all
#Allow from 192.168.64.5      # Your, the developers IP address
#Allow from w3.org            # css/xhtml check jigsaw.w3.org/css-validator/
#Allow from googlebot.com     # Allows google to crawl your pages
#Satisfy Any                  # no password required if host/ip is Allowed

### DONT HAVE TO EMPTY CACHE OR RELOAD TO SEE CHANGES ###
#ExpiresDefault A5 #If using mod_expires
#<FilesMatch "\.(flv|gif|jpg|jpeg|png|ico|js|css|pdf|swf|html|htm|txt)$">
#   Header set Cache-Control "max-age=5"
#</FilesMatch>

### ALLOW ACCESS WITH PASSWORD OR NO PASSWORD FOR SPECIFIC IP/HOSTS ###
#AuthType basic
#AuthName "Ooops! Temporarily Under Construction..."
#AuthUserFile /.htpasswd
#AuthGroupFile /dev/null
#Require valid-user           # password prompt for everyone else
#Order Deny,Allow
#Deny from all
#Allow from 192.168.64.5      # Your, the developers IP address
#Allow from w3.org            # css/xhtml check jigsaw.w3.org/css-validator/
#Allow from googlebot.com     # Allows google to crawl your pages
#Satisfy Any                  # no password required if host/ip is Allowed

###############################################################################
#
#    Copyright (c) 2007 AskApache.com. All rights reserved.
#
#  Latest: http://z.askapache.com/p/htaccess.txt
#  Online: http://www.askapache.com/htaccess/ultimate-htaccess-file-sample.html
###############################################################################

From the .htaccess cheatsheet

  1. For Webmasters
    • When site is ‘Under Construction’
    • Redirect everyone to different site except 1 IP
    • Redirect everyone to different site except 1 IP
    • Redirect Everyone but you to alternate page on your server.
    • Set the Timezone of the server
    • Set the Server Administrator Email
    • Turn off the ServerSignature
    • Force Files to download, do not display in browser
    • Process All .gif files with a cgi script
    • Process Requests with certain Request Methods
    • Make any file be a certain filetype
    • Use IfModule directive for robust code

  2. Custom HTTP Headers
    • Prevent Caching 100%
    • Remove IE imagetoolbar without meta tag
    • Add Privacy (P3P) Header to your site
    • Add a ‘en-US’ language header and ‘UTF-8′ without meta tags!
      • Using AddType
      • Using the Files Directive
      • Using the FilesMatch Directive
  3. PHP htaccess tips
    • When php run as CGI
    • Use a custom php.ini with mod_php or php as a cgi
      • When php run as Apache Module (mod_php)
      • When cgi php is run with wrapper (FastCGI)
  4. SEO Search Engine Friendly Redirects without mod_rewrite
    • For single moved file
    • Redirect Home to new Domain
    • For multiple files like a blog/this.php?gh
    • Redirect Entire site to single file
  5. mod_rewrite tips and tricks
    • Mostly .htaccess rewrite examples should begin with:
    • Check for a key in QUERY_STRING
    • Removes the QUERY_STRING from the URL
    • Fix for infinite loops
    • Require the www
    • Require no www
    • Redirect .php files to .html files (SEO friendly)
    • Redirect .html files to actual .php files (SEO friendly)
    • block access to files during certain hours of the day
    • Rewrite underscores to hyphens for SEO URL
    • Require the www without hardcoding
    • Require no subdomain
    • Require no subdomain
    • Redirecting WordPress Feeds to Feedburner
    • Only allow GET and PUT request methods
    • Prevent Files image/file hotlinking and bandwidth stealing
    • Stop browser prefetching
    • Make a prefetching hint for Firefox.
  6. Speed up your site with Caching and cache-control
    • htaccess time cheatsheet
    • Caching with both mod_expires + mod_headers
    • Caching with mod_headers
    • Caching with mod_expires
  7. Apache Authentication in htaccess
    • Require password for 1 file only
    • Protect multiple files:
    • Using the Apache Allow Directive in htaccess
      • network/netmask pair
      • IP address
      • More than 1 IP address
      • Partial IP addresses, first 1 to 3 bytes of IP, for subnet restriction
      • network/nnn CIDR specification
      • IPv6 addresses and subnets
      • Deny subdomains
      • Allow from IP without password prompt, and also allow from any address with password prompt
      • Skeleton .htaccess file to start with
  8. Security with Apache htaccess
    • CHMOD your files
    • Prevent access to .htaccess and .htpasswd files
    • Show Source Code instead of executing
    • Securing directories: Remove the ability to execute scripts
    • ErrorDocuments
      • Common STATUS Codes and ErrorDocument Implementations
      • When using CGI PHP, php 404 Error example
      • An example 404 Error page in perl cgi
      • ErrorDocuments generated by Apache
  9. SSL example usage in htaccess
    • Redirect non-https requests to https server
    • Rewrite non-https to HTTPS without mod_ssl!
      • Based on HTTPS variable (best)
      • Based on SERVER_PORT
      • Redirect everything served on port 80 to HTTPS URI
      • Redirect particular URLs to a secure version in an SSL SEO method
      • Check to see whether the HTTPS environment variable is set
      • Rewrite to SSL or NON-SSL using relative URL!
  10. Apache Variable fun (mod_env)
    • Using visitor dependent environment variables:
    • Special Purpose Environment Variables
    • SetEnvIf
      • SetEnvIfNoCase Example
      • SetEnvIfNoCase Example 2
Advertisements

3 thoughts on “List of .htaccess Examples

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s