FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Home  »  Htaccess  »  Apache Authentication in htaccess

by 14 comments

How to password-protect, Allow or Deny a visitor based on a condition. If you are having trouble getting htaccess-based password protection to work see: Troubleshooting htaccess Authentication: Getting it to work

Generate Your authentication htpasswd files with my free Online Password Generator!

Require password for 1 file only

<Files "login.php">
Order deny,allow
Deny from all
AuthName "htaccess password prompt"
AuthType Basic
AuthUserFile /web/askapache.com/.htpasswd
Require valid-user
</Files>

Protect multiple files:

<FilesMatch "^(exec|env|doit|phpinfo|w).*$">
Order deny,allow
Deny from all
AuthName "htaccess password prompt"
AuthUserFile /.htpasswd
AuthType basic
Require valid-user
</FilesMatch>

Using the Apache Allow Directive in htaccess

Allow network/netmask pair

Order deny,allow
Deny from all
Allow from 10.1.0.0/255.255.0.0

Allow IP address

Order deny,allow
Deny from all
Allow from 10.1.2.3

Allow More than 1 IP address

Order deny,allow
Deny from all
Allow from 192.168.1.104 192.168.1.205

Allow Partial IP addresses, first 1 to 3 bytes of IP, for subnet restriction

Order deny,allow
Deny from all
Allow from 10.1
Allow from 10 172.20 192.168.2

Allow network/nnn CIDR specification

Order deny,allow
Deny from all
Allow from 10.1.0.0/16

Allow IPv6 addresses and subnets

Order deny,allow
Deny from all
Allow from 2001:db8::a00:20ff:fea7:ccea
Allow from 2001:db8::a00:20ff:fea7:ccea/10

Deny subdomains

Order Allow,Deny
Allow from apache.org
Deny from wireshark.apache.org

Allow from IP without password prompt, and also allow from any address with password prompt

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

Skeleton .htaccess file

I use this when I start a new site, and uncomment or delete parts of the file depending on the sites needs

Ultimate htaccess file sample

#
#            DEFAULT SETTINGS
#
Options +ExecCGI -Indexes
DirectoryIndex index.php index.html index.htm
 
ErrorDocument 400 /cgi-bin/error.php
ErrorDocument 401 /cgi-bin/error.php
ErrorDocument 403 /cgi-bin/forbidden.cgi
ErrorDocument 404 /404.html
ErrorDocument 405 /cgi-bin/error.php
ErrorDocument 406 /cgi-bin/error.php
ErrorDocument 409 /cgi-bin/error.php
ErrorDocument 413 /cgi-bin/error.php
ErrorDocument 414 /cgi-bin/error.php
ErrorDocument 500 /cgi-bin/error.php
ErrorDocument 501 /cgi-bin/error.php
 
### DEFAULTS
ServerSignature Off
 
AddType video/x-flv .flv
AddType application/x-shockwave-flash .swf
AddType image/x-icon .ico
 
AddDefaultCharset UTF-8
AddLanguage en-US .html .htm .txt .xml .php
 
SetEnv TZ America/Indianapolis
SetEnv SERVER_ADMIN webmaster@askapache.com
 
### PHPINI-CGI
#AddHandler php-cgi .php
#Action php-cgi /cgi-bin/php5.cgi
 
### FAST-CGI
#AddHandler fastcgi-script .fcg .fcgi .fpl
#AddHandler php5-fastcgi .php
#Action php5-fastcgi /cgi-bin/fastcgi.fcgi
 
#
#           HEADERS and CACHING
#
# 1 YEAR
<FilesMatch "\.(flv|ico|pdf)$">
Header set Cache-Control "max-age=29030400, public"
</FilesMatch>
 
# 1 WEEK
<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=604800, public"
</FilesMatch>
 
# 3 HOUR
<FilesMatch "\.(txt|xml|js|css)$">
Header set Cache-Control "max-age=10800"
</FilesMatch>
 
# 1 MIN
<FilesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
Header set P3P "policyref="/w3c/p3p.xml", CP="NOI DSP COR NID CUR ADM DEV OUR BUS""
Header set imagetoolbar "no"
</FilesMatch>
 
#
#          REWRITES AND REDIRECTS
#
### SEO REDIRECTS
#Redirect 301 /ssl-ns.html /2006/htaccess/apache-ssl-in-htaccess-examples.html
#Redirect 301 /ht.tml
#Redirect 301 /index.html /
#RedirectMatch 301 /2006/htaccess-forum/(.*) /2006/htaccess/$1
#RedirectMatch 301 /(.*)rfc2616(.*) http://rfc.askapache.com/rfc2616/rfc2616.html
#RedirectMatch 301 /phpmanual(.*) /manual/en/$1
 
