You are on page 1of 23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

Site Navigation Top Links .htaccess tips and tricks


<ifModule> clever stuff here </ifModule>

Introduction to .htaccess..
This work in constant progress is some collected wisdom, stuff I've learned on the topic of .htaccess hacking, commands I've used successfully in the past, on a variety of server setups, and in most cases still do. You may have to tweak the examples some to get the desired result, though, and a reliable test server is a powerful ally, preferably one with a similar setup to your "live" server. Okay, to begin..
..a win32 Apache mirror of corz.org

.htaccess files are invisible There's a good reason why you won't see .htaccess files on the web; almost every web server in the world is configured to ignore them, by default. Same goes for most operating systems. Mainly it's the dot "." at the start, you see? If you don't see, you'll need to disable your operating system's invisible file functions, or use a text editor that allows you to open hidden files, something like bbedit on the Mac platform. On windows,
corz.org/serv/tricks/htaccess.php 1/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

showing invisibles in explorer should allow any text editor to open them, and most decent editors to save them too**. Linux dudes know how to find them without any help from me.

that same folder, as seen from Mac OS X

In both images, the operating system has been instructed to display invisible files. ugly, but necessary sometimes. You will also need to instruct your ftp client to do the same. By the way; the windows screencap is more recent than the mac one, moved files are likely being handled by my clever 404 script.

** even notepad can save files beginning with a dot, if you put double-quotes around the name when you save it; i.e.. ".htaccess". You can also use your ftp client to rename files beginning with a dot, even on your local filesystem; works great in FileZilla.

What are .htaccess files anyway?


Simply put, they are invisible plain text files where one can store server directives. Server directives are anything you might put in an Apache config file (h t t p d . c o n f ) or even a p h p . i n i **, but unlike those "master" directive files, these .htaccess directives apply only to the folder in which the .htaccess file resides, and all the folders inside. This ability to plant .htaccess files in any directory of our site allows us to set up a finely-grained tree of server directives, each subfolder inheriting properties from its parent, whilst at the same time adding to, or over-riding certain directives with its own .htaccess file. For instance, you could use .htacces to enable indexes all over your site, and then deny indexing in only certain subdirectories, or deny index listings site-wide, and allow indexing in certain subdirectories. One line in the .htaccess file in your root and your whole site is altered. From here on, I'll probably refer to the main .htaccess in the root of your website as "the master .htaccess file", or "main" .htaccess file. There's a small performance penalty for all this .htaccess file checking, but not noticeable, and you'll find most of the time it's just on and there's nothing you can do about it anyway, so let's make the most of it..
corz.org/serv/tricks/htaccess.php 2/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

** Your main p h p . i n i , that is, unless you are running under phpsuexec, in which case the directives would go inside individual p h p . i n ifiles

Is .htaccess enabled?
It's unusual, but possible that .htaccess is not enabled on your site. If you are hosting it yourself, it's easy enough to fix; open your h t t p d . c o n fin a text editor, and locate this < D i r e c t o r y >section.. Your D o c u m e n t R o o tmay be different, of course.. # This should be changed to whatever you set DocumentRoot to. # <Directory "/var/www/htdocs"> # ..locate the line that reads.. AllowOverride None ..and change it to.. AllowOverride All Restart Apache. Now .htaccess will work. You can also make this change inside a virtual host, which would normally be preferable. If your site is hosted with someone else, check your control panel (Plesk. CPanel, etc.) to see if you can enable it there, and if not, contact your hosting admins. Perhaps they don't allow this. In which case, switch to a better web host.

What can I do with .htaccess files?


Almost any directive that you can put inside an h t t p d . c o n ffile will also function perfectly inside an .htaccess file. Unsurprisingly, the most common use of .htaccess is to..

Control (A l l o w /D e n y ) Access..
.htaccess is most often used to restrict or deny access to individual files and folders. A typical example would be an "includes" folder. Your site's pages can call these included scripts all they like, but you don't want users accessing these files directly, over the web. In that case you would drop an .htaccess file in the includes folder with content something like this..
corz.org/serv/tricks/htaccess.php 3/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

