.htaccess files - Ultimate htaccess Guide

« .htaccess Plugin Blocks Spam, Hackers, and Password Protects BlogHtaccess SEO Trends by Google »

Jul 10, 08

.htaccess Files

.htaccess files are “distributed configuration files” to control the Apache Web Server. The .htaccess files are similar to the main server configuration file httpd.conf but are used to control the directory they are placed in. Many web hosts allow .htaccess files for their customers but don’t explain how to use them.

Over the years I have learned some incredibly useful and powerful ways to utilize htaccess configuration files to do all kinds of unbelievably cool stuff.. This page is one big TOC for easy access to all my favorite htaccess tricks and examples. I write new posts and techniques periodically and add them to this htaccess index. Some of my best server tricks and htaccess techniques are on their way. I like to semi-hide the very best htaccess solutions in hard-to-find areas of these articles so they won’t be used by everyone, most of the best solutions are definately not cut-and-paste ready to be pasted into your .htaccess file, but 99% of these .htaccess articles are full of easy to use, cut-and-paste-ready htaccess example code snippets.

.htaccess note: The best of the best mod_rewrite htaccess code snippets I find and other tricks are included in this htaccess plugin.

Originally these articles came from my personal notes and real .htaccess files I used on various servers.. So in some places the article format is perfect for an experienced apache server admin or hacker, but frustrating for someone just trying to learn the basics, sorry about ya. For those wanting a good explanation of the overal use and concept of .htaccess files. Advanced users can check out these other htaccess sites, my personal faves.


Cookie Manipulation, New .htaccess examples

Cookie Manipulation in .htaccess with RewriteRuleFresh .htaccess code for you! Check out the Cookie Manipulation and environment variable usage with mod_rewrite! I also included a couple Mod_Security .htaccess examples. Enjoy!

htaccess For Webmasters


Custom HTTP Headers


Securing php.ini and php.cgi with .htaccess

Locking down your php.ini and php cgi with .htaccessIf you have a php.cgi or php.ini file in your /cgi-bin/ directory or other pub directory, try requesting them from your web browser. If your php.ini shows up or worse you are able to execute your php cgi, you’ll need to secure it ASAP. This shows several ways to secure these files, and other interpreters like perl, fastCGI, bash, csh, etc.


PHP htaccess tips


301 Redirects without mod_rewrite


mod_rewrite tips and tricks

Some of my fav mod_rewrite tricks:


Speed with .htaccess Caching


htaccess Password Protection


Blocking Bad Bots

Block Bad RobotWant to block a bad robot or web scraper using .htaccess files? Here are 2 methods that illustrate blocking 436 various user-agents.

Security with Apache htaccess


HTTP to HTTPS Redirects with mod_rewrite

HTTP to HTTPS Redirects with mod_rewriteThis is freaking sweet if you use SSL I promise you! Basically instead of having to check for HTTPS using a RewriteCond %{HTTPS} =on for every redirect that can be either HTTP or HTTPS, I set an environment variable once with the value “http” or “https” if HTTP or HTTPS is being used for that request, and use that env variable in the RewriteRule.


SSL encryption in htaccess, HTTPS


SetEnvIf and SetEnvIfNoCase Examples


Apache Variable fun mod_env


Elite .htaccess Security with MOD_SECURITY


AskApache’s Favorite .htaccess Articles/Links

These are just some of my favorite .htaccess resources. I’m really into doing your own hacking to get the knowledge and these links are all great resources if you are like me. I’m really interested in new or unusual solutions or hacks that use .htaccess, so let me know if you find one.

corz.org

Here’s a resource that I consider to have some of the most creative and ingenious ideas for .htaccess files. Its a trip trying to navigate around the site, a fun one. Its like nothing I’ve ever seen. There are only a few articles on the site, but the htaccess articles are truly original and worth a look for advanced users.. htaccess tricks and tips and more .htaccess tricks

Perishable Press