### REWRITES
RewriteEngine On
RewriteBase /
 
### WORDPRESS
#<ifModule mod_rewrite.c>
#RewriteEngine On
#RewriteBase /
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
#RewriteRule . /index.php [L]
#</ifModule>
 
### REQUIRE WWW
#RewriteCond %{HTTP_HOST} !^www\.askapache\.com$ [NC]
#RewriteRule ^(.*)$ /$1 [R=301,L]
 
### STOP LOOP CODE
#RewriteCond %{ENV:REDIRECT_STATUS} 200
#RewriteRule ^.*$ - [L]
 
### REDIRECT BLOG FEED TO FEEDBURNER
#RewriteCond %{HTTP_USER_AGENT} !^.*(FeedBurner|FeedValidator|Recent) [NC]
#RewriteRule ^feed/?.*$ http://feeds.feedburner.com/apache/htaccess [L,R=302]
 
### BLOCK WGET
#RewriteCond %{HTTP_USER_AGENT} ^Wget.* [NC]
#RewriteRule .* /cgi-bin/forbidden.cgi [L]
 
#
#           AUTHENTICATION
#
### BASIC PASSWORD PROTECTION
#AuthName "Prompt"
#AuthUserFile /web/askapache.com/.htpasswd
#AuthType basic
#Require valid-user
 
### UNDER CONSTRUCTION PROTECTION
#AuthName "Under Development"
#AuthUserFile /web/askapache.com/.htpasswd
#AuthType basic
#Require valid-user
#Order Deny,Allow
#Deny from all
#Allow from 23.23.23.1 w3.org googlebot.com google.com google-analytics.com
#Satisfy Any

Tags

April 10th, 2007

Comments Welcome

  • Fred

    Regarding "Require password for 1 file only", shouldn't this:

    AuthName "htaccess password prompt"
    AuthType Basic
    AuthUserFile /web/askapache.com/.htpasswd
    Require valid-user

    be this:

    AuthName "htaccess password prompt"
    AuthType Basic
    AuthUserFile /web/askapache.com/.htpasswd
    Order deny,allow
    Deny from all
    Require valid-user

    Your example allowed anyone on in two of my systems because of lack of a deny clause. Adding the two lines solved it.

  • http://www.askapache.com/ AskApache

    @ Fred

    Absolutely right. Thanks for the heads, thats a pretty big foul up on my part.

  • Motosauro

    Thanks for the snippets, I pasted them into my blog since I tend to forget them very easily :)

    Just one question: why do you think it's better to put ErrorDocument override in .htaccess files rather than vhost definitions?
    I place them in vhost definition files because they don't ever change (almost). I guess it's just a matter of personal taste though

    Thanks mate :)

  • chris jar

    Hi,

    I encountered this problem.

    I have .htaccess file:

    AuthType Basic
    AuthName "RestrictedFilesmain"
    AuthUserFile "d:Program FilesApache GroupApache2htdocsmainconfc.htpasswd"
    ErrorDocument 401 "ERROR_ 441 Authorization Required"
    ErrorDocument 403 "ERROR_ 403 Forbidden"
    ErrorDocument 404 "ERROR_ 404 Not Found"
    Require user loggeduser
    Require user chris

    and c.htpasswd file

    loggeduser:10144831511059024327
    chris:a2wssd

    When I log in into the protected page for the first time I enter chris:a2wssd and I am allowed to enter the page. Next I change password in the c.httpasswd file into a2ws4ss. And I still have access to the page just using refresh button in my Firefox browser.

    It looks like the Apache server didn't notice that I have change the password value in the mean time. What's wrong? I need to stop immediately the access to the protected page by changing the password in the file.

    Regards chris

  • http://www.4cinc.com Bobby Kozora

    I'm trying to use apache authentication as added protection to the password protected admin section of one of my sites. The site's using Wordpress. What's happening is when I access the admin section the .htaccess file in that directory isn't executing. Well, it will throw errors but if all's fine it passes back to my root .htaccess which then displays the 404 page. If I remove the .htaccess from my admin directory I can once again access my login page. Any ideas? I'm stumped.

  • Fred

    Bobby, create an .htaccess file in your wp-admin directory following the contents listed in "Allow from IP without password prompt, and also allow from any address with password prompt".

    The "Allow from 172.17.10.1" should contain your static IP address if you have one, or that of your client if you are building this site for someone else to access. Of course, you can add more than one line in that format. It will allow anyone arriving from an IP in the Allow statement(s) to access the WPAdmin login screen without having the enter the Apache Username/Password combination. Everyone else will be stopped at the Apache login screen, and if they authenticate there they will then receive the WP login screen. I do this on over 100 WP sites.

  • http://brokenflower.org/pblog/ martin

    Great article, thank you!

  • http://www.virvo.com Apache Development

    I am encountering a problem where I get a 404 page every time I put Require valid-user into the .htaccess of a folder. Any ideas why this might be happening?

  • AK

    Your "Allow from IP without password prompt, and also allow from any address with password prompt" example is exactly what I was looking for. Thank you!

    • Tra

      i found this to be an informative and interesting blog.. very useful and knowledge able. Thank you for the efforts you have made in writing this authentication article. Your writing abilities have inspired me..

  • sy

    I have my "password" file in C:Program FilesApache GroupApache2htdocsusers

    I would like to restrict access to a folder "flash anim" in C:Program FilesApache GroupApache2htdocsFlash Anim

    I have given the following directives in my .htaccess file

    AuthType Basic
    AuthName "Restricted Files"
    AuthUserFile /Program Files/Apache Group/Apache2/htdocs/users/password
    Require user windowsistheproblem

    When I access the that directory it gives me the following error:

    [Tue Jul 27 15:37:17 2010] [alert] [client 10.10.10.57] C:/Program Files/Apache Group/Apache2/htdocs/Flash Anim/.htaccess: AuthUserFile takes 1-2 arguments, text file containing user IDs and passwords

    I have no idea where I am getting wrong. What does the above error log means? can any body help please?

  • Parvez

    i want to give permission to open all user image folder from my site and other are password protected.

  • kiran

    Hi,
    As shown the partial IP example for IPV4 addresses (in Allow from), is it possible to use partial IPV6 address also ?
    example :

    Allow from 2001:db8:a00:20ff:fea7:cc00:1234:564 <--full Ipv6 address
    Allow from 2001:db8:a00:20ff:fea7:cc00  <---------partial Ipv6 address

    Regards,
    Kiran

  • Pingback: HTAccess and htpasswd » Knowledge Base

