Stupid htaccess Trick: Enable File or Directory Access to Your Password-Protected Site

Published Monday, November 26, 2007 @ 8:22 am • 4 Responses

In this brief tutorial, we are going to enable users to access any file or directory of a site that is password-protected via htaccess. There are many reasons for wanting to employ this technique, including:

  • Share public resources from an otherwise private site
  • Enable visitors to access content during site maintenance
  • Testing and formatting of layout and design during development

As a webmaster, I have used this technique on several occasions. This trick works great for allowing access to any number of files, directories, and/or combination of both. We will begin with a generalized example, proceed with an explanatory discussion, and wrap things up with a couple of useful modifications.

A Generalized Example

Here is the basic htaccess code enabling users to access a specific directory and file on your domain:

# password protection allowing directory and file access
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/path/.htpasswd
AuthGroupFile /dev/null 
Require valid-user
SetEnvIf Request_URI "(path/to/directory/)$" allow
SetEnvIf Request_URI "(path/to/file\.php)$"  allow
Order allow,deny
Allow from env=allow
Satisfy any

To use this tasty little nugget, copy & paste into your site’s root (or target directory) htaccess file and edit the following parameters:

  • The phrase “Restricted Area” will be displayed on the password-prompt dialogue box — edit accordingly.
  • Edit the AuthUserFile path to match that of your htaccess password file (e.g., “/home/path/.htpasswd”).
  • Edit the first Request_URI path to match that of your target directory, and/or the second Request_URI path to match that of your target file (delete either one if not needed).

Afterwards, ensure that everything is functioning properly by attempting to access both your password-protected content and newly accessible directory and/or file. To reassure yourself, try using a few free proxies (Google: “free proxy”) to access your various resources.

Discussion

So, how exactly does this fine slice of htaccess code operate? Let’s break it on down..

AuthType Basic
This line specifies the authorization type, enabling Apache to run the correct function. In this case, and in 99% of the cases I have seen, the authorization type is “Basic”.
AuthName "Restricted Area"
Here we are specifying the message that will be displayed with the password-prompt dialogue box. This is a great place to inform visitors of any publicly available content. For example, you could display something like: “Private Site - Public content available at http://domain.tld/content/”
AuthUserFile /home/path/.htpasswd
In this line, we are specifying the location of the user authentication file. This file should not be available via the Internet (i.e., place in a directory above public_html) because it contains the password verification.
AuthGroupFile /dev/null
Here we are specifying the location of the group authorization file, if any. In this example, because we are not authorizing any groups, we specify a “null” value.
Require valid-user
This line instructs Apache to implement the password protection, essentially saying, “require a valid password” before allowing access.
SetEnvIf Request_URI "(path/to/directory/)$" allow
In this line, we are setting the specified URL request as an allow variable. This variable will be checked later in the script. This line essentially says, “associate the specified URL (i.e., path/to/directory/) with an allow variable.”
SetEnvIf Request_URI "(path/to/file\.php)$" allow
As in the previous line, here we are setting the specified URL request as an allow variable. This variable will be checked later in the script. This line essentially says, “associate the specified URL (i.e., path/to/file\.php) with an allow variable.”
Order allow,deny
Here we designate the order in which access parameters will be evaluated. In this case, we want to consider allowed access before denied access. Especially in this example, the order of these two parameters is critical.
Allow from env=allow
In this line, we are telling Apache to allow access to any resource associated with an allow variable.
Satisfy any
Finally, we wrap things up by instructing Apache to apply the directives for any condition in which the specified parameters have been satisfied ;)

Some tweaks and modifications..

Let’s take a look at a couple of potentially useful modifications..

Allow access to multiple site resources

To allow public user access to more resources, set additional allow variables:

# password protection allowing multiple resources
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/path/.htpasswd
AuthGroupFile /dev/null 
Require valid-user
# allow public access to the following resources
SetEnvIf Request_URI "(path/to/directory_01/)$"         allow
SetEnvIf Request_URI "(path/to/directory_02/)$"         allow
SetEnvIf Request_URI "(path/to/file\.php)$"             allow
SetEnvIf Request_URI "(path/to/file\.html)$"            allow
SetEnvIf Request_URI "(path/to/another/resource/)$"     allow
SetEnvIf Request_URI "(path/to/yet/another/resource/)$" allow
Order allow,deny
Allow from env=allow
Satisfy any