NO ENTRY! # no one gets in here! deny from all which would deny ALL direct web (HTTP) access to ANY files in that folder (your scripts reach them via the filesystem). You can be more specific with your conditions, for instance limiting access to a particular IP range, here's a handy top-level ruleset for a local test server.. NO ENTRY outside of the LAN! # no nasty crackerpots in here! Order Allow,Deny Deny from All Allow from 192.168.0.0/24 # this would do the same thing.. #Allow from 192.168.0 Note the O r d e rdirective, which controls the order in which Apache handles the access rules (aka. directives) when making its three passes. With A l l o w , D e n y , first checking and applying A l l o wrules, then D e n yrules, and denying everything else. With D e n y , A l l o w , first applying D e n yrules, then A l l o wrules, then allowing everything else. If you think about it, the D e n yline in example above, is redundant. This.. NO ENTRY outside of the LAN! Order Allow,Deny Allow from 192.168.0 .. is enough to secure a local server. And because Apache processes the directives in three groups (one on each pass), the processing order defined by the O r d e rdirective, the actual ordering of the rules in your config file is unimportant. This.. NO ENTRY outside of the LAN! Allow from 192.168.0.0/24 Order Allow,Deny ..is identical in operation to the previous example. Generally these sorts of requests would bounce off your firewall anyway, but on a live server (like my dev mirrors sometimes are) they become useful for filtering out undesirable IP blocks, known risks, lots of things. By the way, in case you hadn't spotted; lines beginning with "#" are ignored by Apache; handy for comments. Sometimes, you will only want to ban one IP, perhaps some persistent robot that doesn't play by the rules..
corz.org/serv/tricks/htaccess.php 4/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

post user agent every fifth request only. hmmm. ban IP.. # someone else giving the ruskies a bad name.. order allow,deny deny from 83.222.23.219 allow from all The usual rules for IP addresses apply, so you can use partial matches, ranges, and so on. Whatever, the user gets a 403 "access denied" error page in their client software (browser, usually), which certainly gets the message across. This is probably fine for most situations, but in part two I'll demonstrate some cooler ways to deny access, as well as how to deny those nasty web suckers, bad referrers, script kiddies and more. One final note about A l l o wand D e n yrules for local servers (or anywhere you have acceess to the main h t t p d . c o n f ,v h o s t . c o n fand such files). If A l l o w O v e r r i d eA l lis set in a config file processed before the one containing these rules (it usually is), they will override any rules set in the preceding config file. For example, if you have A l l o w O v e r r i d eA l land D e n yA l lset in your V i r t u a l H o s tconfig, and A l l o wA l lin your . h t a c c e s s , the . h t a c c e s srules apply, allowing access from all addresses. If you delete the A l l o wrule in the . h t a c c e s s , the rules from your V i r t u a l H o s tconfig will apply. If you delete those rules, the ones from your main httpd.conf will apply. < L o c a t i o n >rules override everything.

Custom error documents..


I guess I should briefly mention that .htaccess is where most folk configure their error documents. Usually with sommething like this.. the usual method. the "err" folder (with the custom pages) is in the root # custom error documents ErrorDocument 401 /err/401.php ErrorDocument 403 /err/403.php ErrorDocument 404 /err/404.php ErrorDocument 500 /err/500.php You can also specify external URLs, though this can be problematic, and is best avoided. One quick and simple method is to specify the text in the directive itself, you can even use HTML (though there is probably a limit to how much HTML you can squeeze onto one line). Remember, for Apache 1; begin with a ", but DO NOT end with one. For Apache 2, you can put a second quote at the end, as normal. measure twice, quote once.. # quick custom error "document"..
corz.org/serv/tricks/htaccess.php 5/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

ErrorDocument 404 "<html><head><title>NO!</title></head><body><h2><tt>There is nothing here.. go away quickly!</tt></h2></body></html> Using a custom error document is a Very Good Idea, and will give you a second chance at your almost-lost visitors. I recommend you download mine. But then, I would.

Password protected directories..