Stupid .htaccess tricks is probably the best explanation online for many of the best .htaccess solutions. Unlike me they are fantastic copywriters, even for technical stuff, so its a good blog to kick back on, a breeze to read. Another .htaccess article I enjoyed was How to Block Proxy Servers via htaccess, which I incorporated into the WordPress Password Protect Plugin.

BlogSecurity

Mostly a site for… blog security (which is really any web-app security) this blog has a few really impressive articles full of solid information for Hardening WordPress with .htaccess among more advanced topics that can be challenging but effective. This is a good site to subscribe to their feed, they publish plugin exploits and wordpress core vulnerabilities quite a bit.

jdMorgan

Moderator of the Apache Web Server Forum for webmasterworld, in my experience he can answer any tough question pertaining to advanced .htaccess stuff..

Check-These.info

Oldschool security/unix dude who taught me alot about mod_rewrite when I switched sides.

  1. Detailed Basic Mod_Rewrite Guide
  2. More Advanced Mod_Rewrite Tutorial

.htaccess Core Directives

Here are some of the directives included in the core of apache httpd that you may utilize in .htaccess files. You can find out what your httpd allows like this:

$ ./httpd -L|grep -B 2 "htaccess"|grep -v '-'
Files (core.c)
        Container for directives affecting files matching specified patterns
        Allowed in *.conf anywhere and in .htaccess
Limit (core.c)
        Container for authentication directives when accessed using specified HTTP methods
        Allowed in *.conf anywhere and in .htaccess
LimitExcept (core.c)
        Container for authentication directives to be applied when any HTTP method other than those specified is used to access the resource
        Allowed in *.conf anywhere and in .htaccess
IfModule (core.c)
        Container for directives based on existance of specified modules
        Allowed in *.conf anywhere and in .htaccess
IfDefine (core.c)
        Container for directives based on existance of command line defines
        Allowed in *.conf anywhere and in .htaccess
FilesMatch (core.c)
        Container for directives affecting files matching specified patterns
        Allowed in *.conf anywhere and in .htaccess
AuthType (core.c)
        An HTTP authorization type (e.g., "Basic")
        Allowed in *.conf only inside <Directory>, <Files> or <Location> and in .htaccess
AuthName (core.c)
        The authentication realm (e.g. "Members Only")
        Allowed in *.conf only inside <Directory>, <Files> or <Location> and in .htaccess
Require (core.c)
        Selects which authenticated users or groups may access a protected space
        Allowed in *.conf only inside <Directory>, <Files> or <Location> and in .htaccess
Satisfy (core.c)
        access policy if both allow and require used ('all' or 'any')
        Allowed in *.conf only inside <Directory>, <Files> or <Location> and in .htaccess
AddDefaultCharset (core.c)
        Allowed in *.conf anywhere and in .htaccess
AcceptPathInfo (core.c)
        Allowed in *.conf anywhere and in .htaccess
        when AllowOverride includes FileInfo
AccessFileName (core.c)
ErrorDocument (core.c)
        Change responses for HTTP errors
        Allowed in *.conf anywhere and in .htaccess
Options (core.c)
        Set a number of attributes for a given directory
        Allowed in *.conf anywhere and in .htaccess
DefaultType (core.c)
        the default MIME type for untypable files
        Allowed in *.conf anywhere and in .htaccess
FileETag (core.c)
        Specify components used to construct a file's ETag
        Allowed in *.conf anywhere and in .htaccess
EnableMMAP (core.c)
        Allowed in *.conf anywhere and in .htaccess
EnableSendfile (core.c)
        Controls whether sendfile may be used to transmit files
        Allowed in *.conf anywhere and in .htaccess
ServerSignature (core.c)
        Allowed in *.conf anywhere and in .htaccess
ContentDigest (core.c)
        Allowed in *.conf anywhere and in .htaccess
LimitRequestBody (core.c)
        Limit (in bytes) on maximum size of request message body
        Allowed in *.conf anywhere and in .htaccess
LimitXMLRequestBody (core.c)
        Allowed in *.conf anywhere and in .htaccess
RLimitCPU (core.c)
        Soft/hard limits for max CPU usage in seconds
        Allowed in *.conf anywhere and in .htaccess