Of course, you will want to customize this code to reflect the various resources for which you would like to allow public access.

Allow webmaster and other sites open access to entire site

Here’s the scene: you have the entire site password-protected via htaccess. You also have allowed open, public access to various site resources, directories, etc. Now, what if you also want to provide unrestricted access to the entire domain for certain, key individuals and sites? Easy, just use this lil’ chunk of htaccess goodness:

# password protection allowing multiple resources
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/path/.htpasswd
AuthGroupFile /dev/null 
Require valid-user
# allow public access to the following resources
SetEnvIf Request_URI "(path/to/directory_01/)$"         allow
SetEnvIf Request_URI "(path/to/directory_02/)$"         allow
SetEnvIf Request_URI "(path/to/file\.php)$"             allow
SetEnvIf Request_URI "(path/to/file\.html)$"            allow
SetEnvIf Request_URI "(path/to/another/resource/)$"     allow
SetEnvIf Request_URI "(path/to/yet/another/resource/)$" allow
Order allow,deny
Allow from env=allow
# allow open access to entire site for select ips and sites
Allow from 777.777.77.7
Allow from 888.888.88.8
Allow from 999.999.99.9
Allow from domains.tld
Allow from website.tld
Allow from example.tld
Satisfy any

To use this code, replace/edit each “Allow from …” line to reflect either the IP address or URL of any sites for which you would like to allow open, unrestricted access. For example, you may want to allow the site administrator(s) open access, along with perhaps a few key validation sites. This is the stuff that web-development dreams are made of!!

Well, that does it for this post. A big thank you goes out to our friend Dave Atkins for inquiring about this technique. And, as always, please share your comments, criticisms, and suggestions with the rest of us ;)

Update: The original version of this article presented a method for allowing open feed access at password-protected sites. Unfortunately, the code did not work as intended thanks to Apache’s virtually complete lack of support for query strings. Needless to say, this article has been rewritten to demonstrate a generalized technique for enabling access to files and directories.

Peace!


Dialogue

4 Responses Jump to comment form

1Dan

March 3, 2008 at 1:00 pm

Can this code be modified for multiple username/passwords to each be directed to a specific directory. I’m looking to use only 2 username/passwords. User1 will be directed to www.domain.com/user1/ and User2 will be directed to www.domain.com/user2/

2Perishable

March 3, 2008 at 3:56 pm

This code is designed to operate on a per-directory basis. Upon attempted access, the user is prompted to enter credentials, which, if verified, will enable access to the resource (file or directory). The directives function as an intermediary security checkpoint and do not redirect unless authentication has failed. I.E., such redirection is possible, but is not included in the script.

3Andrew

June 11, 2008 at 6:40 pm

Where you say “either the IP address or URL” for the Allow directive, can a URL include subdirectories? E.g.

Allow from mysite.com/authenticated/

Thanks.

4Perishable

June 14, 2008 at 8:11 am

Hi Andrew,
Yes, as far as I know. I haven’t tested it myself, so I would be interested in your findings.
Regards,
Jeff

Subscribe to comments on this post


Share your thoughts..

TopRead official comment policy

← Previous post • Next post →

« Yahoo! in my BlackholeRefreshMints: Refresh Stats Bookmarklets for Mint 2 »

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

automation is great: i've got photoshop batch processing 300+ images while FTP is simultaneously uploading them to the server..

Perishable on Tumblr

Tons of Firewalls

Tuesday, 7 October 2008, 1:45 am

Recently overheard on conservative talk radio (instructing listeners how to obtain a free promotional video from their new website):

“This website has tons and tons of firewalls, so you have to use your real email address to download the video..”

The Quiet Search Revolution

Monday, 6 October 2008, 12:15 pm

Just a thought.. As awesome as Google is these days, it would suck if they ended up owning the entire search-engine business. When they get to the point where all competition is impossible (due to their sheer size, financial resources, media influence, etc.), how many alternate search engines will have the resources for continuous improvement and top-quality search results? When this happens, we will have no choice but to do exactly what Google tells us to do.

As deeply ingrained as it is for everyone to instinctively and unthinkingly turn to Google for their search activity, it is time to leave a few alternate search tabs open for as much use as possible. Instead of using Google just because that’s what you always do, try your search on MSN, Yahoo, Ask, or any of the other independent search engines instead. Sharing traffic with other search engines is a nice, quiet way to keep the competitive spirit alive and well in the search-engine business.