The next most obvious use for our .htaccess files is to allow access to only specific users, or user groups, in other words; password protected folders. a simple authorisation mechanism might look something like this.. a simple sample .htaccess file for password protection: AuthType Basic AuthName "restricted area" AuthUserFile /usr/local/var/www/html/.htpasses require valid-user You can use this same mechanism to limit only certain kinds of requests, too.. only valid users can POST in here, anyone can GET, PUT, etc: AuthType Basic AuthName "restricted area" AuthUserFile /usr/local/var/www/html/.htpasses <Limit POST> require valid-user </Limit> You can find loads of online examples of how to setup authorization using .htaccess, and so long as you have a real user (or create one, in this case, 'jimmy') with a real password (you will be prompted for this, twice) in a real password file (the cswitch will create it).. h t p a s s w dc/ u s r / l o c a l / v a r / w w w / h t m l / . h t p a s s e sj i m m y ..the above will work just fine. h t p a s s w dis a tool that comes free with Apache, specifically for making and updating password files, check it out. The windows version is the same; only the file path needs to be changed; to wherever you want to put the password file. Note: if the Apache b i n /folder isn't in your PATH, you will need to c dinto that directory before performing the command. Also note: You can use forward and back-slashes interchangeably with Apache/php on Windows, so this would work just fine.. h t p a s s w dcc : / u n i x / u s r / l o c a l / A p a c h e 2 / c o n f / . h t p a s s e sj i m m y
corz.org/serv/tricks/htaccess.php 6/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

Relative paths are fine too; assuming you were inside the b i n /directory of our fictional Apache install, the following would do exactly the same as the above.. h t p a s s w dc. . / c o n f / . h t p a s s e sj i m m y Naming the password file . h t p a s s e sis a habit from when I had to keep that file inside the web site itself, and as web servers are configured to ignore files beginning with . h t , they too, remain hidden. If you keep your password file outside the web root (a better idea), then you can call it whatever you like, but the . h t _ s o m e t h i n ghabit is a good one to keep, even inside the web tree, it is secure enough for our basic purpose.. Once they are logged in, you can access the r e m o t e _ u s e renvironmental variable, and do stuff with it.. the r e m o t e _ u s e rvariable is now available.. RewriteEngine on RewriteCond %{remote_user} !^$ [nc] RewriteRule ^(.*)$ /users/%{remote_user}/$1 Which is a handy directive, utilizing m o d _ r e w r i t e ; a subject I delve into far more deeply, in part two.

Get better protection..


