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

Upload: henry-leonardo-diaz-gutierrez

Post on 02-Apr-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    1/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php

    Site Navigation

    Top Links

    .htaccess tips and tricks

    clever stuff here

    Introduction to .htaccess..

    This work in constant progress is some collected wisdom, stuff I've learned on the topic of .htaccesshacking, commands I've used successfully in the past, on a variety of server setups, and in mostcases still do. You may have to tweak the examples some to get the desired result, though, and areliable test server is a powerful ally, preferably one with a similar setup to your "live" server. Okay, tobegin..

    ..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 theworld is configured to ignore them, by default. Same goes for most operating systems. Mainly it's thedot "." 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 texteditor that allows you to open hidden files, something like bbedit on the Mac platform. On windows,

    http://corz.org/serv/tricks/htaccess.php#section-hide_and_deny_files
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    2/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 2

    showing invisibles in explorer should allow any text editor to open them, and most decent editors tosave 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 necessarysometimes. 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 beinghandled by my clever 404 script.

    ** even notepad can save files beginning with a dot, if you put double-quotes around thename when you save it; i.e.. ".htaccess". You can also use your ftp client to rename filesbeginning 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 directivesare anything you might put in an Apache config file (httpd.conf) or even a php.ini**, but unlikethose "master" directive files, these .htaccess directives apply only to the folder in which the .htaccessfile 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 treeof server directives, each subfolder inheriting properties from its parent, whilst at the same timeadding 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, ordeny index listings site-wide, and allow indexing in certain subdirectories. One line in the .htaccess filein your root and your whole site is altered. From here on, I'll probably refer to the main .htaccess inthe 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'llfind most of the time it's just on and there's nothing you can do about it anyway, so let's make themost of it..

    http://filezilla-project.org/http://corz.org/serv/tools/active-errors/http://corz.org/serv/tricks/htaccess.php#windows-invisible-save-tricks
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    3/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 3

    ** Your main php.ini, that is, unless you are running under phpsuexec, in which case the directiveswould go inside individual php.ini files

    Is .htaccess enabled?

    It's unusual, but possible that .htaccess is not enabled on your site. If you are hosting it yourself, it'seasy enough to fix; open your httpd.conf in a text editor, and locate this section..

    Your DocumentRoot may be different, of course..# This should be changed to whatever you set DocumentRoot to.##

    ..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, whichwould normally be preferable.

    If your site is hosted with someone else, check your control panel (Plesk. CPanel, etc.) to see if youcan enable it there, and if not, contact your hosting admins. Perhaps they don't allow this. In whichcase, switch to a better web host.

    What can I do with .htaccess files?

    Almost any directive that you can put inside an httpd.conf file will also function perfectly inside an

    .htaccess file. Unsurprisingly, the most common use of .htaccess is to..

    Control (Allow/Deny) Access..

    .htaccess is most often used to restrict or deny access to individual files and folders. A typical examplewould be an "includes" folder. Your site's pages can call these included scripts all they like, but youdon't want users accessing these files directly, over the web. In that case you would drop an .htaccessfile in the includes folder with content something like this..

  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    4/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 4

    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 aparticular 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,DenyDeny from All

    Allow from 192.168.0.0/24# this would do the same thing..#Allow from 192.168.0

    Note the Order directive, which controls the order in which Apache handles the access rules (aka.directives) when making its three passes. With Allow,Deny, first checking and applying Allow rulesthen Deny rules, and denying everything else. With Deny,Allow, first applying Deny rules, thenAllow rules, then allowing everything else.

    If you think about it, the Deny line 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 Order directive, the actual ordering of therules in your config file is unimportant. This..

    NO ENTRY outside of the LAN!Allow from 192.168.0.0/24Order 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 mydev 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 therules..

  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    5/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 5

    post user agent every fifth request only. hmmm. ban IP..# someone else giving the ruskies a bad name..order allow,denydeny from 83.222.23.219allow from all

    The usual rules for IP addresses apply, so you can use partial matches, ranges, and so on. Whateverthe user gets a 403 "access denied" error page in their client software (browser, usually), whichcertainly gets the message across. This is probably fine for most situations, but in part two I'lldemonstrate some cooler ways to deny access, as well as how to deny those nasty web suckers, badreferrers, script kiddies and more.

    One final note about Allow and Deny rules for local servers (or anywhere you have acceess to themain httpd.conf, vhost.conf and such files). IfAllowOverride All is set in a config fileprocessed before the one containing these rules (it usually is), they will override any rules set in thepreceding config file.

    For example, if you have AllowOverride All and Deny All set in your VirtualHost config,and Allow All in your .htaccess, the .htaccess rules apply, allowing access from alladdresses. If you delete the Allow rule in the .htaccess, the rules from your VirtualHost configwill apply. If you delete those rules, the ones from your main httpd.conf will apply. rulesoverride 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 documentsErrorDocument 401 /err/401.phpErrorDocument 403 /err/403.phpErrorDocument 404 /err/404.phpErrorDocument 500 /err/500.php

    You can also specify external URLs, though this can be problematic, and is best avoided. One quickand simple method is to specify the text in the directive itself, you can even use HTML (though thereis 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, asnormal.

    measure twice, quote once..# quick custom error "document"..

    http://corz.org/serv/tricks/htaccess2.php#cooldenial
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    6/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 6

    ErrorDocument 404 "NO!Thereis nothing here.. go away quickly!

    Using a custom error document is a Very Good Idea, and will give you a second chance at youralmost-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 usergroups, in other words; password protected folders. a simple authorisation mechanism might looksomething like this..

    a simple sample .htaccess file for password protection:AuthType BasicAuthName "restricted area"

    AuthUserFile /usr/local/var/www/html/.htpassesrequire 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 BasicAuthName "restricted area"AuthUserFile /usr/local/var/www/html/.htpasses

    require valid-user

    You can find loads ofonline examples of how to setup authorization using .htaccess, and so long asyou have a real user (or create one, in this case, 'jimmy') with a real password (you will be promptedfor this, twice) in a real password file (the -c switch will create it)..

    htpasswd -c /usr/local/var/www/html/.htpasses jimmy

    ..the above will work just fine. htpasswd is a tool that comes free with Apache, specifically formaking and updating password files, check it out. The windows version is the same; only the file pathneeds to be changed; to wherever you want to put the password file.

    Note: if the Apache bin/ folder isn't in your PATH, you will need to cd into that directory beforeperforming the command. Also note: You can use forward and back-slashes interchangeably with

    Apache/php on Windows, so this would work just fine..

    htpasswd -c c:/unix/usr/local/Apache2/conf/.htpasses jimmy

    http://httpd.apache.org/docs/howto/auth.htmlhttp://corz.org/serv/tools/active-errors/
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    7/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 7

    Relative paths are fine too; assuming you were inside the bin/ directory of our fictional Apacheinstall, the following would do exactly the same as the above..

    htpasswd -c ../conf/.htpasses jimmy

    Naming the password file .htpasses is a habit from when I had to keep that file inside the web siteitself, and as web servers are configured to ignore files beginning with .ht, 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 .ht_something habit is a good one to keep, even inside the web tree, it is secureenough for our basic purpose..

    Once they are logged in, you can access the remote_user environmental variable, and do stuff withit..

    the remote_user variable is now available..RewriteEngine onRewriteCond %{remote_user} !^$ [nc]RewriteRule ^(.*)$ /users/%{remote_user}/$1

    Which is a handy directive, utilizing mod_rewrite; 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 sendingpassword 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 overthe wire, not clever.

    If you have php, and are looking for a more secure login facility, check out pajamas. It's free. If youare looking for a password-protected download facility (and much more, besides), check out my distromachine, 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 mayfail dramatically at your real site. In fact this is a great way to find out if .htaccess files are enabled onyour site; create one, put some gibberish in it, and load a page in that folder, wait for the 500 error. ifthere 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 tag above, we can create conditionaldirectives, things which will only come into effect ifcertain conditions are true. The most useful of

    http://corz.org/serv/tools/distromachine/http://corz.org/serv/security/pajamas.phphttp://corz.org/engine?source=menu&section=php%2Fsecurityhttp://corz.org/serv/tricks/htaccess2.php
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    8/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 8

    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)php_value default_charset utf-8

    ..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 runningon the server, the above .htaccess directive will do exactly nothing; Apache just ignores it. As well asproofing us against knocking the server into 500 mode, this also makes our .htaccess directives thatwee bit more portable. Of course, if your syntax is messed-up, no amount of if-module-ing is going toprevent 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 .

    Groovy things to do with .htaccess..

    So far we've only scratched the surface. Aside from authorisation, the humble .htaccess file can beput to all kinds of uses. If you've ever had a look in my public archives you will have noticed that thatthe directories are fully browsable, just like in the old days before adult web hosts realized how to turnthat 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 mod_autoindex.c installed on yourserver (probably, yes), you can get nice fancy indexing, too..

    show me those files!

    IndexOptions FancyIndexing

    ..which, as well as being neater, allows users to click the titles and, for instance, order the listing bydate, or file size, or whatever. It's all for free too, built-in to the server, we're just switching it on. Youcan control certain parameters too..

    let's go all the way!

    http://corz.org/public/
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    9/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

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

    IndexOptions FancyIndexing IconHeight=16 IconWidth=16

    Other parameters you could add include..

    NameWidth=30DescriptionWidth=30IconsAreLinks SuppressHTMLPreamble (handy!)

    I'm not mentioning the "XHTML" parameter in Apache2, because it still isn't! Anyways, I've chuckedone of my old fancy indexing .htaccess file onsite for you to have some fun with. Just addreadme.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 moredetails.

    custom directory index files

    While I'm here, it's worth mentioning that .htaccess is where you can specify which files you wantto use as your indexes, that is, if a user requests /foo/, Apache will serve up /foo/index.html,

    or whatever file you specify.

    You can also specify multiple files, and Apache will look for each in order, and present the first one itfinds. 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 youimagined 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 canbe done, it can be done". Swap "Linux" for any decent operating system, the "AMP" part runs on mostof them.

    Okay, so now we have nice fancy directories, and some of them password protected, if you don'twatch out, you're site will get popular, and that means bandwidth..

    Save bandwidth with .htaccess!

    http://corz.org/public/http://corz.org/serv/resources/file_view.htaccess.txt
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    10/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 10

    If you pay for your bandwidth, this wee line could save you hard cash..

    save me hard cash! and help the internet!php_value zlib.output_compression 16386

    All it does is enables PHP's built-in transparent zlib compression. This will half your bandwidth usage inone 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 php.ini file, 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 serverin the world is configured to ignore them, by default" and that is, of course, because .ht_anything filesgenerally have server directives and passwords and stuff in them, most servers will have somethinglike this in their main configuration..

    Standard setting..Order allow,denyDeny from allSatisfy All

    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 .htprevents them being accessed. This version..

    ignore what you wantOrder allow,deny

    Deny from allSatisfy All

    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 findit convenient to put all the files starting with a dot into one, and the files with denied extensions intoanother, something like this..

    http://corz.org/devblog/2006-Q1/phpsuexec
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    11/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 1

    the whole lot# deny all .htaccess, .DS_Store $h and ._* (resource fork) filesOrder allow,denyDeny from allSatisfy All

    # deny access to all .log and .comment filesOrder allow,denyDeny from allSatisfy All

    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 toprotect from direct access. I think it's clear now why the file is called ".htaccess".

    These days, using is preferred over , mainly because you can use regularexpression 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..SetHandler application/x-httpd-php

    Any files with a *.css or *.style extension will now be handled by php, rather than simply servedup by Apache. And because you can use regexp, you could do stuff like , which is handy. Any statements you come across can be advantageouslyreplaced by statements. Good to know.

    More stuff..

    At the end of my .htaccess files, there always seems to be a section of "stuff"; miscellaneouscommands, mainly php flags and switches; so it seems logical to finish up the page with a weeselection of those..

    php flags, switches and other stuff..

  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    12/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 12

    # 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 offphp_flag log_errors onphp_value track_errors onphp_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 on/off and true/false interchangeably, aswell as 0/1, also php_value and php_flag can be switched around while things continue to work as

    expected! I guess, logically, booleans should always be php_flag, and values, php_value; butsuffice 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 thewrong type in .htaccess, say, set a php_flag using php_value, a php ini_get() command, forinstance, would return true, even though you had set the value to off, because it reads off valueas a string, which of course evaluates to not-zero, i.e. 1, or "true". If you don't rely on get_ini(),or similar, it's not a problem, though clearly it's better to get it right from the start. By the way; one othe values above is incorrectly set. Did you spot it?

  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    13/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 13

    go to part two..

    Most php settings, you can override inside your actual scripts, but I do find it handy to be able to setdefaults 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 arcanemysteries of URL rewriting.

    ;o) Cor

    Useful Links..

    Apache2 .htaccess docs.htaccess info, straight from the Horse's mouth..htaccess generatorRather neat online php .htaccess generator tool - aka. 'Dot Htaccesser', by Chris Todd.htaccess generator sourceThe 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 domainneeds.This page in BelorussianThe official Belorussian human-translation of .htaccess tricks and tips.Serbo-Croatian versionThe official Serbo-Croatian human-translation of ".htaccess tricks and tips".

    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

    http://www.catb.org/~esr/faqs/smart-questions.htmlhttp://science.webhostinggeeks.com/corz-uvodhttp://webhostingrating.com/libs/htaccess-behttp://www.namecheap.com/?aff=6311http://corz.org/public/scripts/others/http://corz.org/serv/tricks/htaccesser/index.phphttp://httpd.apache.org/docs/2.0/howto/htaccess.htmlmailto:[email protected]?subject=htaccess.phphttp://corz.org/serv/tricks/htaccess2.php
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    14/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 14

    your free tech dude. Sure, folk sometimes dropback in, but realistically, the chances of someoneelse coming along and answering your techquestion are about as close to zero as it gets;almost no one sticks around but me, the guy whowrote all that text (above).

    If you can't be bothered to read the article, I can't

    be bothered responding. Capiche? I do read allcomments, though, and answer questions about thearticle. I'm also keen to discuss anything you thinkI've missed, or interesting related concepts ingeneral.

    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 exactcode that isn't working (preferably inside [pre]

    [/pre] tags), replacing any personal domain

    names with "example.com" (advertising getsdeleted) or else..

    b) Pay me. The PayPal button is at the top right ofthe page. I offer many related services, if you needpriority assistance, get in touch.

    Other posts will be ignored and/or deleted.

    Ifyou want to know about rewriting withmod_rewrite please see the next page!

    cbparser powered comments..

    previous comments (fourteen pages) show all comments

    Bill - 16.09.11 12:23 pm

    Thanks for the crash course in .htaccess. I feel like I"velearned 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 websiteto re-write url

    http://corz.org/serv/tricks/htaccess.php?page=all#commentshttp://corz.org/serv/tricks/htaccess.php?page=1#commentshttp://corz.org/blog/inc/cbparser.phphttp://corz.org/serv/tricks/htaccess2.phphttp://corz.org/corz/hire-cor.phphttp://www.catb.org/~esr/faqs/smart-questions.html
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    15/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 15

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

    domainmonstrocity - 08.10.11 2:44 am

    I am a newbie at Web Hosting and I very much appreciatethese tips. Feel free to check out my website at the nameabove 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 htaccessfiles may take an hour to take effect. This may only applyto 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 whathtacess was until I landed here.My question is when I put deny all into one of my folders itworks. The only problem is, the files in that folder can notbe linked to my pages.

    I have a CSS folder with all my CSS inside. I also haveother folders for Javascripts and so on. I dont wantsomeone typing mysite.com/css/style.css and getting alook at my CSS or javascripts. When I place "deny all" Mypages outside the folders do not call my CSS orJavascripts.

    Can you help please?

    Thanks

    The link you want is hidden away up there in the mainarticle, in the "Control access.." section, but I'll re-post ithere 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 itstill make sense to write the following line?

    http://corz.org/serv/tricks/htaccess2.php#cooldenial
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    16/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 16

    What actually does mod_php5.c check for? Check if php5module 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 getan error then in that case is it because I am not allowed tochange the value of that php setting in the .htaccess file?

    btw Corz I love your site. Your post help me tremendouslyin understanding things so easilyKeep up the good work

    This tag creates a CONDITION, like I said above, only ifphp is loaded will the commands within it come into effect.

    If you have some wonky code that causes an error, puttingit inside a conditional tag that is true (i.e. the php5 moduleIS loaded) causes the wonky code to run, which againcauses the same error.

    The idea of using a conditional section is to prevent codefrom running in inappropriate environments, for example,trying to tell a php4 server to set php_valuedate.timezone which only became available with php5.

    And of course, none of this works if php is running as a cgirather 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, howdo you get back to the world of no answers that make anysense?

  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    17/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

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

    Surojit - 16.12.11 9:40 pm

    Hi,

    I'm looking for a way to save wrong url strings, so I couldregister 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 homepage (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 getthe 404 script to grab the URI from the incoming HTTPrequest headers, i.e.. $_SERVER['REQUEST_URI']).

    If you get stuck, take a look at my own 404 script whichdoes 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 abovemessage.

    What am I doing wrong? Thank you.

    'standard "Oops!!!" page '? ;o) Cor

    Robert Benson - 12.04.12 5:19 pm

    http://corz.org/engine?section=beta%2Fphp&source=404.php
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    18/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 18

    In my .htaccess file I want to deny access to all domainsending 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 denyaccess (to your web site) to people inside the .gov IP

    blocks? Or deny access to .gov sites from your ownnetwork? 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 frompersons sitting at Government desks using Government

    computers. These would be domains, I'm assuming, thatend in .gov .

    So is there a wild card I can use in .htaccess that in oneline will exclude all the domains ending in .gov ? This wouldbe super helpful to me, because the onesy-twosy mode isgetting tiresome!

    There is another beer in this for you.

    Thanks.

    I'm not familiar with the onesy-twosy method, though itsounds like a lot of fun!

    As for your .gov clients, YES, it is theoretically possible todeny access to folk inside those domains, you simply use:

    Deny from .gov

    HOWEVER, for this to work, you will need to have hostlookups enabled. Theoretically, again, you can achieve thisin .htaccess, like so..

    HostnameLookups On

    but in practice, that will most likely get you a 500 error. Tryit and see. HostnameLookups is somewhat wasteful ofserver resources, due to the DNS query being performedbefore each request is processed.

  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    19/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 19

    If it's your own server, you can easily enable this in yourmain httpd.conf (or equivalent). If it's a shared server,

    the admins are unlikely to enable it for the abovementioned reason.

    Failing all that, you can block the IP ranges associated withthese 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-Finances-and-Employment/Federal-Executive-Branch-Internet-Domains/k9h8-e98h

    Clearly, translating all that to an IP database would be ahuge effort, though not beyond the scope of a fairly simpleprogram.

    And if you are programming something, this would probablybe best handled with php (or similar), doing DNS calls forall inbound requests and creating a black-list of anydomains which match your criteria (.gov, etc.), somewhatlike 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, savingresources and bandwidth.

    The advantage of a php-based solution is that you don'tneed shared server admins to do anything. Just code-and-go!

    Have fun!

    ;o) Cor

    zauber - 18.10.12 12:15 pm

    can you break up a picture into dots and make it writeableso replce each dot with the original color + some text?

  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    20/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 20

    how? where do find info for such a task?how do i break up a pic into writeable dots + orignal colorso when I look at original dots, from ABOVE", i still seethe 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'sterms for we noobs but I still have a question, if you don'tmind expanding one of your tips.

    You said: "Save bandwidth with .htaccess" I have reselleraccount on Hostgator with .htaccess enabled on WordPressblog. Will this work for me? If Yes, where in .htaccess do Iplace your snippet? At the head? Tail?

    Thanks

    Wherever you like! The whole .htaccess is processedbefore 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 haveput into this and how open you are with helping others outexcellent to see that human beings can still be helpful (mylittle bit of doubt in mankind creeping in my apologies)

    I must say I will return and see what else you get up toand 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 indeedamazingly fast,

    I may drop you a line as to a little project which would use

  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    21/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 2

    your hashing program and would like your advice on itsome time, but let me get my thoughts together and thencompile 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 moreby oneself!

    Steve - 01.02.13 12:20 am

    Hi,

    I found your article during my search for information. Goodarticle. However, I do have a question why my applicationdoes not apply the rules in the .htaccess as you describedthem.

    For example:

    /app/include1

    .htaccess - deny from all

    files.../phpscripts

    .htaccess - deny from allphp file

    index.php.htaccess - Options -Indexes

    When I visit my site through localhost(localhost/app/index.php), it displays the web page createdby index.php. However when I clicked a link on the index

    page, which points to a script named test.php located inthe folder /phpscripts, I get the message that

    /phpscripts/test.php is forbidden.

    I though your article stated that files in /phpscripts wouldbe accessible through the filesystem? Am I missingsomething?

    I'm trying to restrict access to PHP files located in/phpscripts folder from

    http://informatique.edublogs.org/
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    22/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    corz.org/serv/tricks/htaccess.php 22

    visitors to my site, but be able to run them through thefilesystem.

    Any help would be appreciated.

    When you say, "points to a script named test.php locatedin 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 aset number within a set time from any single requester.(Sort of like a DOS attack.) Say a limit of 5 requests within30 seconds. How would I do this, is it even possible?

    As far as I know, you cannot do this in .htaccess. But youcan do it with anti-hammer. Note, the version on the pagehas been superceded with an as yet unavailable beta whichhas much more functionality - until I get a chance to getthat 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 mysetup, the /include1 folder contains files for PHP functionsand other useful PHP code that are 'included' and used byapplication PHP scripts.

    I want to setup the structure and .htaccess to allow theapplication PHP scripts to use the keyword 'include' to add

    PHP files from the /include1 directory but PREVENT sitevisitors from running the /include1 PHP files directly (thesefiles only make sense in the context where they areincluded)?

    Any help would be appreciated!

    It is explained here. ;o) Cor

    http://corz.org/serv/tricks/htaccess.php#section-control_and_deny_accesshttp://corz.org/serv/tools/anti-hammer/http://php.net/manual/en/function.include.php
  • 7/27/2019 .Htaccess Tricks and Tips.. Part One_ Tips, Tricks, Hints, Examples; Juicy .Htaccess Information

    23/23

    25/06/13 .htaccess tr icks and tips.. par t one: tips, tr icks, hints, examples; juicy .htaccess information.

    Chetan Sharma - 31.03.13 1:33 pm

    Thanks buddy, it really helps

    Automatic Section Links