Disappearing WordPress Posts

Wednesday, 1 October 2008, 7:50 pm

Today I experienced difficulties while trying to publish or even save new posts in WordPress. I would compose the post as usual, add all of the keywords, tags, meta tags, and so on, but as soon as I clicked the “Publish” or “Save” button, the post would just disappear from existence.

The weird thing is that during the drafting process, WordPress’ default auto-save feature showed that the post had been saved at expected intervals. Unfortunately, after trying to publish several different posts, WordPress showed absolutely no record of the posts ever being created. They simply vanished into thin air.

Fortunately, a little investigation revealed the culprit. If you should find yourself dealing with this same issue, here are some different things that you should try. First, re-upload fresh copies of your entire WordPress installation. I don’t know why exactly, but apparently various files can either go stale or completely disappear from the server. Overwriting or writing fresh files may do the trick.

If that doesn’t work, check your WordPress database for errors. In my case, a little investigation revealed that something had caused a couple of fatal errors in the wp_posts table. Fortunately, checking and repairing the table solved the issue.

Tumblr Battles

Wednesday, 1 October 2008, 5:30 pm

Please excuse the duplicate Tumbr posts.. seems there is no way to ping Tumblr to refresh/rebuild the RSS feed according to changes in post content. So, to resolve the issue I have discussed now like two or three times regarding paragraph elements and proper feed formatting, I have no choice but to repost a majority of my text posts.

This is necessary for the proper import and display of my Tumblr feed into WordPress. Currently, there are five items displayed at once, each styled according to proper inclusion of paragraph tags. Thus, whenever the Tumblr feed “forgets” to enclose single-paragraph posts with the proper tags, the result is an unstyled post entry displayed on my site.

Assuming that makes sense, you will please excuse my dust while I repost a few older entries in an attempt to reconstruct (the hard way) a properly formatted Tumblr feed.

More Optimization Measures

Wednesday, 1 October 2008, 5:27 pm

Another important step in improving the performance of my recent redesign involves the optimization of both CSS and JavaScript content. During development there were around 15 server requests for these two types of files, 10 JavaScript files and 5 CSS files. This was okay for my own use, but would not work for production purposes.

Optimizing these file types involves consolidation, compression, and caching. Consolidation of 10 JavaScript files into three is huge improvement. Now I deliver one JS file for the functionality of the site, one for Mint, and another for Analytics. Likewise for the stylesheets; after consolidation, a single stylesheet is delivered to all modern browsers. There are two additional stylesheets as well, but they are targeted at IE6 and mobile browsers and will not load elsewhere.

Once the files were consolidated as much as possible, it was time to optimize or “crunch” them. Using the sexy Flumpcakes CSS optimizer, I was able to reduce my stylesheets by around 25%. Likewise for JavaScript, I used xtreeme.com’s optimizer to shave an additional 20% off the size of my JS content.

Finally, once I had consolidated and compressed my JS and CSS files as much as possible, I wanted to further my optimization efforts by ensuring that these files were cached by the browser. By setting far-future Expires headers for everything but the statistical files, my site gains an additional performance boost by eliminating the need to reload preexisting content.

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • Adam Singer: Thanks for this. You're right, if it isn't broken, don't fix it. I was about to update my permalinks and install a plugin to redire...
  • Marilyn: It looks great on my browser! I wish I had that much creativity in my head! It's gorgeous!...
  • Randy: "Too girly?" It looks like a great design. Define "too girly!"...
  • Christopher Ross: .htaccess based redirects are wonderful. I'm always baffled by web professionals who don't take the time to learn more about them....
  • federico: Hi Jeff... tnx so much...it worked perfectly... c u Federico...
  • Cooltad: The skin seems (mostly) fine in my expert opinion. Your one of the few people able to make a design with a transparent table and a b...
  • Neal: The free Intro to Linux book is a great place to start http://www.ischool.utexas.edu/mirrors/LDP/LDP/intro-linux/html/index.html ...
  • Louis: @Jeff: Your “Archives” page is slick, although I would expect a cleaner implementation from such a vehement advoc...
  • Jeremy: Well I think that you may be over-critical, I don't see a darn thing wrong with it - I like it a lot!...
  • Jeff Starr: Alright, this is exactly the kind of information I was hoping to get. Lots of great ideas and recommendations here. I will be reading...

Read more recent comments..