The authentication examples above assume that your web server supports "Basic" http authorisation, as far as I know they all do (it's in the Apache core). Trouble is, some browsers aren't sending password this way any more, personally I'm looking to php to cover my authorization needs. Basic auth works okay though, even if it isn't actually that secure - your password travels in plain text over the wire, not clever. If you have php, and are looking for a more secure login facility, check out pajamas. It's free. If you are looking for a password-protected download facility (and much more, besides), check out my distro machine, also free.

500 error..
If you add something that the server doesn't understand or support, you will get a 500 error page, aka.. "the server did a boo-boo". Even directives that work perfectly on your test server at home may fail dramatically at your real site. In fact this is a great way to find out if .htaccess files are enabled on your site; create one, put some gibberish in it, and load a page in that folder, wait for the 500 error. if there isn't one, probably they are not enabled. If they are, we need a way to safely do live-testing without bringing the whole site to a 500 standstill. Fortunately, in much the same way as we used the < L i m i t >tag above, we can create conditional directives, things which will only come into effect if certain conditions are true. The most useful of
corz.org/serv/tricks/htaccess.php 7/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

these is the "ifModule" condition, which goes something like this.. only if PHP is loaded, will this directive have any effect (switch the 4 for a 5 if using php5) <ifModule mod_php4.c> php_value default_charset utf-8 </ifModule> ..which placed in your master .htaccess file, that would set the default character encoding of your * entire site to utf-8 (a good idea!), at least, anything output by PHP. If the PHP4* module isn't running on the server, the above .htaccess directive will do exactly nothing; Apache just ignores it. As well as proofing us against knocking the server into 500 mode, this also makes our .htaccess directives that wee bit more portable. Of course, if your syntax is messed-up, no amount of if-module-ing is going to prevent a error of some kind, all the more reason to practice this stuff on a local test server. * *note: if you are using php5, you would obviously instead use < i f M o d u l e m o d _ p h p 5 . c > .

Groovy things to do with .htaccess..


So far we've only scratched the surface. Aside from authorisation, the humble .htaccess file can be put to all kinds of uses. If you've ever had a look in my public archives you will have noticed that that the directories are fully browsable, just like in the old days before adult web hosts realized how to turn that feature off! A line like this.. bring back the directories! Options +Indexes +MultiViews +FollowSymlinks ..will almost certainly turn it back on again. And if you have m o d _ a u t o i n d e x . cinstalled on your server (probably, yes), you can get nice fancy indexing, too.. show me those files! <IfModule mod_autoindex.c> IndexOptions FancyIndexing </ifModule> ..which, as well as being neater, allows users to click the titles and, for instance, order the listing by date, or file size, or whatever. It's all for free too, built-in to the server, we're just switching it on. You can control certain parameters too.. let's go all the way!
corz.org/serv/tricks/htaccess.php 8/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

<IfModule mod_autoindex.c> IndexOptions FancyIndexing IconHeight=16 IconWidth=16 </ifModule> Other parameters you could add include.. NameWidth=30 DescriptionWidth=30 IconsAreLinks SuppressHTMLPreamble (handy!) I'm not mentioning the "XHTML" parameter in Apache2, because it still isn't! Anyways, I've chucked one of my old fancy indexing .htaccess file onsite for you to have some fun with. Just add readme.html and away you go! note: these days I use a single header files for all the indexes.. HeaderName /inc/header.html .. and only drop in local "readme" files. Check out the example, and my public archives for more details.

custom directory index files


While I'm here, it's worth mentioning that . h t a c c e s sis where you can specify which files you want to use as your indexes, that is, if a user requests / f o o / , Apache will serve up / f o o / i n d e x . h t m l , or whatever file you specify. You can also specify multiple files, and Apache will look for each in order, and present the first one it finds. It's generally setup something like.. DirectoryIndex index.html index.php index.htm

It really is worth scouting around the Apache documentation, often you will find controls for things you imagined were uncontrollable, thereby creating new possibilities, better options for your website. My experience of the magic "LAMP" (Linux-Apache-MySQL-PHP) has been.. "If you can imagine that it can be done, it can be done". Swap "Linux" for any decent operating system, the "AMP" part runs on most of them. Okay, so now we have nice fancy directories, and some of them password protected, if you don't watch out, you're site will get popular, and that means bandwidth..

Save bandwidth with .htaccess!


corz.org/serv/tricks/htaccess.php 9/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

If you pay for your bandwidth, this wee line could save you hard cash.. save me hard cash! and help the internet! <ifModule mod_php4.c> php_value zlib.output_compression 16386 </ifModule> All it does is enables PHP's built-in transparent zlib compression. This will half your bandwidth usage in one stroke, more than that, in fact. Of course it only works with data being output by the PHP module, but if you design your pages with this in mind, you can use php echo statements, or better yet, php "includes" for your plain html output and just compress everything! Remember, if you run phpsuexec, you'll need to put php directives in a local p h p . i n ifile, not .htaccess. See here for more details.

Hide and deny files..


Do you remember I mentioned that any file beginning with .ht is invisible? .."almost every web server in the world is configured to ignore them, by default" and that is, of course, because .ht_anything files generally have server directives and passwords and stuff in them, most servers will have something like this in their main configuration.. Standard setting.. <Files ~ "^\.ht"> Order allow,deny Deny from all Satisfy All </Files> which instructs the server to deny access to any file beginning with .ht, effectively protecting our .htaccess and other files. The "." at the start prevents them being displayed in an index, and the .ht prevents them being accessed. This version.. ignore what you want <Files ~ "^.*\.([Ll][Oo][Gg])"> Order allow,deny Deny from all Satisfy All </Files> tells the server to deny access to *.log files. You can insert multiple file types into each rule, separating them with a pipe "|", and you can insert multiple blocks into your .htaccess file, too. I find it convenient to put all the files starting with a dot into one, and the files with denied extensions into another, something like this..

corz.org/serv/tricks/htaccess.php

10/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

the whole lot # deny all .htaccess, .DS_Store $h and ._* (resource fork) files <Files ~ "^\.([Hh][Tt]|[Dd][Ss]_[Ss]|[_])"> Order allow,deny Deny from all Satisfy All </Files> # deny access to all .log and .comment files <Files ~ "^.*\.([Ll][Oo][Gg]|[cC][oO][mM][mM][eE][nN][tT])"> Order allow,deny Deny from all Satisfy All </Files> would cover all ._* resource fork files, .DS_Store files (which the Mac Finder creates all over the place) *.log files, *.comment files and of course, our .ht* files. You can add whatever file types you need to protect from direct access. I think it's clear now why the file is called ".htaccess".

<FilesMatch>
These days, using < F i l e s M a t c h >is preferred over < F i l e s > , mainly because you can use regular expression in the conditions (very handy), produce clean, more readable code. Here's an example. which I use for my php-generated style sheets.. parse file.css and file.style with the php machine.. # handler for phpsuexec.. <FilesMatch "\.(css|style)$"> SetHandler application/x-httpd-php </FilesMatch> Any files with a * . c s sor * . s t y l eextension will now be handled by php, rather than simply served up by Apache. And because you can use regexp, you could do stuff like < F i l e s M a t c h" \ . s ? h t m l $ " > , which is handy. Any < F i l e s >statements you come across can be advantageously replaced by < F i l e s M a t c h >statements. Good to know.

More stuff..
At the end of my .htaccess files, there always seems to be a section of "stuff"; miscellaneous commands, mainly php flags and switches; so it seems logical to finish up the page with a wee selection of those.. php flags, switches and other stuff..
corz.org/serv/tricks/htaccess.php 11/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

# let's enable php (non-cgi, aka. 'module') for EVERYTHING..' AddType application/x-httpd-php5 .htm .html .php .blog .comment .inc # better yet.. AddHandler php5-script .php # legacy php4 version..' AddType application/x-httpd-php .htm .html .php .blog .comment .inc # don't even think about setting this to 'on' php_value register_globals off # no session id's in the URL PULEEZE! php_value session.use_trans_sid 0 # should be the same as.. php_flag session.use_trans_sid off # using both should also work fine! # php error logs.. php_flag display_errors off php_flag log_errors on php_value track_errors on php_value error_log /home/cor/errors/phperr.log # if you like to collect interesting php system shell access and web hack scripts # get yourself a SECURE upload facility, and just let the script-kiddies come # in no time you will have a huge selection of fascinating code. If you want folk to # also upload zips and stuff, you might want to increase the upload capacities.. php_value upload_max_filesize 12M php_value post_max_size 12M # php 5 only, afaik. handy when your server isn't where YOU are. php_value date.timezone Europe/Aberdeen # actually, Europe/Aberdeen isn't a valid php timezone, so that won't work. # I recommend you check the php manual for this function, because many crazy places ARE! Note: For most of the flags I've tested, you can use o n /o f fand t r u e /f a l s einterchangeably, as well as 0 /1 , also p h p _ v a l u eand p h p _ f l a gcan be switched around while things continue to work as expected! I guess, logically, booleans should always be p h p _ f l a g , and values, p h p _ v a l u e ; but suffice to say, if some php erm, directive isn't working, these would all be good things to fiddle with! Of course, the php manual explains all. The bottom line is; both will work fine, but if you use the wrong type in .htaccess, say, set a p h p _ f l a gusing p h p _ v a l u e , a php i n i _ g e t ( )command, for instance, would return t r u e , even though you had set the value to o f f , because it reads o f fvalue as a string, which of course evaluates to not-zero, i.e. 1, or "true". If you don't rely on g e t _ i n i ( ) , or similar, it's not a problem, though clearly it's better to get it right from the start. By the way; one of the values above is incorrectly set. Did you spot it?
corz.org/serv/tricks/htaccess.php 12/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

Most php settings, you can override inside your actual scripts, but I do find it handy to be able to set defaults for a folder, or an entire site, using .htaccess.

over to you..
That should get you started with .htaccess, quite easy when you know how. If you really want to bend your brain out of shape, follow the link below for part two of the series, where I delve into the arcane mysteries of URL rewriting.

;o) Cor