RLimitMEM (core.c)
        Soft/hard limits for max memory usage per process
        Allowed in *.conf anywhere and in .htaccess
RLimitNPROC (core.c)
        soft/hard limits for max number of processes per uid
        Allowed in *.conf anywhere and in .htaccess
ForceType (core.c)
        a mime type that overrides other configured type
        Allowed in *.conf anywhere and in .htaccess
SetHandler (core.c)
        a handler name that overrides any other configured handler
        Allowed in *.conf anywhere and in .htaccess
SetOutputFilter (core.c)
        filter (or ; delimited list of filters) to be run on the request content
        Allowed in *.conf anywhere and in .htaccess
SetInputFilter (core.c)
        filter (or ; delimited list of filters) to be run on the request body
        Allowed in *.conf anywhere and in .htaccess
AddOutputFilterByType (core.c)
        Allowed in *.conf anywhere and in .htaccess
 
Files
Container for directives affecting files matching specified patterns
Limit
Container for authentication directives when accessed using specified HTTP methods
LimitExcept
Container for authentication directives to be applied when any HTTP method other than those specified is used to access the resource
IfModule
Container for directives based on existance of specified modules
IfDefine
Container for directives based on existance of command line defines
FilesMatch
Container for directives affecting files matching specified patterns
AuthType
An HTTP authorization type (e.g., “Basic”)
AuthName
The authentication realm (e.g. “Members Only”)
Require
Selects which authenticated users or groups may access a protected space
Satisfy
access policy if both allow and require used (’all’ or ‘any’)
AddDefaultCharset
The name of the default charset to add to any Content-Type without one or ‘Off’ to disable
AcceptPathInfo
Set to on or off for PATH_INFO to be accepted by handlers, or default for the per-handler preference when AllowOverride includes FileInfo
ErrorDocument
Change responses for HTTP errors
Options
Set a number of attributes for a given directory
DefaultType
the default MIME type for untypable files
FileETag
Specify components used to construct a file’s ETag
ServerSignature
En-/disable server signature (on|off|email)
ContentDigest
whether or not to send a Content-MD5 header with each request
LimitRequestBody
Limit (in bytes) on maximum size of request message body
LimitXMLRequestBody
Limit (in bytes) on maximum size of an XML-based request body
ForceType
a mime type that overrides other configured type
SetHandler
a handler name that overrides any other configured handler
SetOutputFilter
filter (or ; delimited list of filters) to be run on the request content
SetInputFilter
filter (or ; delimited list of filters) to be run on the request body
AddOutputFilterByType
output filter name followed by one or more content-types

.htaccess Tutorial Index |

« .htaccess Plugin Blocks Spam, Hackers, and Password Protects BlogHtaccess SEO Trends by Google »


Reader Comments