My Online Tools
WordPress Sites

My Picks

Related Articles
Newest Posts
Twitter

  • Trojan Horse, a novel!  t.co/Hf8EtYaZVa 
  • The Hacker Playbook - very nice high level overview of attacks  t.co/lHwNVWi61u 
  • Clean Code - A Handbook of Agile Software Craftsmanship  t.co/hnJX0x1qIc 
  • Secrets of the JavaScript Ninja - By my absolute favorite JS hacker John Resig!  t.co/tZ42ljmcCl 
  • Hacking Exposed 7: Network Security Secrets & SolutionsMy all time favorite, basic but thorough and accurate.  t.co/jycW0RDVtZ 
  • Empty words will be no surrogate for cold resolve. Pain is nothing.  t.co/qXjpRxbjCw 
  • REVERSING: Secrets of Reverse Engineering  t.co/GaWo29lWWG 
  • NEUROMANCER  t.co/3OoknUcb5Z 
  • "The Shockwave Rider", by John Brunner (1975 hacker sci-fi)  t.co/ZW56HVUefW 
  • The Rootkit ARSENAL - Escape and Evasion in the Dark Corners of the System  t.co/1FzX6bHgsQ 
  • "We Are Anonymous - Inside the Hacker World of LulzSec, Anonymous, and the Global Cyber Insurgency" better be good!  t.co/GL0cFNiUOq 
  • THE IDEA FACTORY Bell Labs  t.co/FyVhgNwwT5 
  • The Datacenter as a Computer -- Urs Holzle  t.co/M5WIYs1OVg 
  • Now by Steven Levy, "IN THE PLEX"  t.co/PwxtLgqukG 

Friends and Recommends
Hacking and Hackers

The use of "hacker" to mean "security breaker" is a confusion on the part of the mass media. We hackers refuse to recognize that meaning, and continue using the word to mean someone who loves to program, someone who enjoys playful cleverness, or the combination of the two. See my article, On Hacking.
-- Richard M. Stallman






[hide]

It's very simple - you read the protocol and write the code. -Bill Joy

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License, just credit with a link.
This site is not supported or endorsed by The Apache Software Foundation (ASF). All software and documentation produced by The ASF is licensed. "Apache" is a trademark of The ASF. NCSA HTTPd.
UNIX ® is a registered Trademark of The Open Group. POSIX ® is a registered Trademark of The IEEE.

| Google+ | askapache

Site Map | Contact Webmaster | License and Disclaimer | Terms of Service

↑ TOPMain