Useful Links..
Apache2 .htaccess docs .htaccess info, straight from the Horse's mouth. .htaccess generator Rather neat online php .htaccess generator tool - aka. 'Dot Htaccesser', by Chris Todd .htaccess generator source The php source for the above tool. The original site has disappeared. Get Domains, cheap. After years of trouble-free, cheap service, I can definitely recommend these guys for your domain needs. This page in Belorussian The official Belorussian human-translation of .htaccess tricks and tips. Serbo-Croatian version The official Serbo-Croatian human-translation of ".htaccess tricks and tips".

go to part two..

Before you ask a question..


Firstly, read this at least once in your life. I insist!
NOTE: THIS IS NOT A COMMUNITY. And I am not
corz.org/serv/tricks/htaccess.php 13/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

your free tech dude. Sure, folk sometimes drop back in, but realistically, the chances of someone else coming along and answering your tech question are about as close to zero as it gets; almost no one sticks around but me, the guy who wrote all that text (above). If you can't be bothered to read the article, I can't be bothered responding. Capiche? I do read all comments, though, and answer questions about the article. I'm also keen to discuss anything you think I've missed, or interesting related concepts in general. If you are still sure that you want to post your own, personal, tech question, then please ensure that you first, either.. a) Have read the article (above) and have tried "everything" yourself; in which case; post the exact code that isn't working (preferably inside [ p r e ] [ / p r e ]tags), replacing any personal domain names with "example.com" (advertising gets deleted) or else.. b) Pay me. The PayPal button is at the top right of the page. I offer many related services, if you need priority assistance, get in touch. Other posts will be ignored and/or deleted.