Skip to form
  1. John says:August 18, 2h

    Hey,

    I am using the following code for redirecting non www url to www url.

    Options +FollowSymLinks
    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP_HOST} !^www\.yourdomain\.com$ [NC]
    RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]

    It work fine for the folowing url type
    site.com/restaurant.html

    If I have to redirect the following non www url to www url
    site.com/cms/restaurant.html

    When I hit this url I get the following response

    "The requested URL /index.php was not found on this server."

    Please let me know what code to add?

    Thanks,
    John

  2. Rich Bowen says:August 11, 17h

    Now even more! Love it.

    .htaccess rewrite mask external link,htaccess mod rewrite error page,how much does mod rewrite,.htaccess dynamic directories,htaccess rewrite url,htaccess url,htaccess hide url,mod rewrite php to htm

    and

    htaccess rewrite rule options,rewrite direct index link htaccess,htaccess rewriterule,.htaccess mod_rewrite rules,convert unix timestamp into date php,php to .html with htaccess

  3. htaccess rewrite says:June 02, 0h

    htaccess rewrite,htaccess mod rewrite,php url rewrite,.htaccess rewrite rule,.htaccess redirect post variables,mod rewrite htaccess,htaccess,.htaccess rewrite,hotlink code,rewrite url .htaccess,htaccess allow indexes,htaccess tips tricks,.htaccess php require,.htaccess php.ini,rewrite htaccess,htaccess rewrite rule,.htaccess mod rewrite,bbcode to html php script,htaccess tips,mod_rewrite won’t do anything in http.conf,redirect subfolder to root,rewriterule htaccess,htaccess rewrite explained,how to use htaccess rewriteengine,short url + htaccess,comment out htaccess,hacking htaccess,htaccess php include,index.html before index.php .htaccess

    Hey your home page is a little out of control

  4. Richard says:May 27, 1h

    This is very useful and powerful. It does help improve the security of my wordpress. I will keep an eye of the updates.

  5. Raymond S. Usbal says:April 18, 6h

    Thanks for putting this up. This guide is complete and direct to the point. I like it!

  6. Jill says:December 17, 22h

    After three frustrating phone calls to the idiots at 1&1 hosting, simply trying to help one of my clients get a redirect…I gave up and asked my website hosting company, DreamHost for help. Their article directed me to this site, which, solved the problem with my client’s site in a snap. Thank you so much for this!

  7. Modified WP-Cache for Huge Speed Increase says:December 13, 23h

    [...] Or just add this to your blogs .htaccess file. [...]

  8. emi says:October 26, 21h

    Hello,

    How can I write a rule for :
    domain.tld/index.php?option=com_content&task=view&id=16Itemid=32 to -> http//domain.tld/content/

    And:
    domain.tld/index.php?option=com_content&task=view&id=30&Itemid=63 to -> http://domain.tld/content/careers

    Thanks

  9. Grafikafe says:October 07, 9h

    very nice doc
    thank you man.

  10. AskApache says:August 13, 16h

  11. Saumendra Swain says:April 13, 21h

    A great article. One of the best tutorial available online.

  12. htaccess says:February 28, 7h

    this does not seem to work ?

    AuthName "htaccess password prompt"
    AuthUserFile /home/askapache.com/.htpasswd
    AuthType Basic
    Require valid-user
    Allow from 172.17.10.1
    Satisfy Any

    It lets me in from any ip address ? I’ve managed to get it to work like this (although may not be correct)

    AuthName "htaccess password prompt"
    AuthUserFile /home/askapache.com/.htpasswd
    AuthType Basic
    Satisfy Any
     
    order deny,allow
    deny from all
    Require valid-user
    Allow from 172.17.10.1

    I’m not sure if this is optimal however.

  13. Saumendra says:February 23, 0h

    An amazing Article, with consise and yet very specific.

  14. Joost says:February 10, 17h

    Great list, it helps clear up much of the htacess mystery and confusion that comes from creating such files.

  15. Liam McDermott says:February 09, 11h

    Thanks for this article, it’s great.

    So great that we’ve made it ‘sticky‘ on The Webmaster Forums.
    Now we don’t have to repeat ourselves, just send people to this article!

  16. adam taylor; eightfourseven2 says:February 07, 16h

    So I try to set up a simple .htaccess file for this site to get rid of the ugly default wordpress links and guess what? It causes a server error

    Great. I email the tech support of the hosting and they say they need more information and point me to some useless FAQs. What information do you want?! All I want is to create an .htaccess file sheesh

    I did, however, come across the *ultimate* .htaccess guide in the process - Seemed like an interesting blog in general

  17. tenstar says:December 07, 1h

    That’s perfect summary, very valuable for my next job of doing SEO friendly urls through htaccess. Thank you.

Like honey.. We Keep em' Buzzin

Be polite, my .htaccess anti-spam is crazy-tight..
Please wrap any code blocks in <pre>...</pre> tags, code words in <code>...</code> tags.

WebDev Technology

Someone's Reading

Related Articles

Popular

Technology Articles

Online Tools

.htaccess Forum

Ask Apache News

Random Articles

Other Articles

This work by AskApache.com is licensed under the most accommodating license type available, just credit source according to license. .htaccess examples


Search