If you want to know about rewriting with mod_rewrite please see the next page!
cbparser powered comments.. previous comments (fourteen pages) Bill - 16.09.11 12:23 pm Thanks for the crash course in .htaccess. I feel like I"ve learned enough to be dangerous! nayandeep - 04.10.11 2:33 pm i want to more about .htaccess. how apply a block of code of htaccess file on whole website to re-write url
corz.org/serv/tricks/htaccess.php 14/23

show all comments

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

Put the command in the root .htaccess file. The rule cascades automatically. ;o) Cor

domainmonstrocity - 08.10.11 2:44 am I am a newbie at Web Hosting and I very much appreciate these tips. Feel free to check out my website at the name above and add the .com at the end. I won't spam ya Simon - 18.10.11 2:20 pm "Does godaddy support .htaccess ?" My understanding is that they do, but changes to htaccess files may take an hour to take effect. This may only apply to virtual server hosting. not sure 18/10/2011 Powers - 27.10.11 10:26 am First of all I want to say great site, I never even knew what htacess was until I landed here. My question is when I put deny all into one of my folders it works. The only problem is, the files in that folder can not be linked to my pages. I have a CSS folder with all my CSS inside. I also have other folders for Javascripts and so on. I dont want someone typing mysite.com/css/style.css and getting a look at my CSS or javascripts. When I place "deny all" My pages outside the folders do not call my CSS or Javascripts. Can you help please? Thanks The link you want is hidden away up there in the main article, in the "Control access.." section, but I'll re-post it here for your convenience. ;o) Cor

Thanks - 01.11.11 8:11 pm Just a quick one. If I have PHP enabled on my server will it still make sense to write the following line?
corz.org/serv/tricks/htaccess.php 15/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

<IfModule mod_php5.c> What actually does mod_php5.c check for? Check if php5 module is loaded or not? Due to which PHP can run on that Apache server? So my question here is even if I use that tag and still get an error then in that case is it because I am not allowed to change the value of that php setting in the .htaccess file? btw Corz I love your site. Your post help me tremendously in understanding things so easily Keep up the good work This tag creates a CONDITION, like I said above, only if php is loaded will the commands within it come into effect. If you have some wonky code that causes an error, putting it inside a conditional tag that is true (i.e. the php5 module IS loaded) causes the wonky code to run, which again causes the same error. The idea of using a conditional section is to prevent code from running in inappropriate environments, for example, trying to tell a php4 server to set p h p _ v a l u e d a t e . t i m e z o n ewhich only became available with php5. And of course, none of this works if php is running as a cgi rather than a module.. ;o) Cor

Manohar - 01.12.11 5:07 pm great concept xxx - 01.12.11 11:08 pm WTF!!

OH Fiddlestix - 13.12.11 3:54 am I don't know how I found this site, somebody help me, how do you get back to the world of no answers that make any sense?

corz.org/serv/tricks/htaccess.php

16/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

Surojit - 16.12.11 9:40 pm Hi, I'm looking for a way to save wrong url strings, so I could register what wrong urls visitors are trying to reach. some like this: visitor tried: http://www.site.com/anywrongurl htaccess redirects: ErrorDocument 404 http://www.site.com/error.php? url=anywrongurl error.php does: saves url parameter into database and redirects to home page (or anywhere). Tks, congratulations for the page and marry christmas. Ricardo Yup, that's roughly how to do it (except you don't add ? parmeters to the 404 ErrorDocument command, you get the 404 script to grab the URI from the incoming HTTP request headers, i.e.. $ _ S E R V E R [ ' R E Q U E S T _ U R I ' ] ). If you get stuck, take a look at my own 404 script which does this and a whole lot more. ;o) Cor

Robert Benson - 17.02.12 9:12 pm In my .htaccess file I have: ErrorDocument 404 " (message) " What could possibly go wrong? Well, selected IPs are getting the standard "Oops!!!" page instead of above message. What am I doing wrong? Thank you. 'standard "Oops!!!" page '? ;o) Cor

Robert Benson - 12.04.12 5:19 pm


corz.org/serv/tricks/htaccess.php 17/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

In my .htaccess file I want to deny access to all domains ending in .gov . Is this possible? How do I do it? Thank you! I don't follow. Do you mean deny access (to your web site) to people coming from .gov sites (referers)? Or deny access (to your web site) to people inside the .gov IP blocks? Or deny access to .gov sites from your own network? Or something else? ;o) Cor

Robert Benson - 13.04.12 4:47 pm Sorry - was not clear. What I want to do is block access to all traffic from persons sitting at Government desks using Government computers. These would be domains, I'm assuming, that end in .gov . So is there a wild card I can use in .htaccess that in one line will exclude all the domains ending in .gov ? This would be super helpful to me, because the onesy-twosy mode is getting tiresome! There is another beer in this for you. Thanks. I'm not familiar with the onesy-twosy method, though it sounds like a lot of fun! As for your .gov clients, YES, it is theoretically possible to deny access to folk inside those domains, you simply use: D e n yf r o m. g o v HOWEVER, for this to work, you will need to have host lookups enabled. Theoretically, again, you can achieve this in .htaccess, like so.. H o s t n a m e L o o k u p sO n but in practice, that will most likely get you a 500 error. Try it and see. HostnameLookups is somewhat wasteful of server resources, due to the DNS query being performed before each request is processed.
corz.org/serv/tricks/htaccess.php 18/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

If it's your own server, you can easily enable this in your main h t t p d . c o n f(or equivalent). If it's a shared server, the admins are unlikely to enable it for the above mentioned reason. Failing all that, you can block the IP ranges associated with these domains, though with .gov, .mil, etc., this would be a huge list. Here's a slightly out-of-date version of that list.. http://www.totse2.com/totse/en/hack/understanding_the_internet/governmentowne170262.html Here's where to get a current list of all the .gov domains, though without IP address information.. https://explore.data.gov/Federal-Government-Financesand-Employment/Federal-Executive-Branch-InternetDomains/k9h8-e98h Clearly, translating all that to an IP database would be a huge effort, though not beyond the scope of a fairly simple program. And if you are programming something, this would probably be best handled with php (or similar), doing DNS calls for all inbound requests and creating a black-list of any domains which match your criteria (.gov, etc.), somewhat like the latest version of Anti-Hammer does for referers. Your php script (most likely used as an "Auto-Prepend") would consult its local black-list before performing lookups, and if an IP is there, no lookup need be performed, saving resources and bandwidth. The advantage of a php-based solution is that you don't need shared server admins to do anything. Just code-andgo! Have fun! ;o) Cor

zauber - 18.10.12 12:15 pm can you break up a picture into dots and make it writeable so replce each dot with the original color + some text?

corz.org/serv/tricks/htaccess.php

19/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

how? where do find info for such a task? how do i break up a pic into writeable dots + orignal color so when I look at original dots, from ABOVE", i still see the original picture?? can this be done? how? how hard? what do i need? need to know what? thanks much.. Jim - 23.10.12 9:38 pm I read your tutorial 3 times. Thanks for using layman's terms for we noobs but I still have a question, if you don't mind expanding one of your tips. You said: "Save bandwidth with .htaccess" I have reseller account on Hostgator with .htaccess enabled on WordPress blog. Will this work for me? If Yes, where in .htaccess do I place your snippet? At the head? Tail? Thanks Wherever you like! The whole .htaccess is processed before serving the page. ;o) Cor

Paul - 03.12.12 11:44 pm Hi Corz, Just dropping a line being you allow me to! Fantastic site , Fantastic work, I was completely blown away at how much effort you have put into this and how open you are with helping others out excellent to see that human beings can still be helpful (my little bit of doubt in mankind creeping in my apologies) I must say I will return and see what else you get up to and I love some of the excellent downloads Anyway Thank you been a pleasure being here and I will be back ! Your Hashing program is what got me here and it is indeed amazingly fast, I may drop you a line as to a little project which would use
corz.org/serv/tricks/htaccess.php 20/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

your hashing program and would like your advice on it some time, but let me get my thoughts together and then compile an email to you rather than here in plan view.

Michael - 11.12.12 3:09 pm Thank you for all the examples, really helpful to learn more by oneself!

Steve - 01.02.13 12:20 am Hi, I found your article during my search for information. Good article. However, I do have a question why my application does not apply the rules in the .htaccess as you described them. For example: / a p p / i n c l u d e 1 . h t a c c e s s-d e n yf r o ma l l f i l e s . . . / p h p s c r i p t s . h t a c c e s s-d e n yf r o ma l l p h pf i l e i n d e x . p h p . h t a c c e s s-O p t i o n sI n d e x e s When I visit my site through localhost (localhost/app/index.php), it displays the web page created by index.php. However when I clicked a link on the index page, which points to a script named test.php located in the folder /phpscripts, I get the message that /phpscripts/test.php is forbidden. I though your article stated that files in /phpscripts would be accessible through the filesystem? Am I missing something? I'm trying to restrict access to PHP files located in /phpscripts folder from
corz.org/serv/tricks/htaccess.php 21/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

visitors to my site, but be able to run them through the filesystem. Any help would be appreciated. When you say, "points to a script named test.php located in the folder /phpscripts", do you mean it includes it? If so, you have a problem. If it's just a link the user has to click, then everything is working as expected. ;o) Cor

John - 01.02.13 7:16 pm Thanks for helping so many of us with great information! I would like to limit the requests for any single page to a set number within a set time from any single requester. (Sort of like a DOS attack.) Say a limit of 5 requests within 30 seconds. How would I do this, is it even possible? As far as I know, you cannot do this in .htaccess. But you can do it with anti-hammer. Note, the version on the page has been superceded with an as yet unavailable beta which has much more functionality - until I get a chance to get that up, feel free to mail me for a copy. ;o) Cor

Steve - 01.02.13 9:20 pm Thanks for your prompt reply. I do have a question about the /include1 folder. In my setup, the /include1 folder contains files for PHP functions and other useful PHP code that are 'included' and used by application PHP scripts. I want to setup the structure and .htaccess to allow the application PHP scripts to use the keyword 'include' to add PHP files from the /include1 directory but PREVENT site visitors from running the /include1 PHP files directly (these files only make sense in the context where they are included)? Any help would be appreciated! It is explained here. ;o) Cor

corz.org/serv/tricks/htaccess.php

22/23

25/06/13

.htaccess tricks and tips.. part one: tips, tricks, hints, examples; juicy .htaccess information.

Chetan Sharma - 31.03.13 1:33 pm Thanks buddy, it really helps

Automatic Section Links

corz.org/serv/tricks/htaccess.php

23/23