Jump to content
xisto Community
Sign in to follow this  
Quatrux

.htaccess Files Usage tips and examples

Recommended Posts

In this tutorial you will find a simple way to use .htaccess files on your webspace, .htaccess is an ascii file, so you will need to upload it in ascii mode and make sure that the file permissions is 644 and it could be read by the server, make sure it has no extension, like some editors just saves it as htaccess.txt or .php so please remove it, the dot in front does not show an extension, it is a hidden file.

be careful using the .htaccess some servers does not let to use them, because of the performance, place the file into your domain root or subdomain root directory, usually in public_html folder.

# Enable this if the httpd.conf does not have it by default# Usually the apache is configured as it needs to#<Files .htaccess>#order allow,deny#deny from all#</Files># Using php_flag or php_value you can change your# server php.ini and httpd.conf/apache.conf settings# Turn off asp tags# Turn off register globals# Turn off magic_quotes_gpc # Turn off magic_quotes_runtime# Turn off expose_php# Turn off serversignature# Turn off servertokens# Set upload_max_filesize to 8M# Set default User Agentphp_flag asp_tags offphp_flag register_globals offphp_flag magic_quotes_gpc offphp_flag magic_quotes_runtime offphp_flag expose_php offphp_flag serversignature offphp_flag servertokens minimalphp_value upload_max_filesize 8Mphp_value user_agent "Opera/8.51 (Windows NT 5.1; U; en)"# so off can be changed to on and etc. also 0 and 1# I don't really know serious difference between php_flag and php_value# but I think that using php_flag the user_agent could not be changed and etc.# Add new Extension# You can add a lot of extensions if needed# Examples, you can make .html to be parsed as phpAddType application/x-httpd-php .myextensionAddType application/x-httpd-php .htmlAddType image/gif .sgif# Set Default Index files# Apache will be looking for this files when accessing http://www.domain.com/# Example, you can make anything, but try to avoid# writing a lot for better performanceDirectoryIndex portal.html index.html index.php default.html main.php# When no index file is found, apache shows the tree# you can tell what to not show in the directory listing# This will not show anythingIndexIgnore *#This will not show gif and png images, but will list everything elseIndexIgnore *.gif *.png[QUOTE]#If you really want to be tricky, using the +Indexes option, you can include a#default description for the directory listing that is displayed when you use it by#placing a file called HEADER in the same directory. The contents of this file will be#printed out before the list of directory contents is listed. You can also specify a#footer, though it is called README, by placing it in the same directory as the#HEADER. The README file is printed out after the directory listing is printed.[/QUOTE]# Redirecting using .htaccess is really simpleRedirect /olddir/oldfile.html http://example.com/newdir/newfile.html# Error Handling# This is the fun part, making your own custom errors# ExamplesErrorDocument 404 /errors/404.htmlErrorDocument 404 /errors/404.phpErrorDocument 404 /file.php?error=404ErrorDocument 404 "The Page could not be found on the Server"# Here is what I use, bellow you will find the php files neededErrorDocument 400 /errors/file.php?error=400ErrorDocument 401 /errors/file.php?error=401ErrorDocument 402 /errors/file.php?error=402ErrorDocument 403 /errors/file.php?error=403ErrorDocument 404 /errors/file.php?error=404ErrorDocument 405 /errors/file.php?error=405ErrorDocument 406 /errors/file.php?error=406ErrorDocument 407 /errors/file.php?error=407ErrorDocument 408 /errors/file.php?error=408ErrorDocument 409 /errors/file.php?error=409ErrorDocument 410 /errors/file.php?error=410ErrorDocument 411 /errors/file.php?error=411ErrorDocument 412 /errors/file.php?error=412ErrorDocument 413 /errors/file.php?error=413ErrorDocument 414 /errors/file.php?error=414ErrorDocument 415 /errors/file.php?error=415ErrorDocument 416 /errors/file.php?error=416ErrorDocument 417 /errors/file.php?error=417ErrorDocument 500 /errors/file.php?error=500ErrorDocument 501 /errors/file.php?error=501ErrorDocument 502 /errors/file.php?error=502ErrorDocument 503 /errors/file.php?error=503ErrorDocument 504 /errors/file.php?error=504ErrorDocument 505 /errors/file.php?error=505# Bocking Users by IP address (I do not use this method)# I prefer to use PHP to ban# This is useful though if some bot is taking your bandwidth..Order Allow,DenyDeny from 10.0.0.1Deny from 192.168.Allow from all

You also can block users or sites by referrer, or prevent hot linking of your media.. I never done that so..

By the way, better use the password protection from your cpanel :huh: but just make sure it does not overwrite anything.

And if you can please avoid using .htaccess file for better performance, it does not get that slow, due to the new servers are fast these days, but still use them if you really need to, not for fun or that it is cool :)

Here is the php file with which you can have your own custom errors with the right headers.

# the file errors/file.php look above.<?php/*+===========================================+| Error Page File for Q-Zone by Quatrax                                          |+===========================================+*//* Check Input */$code = isset($_GET['error']) ? $_GET['error'] : '404';/* Parse Error */error_page($code);exit;function error_page($code = '404') {	/* Client Error 4xx */	$e['400'] = array('400 Bad Request', 'The request could not be understood by the server due to malformed syntax. The client should not repeat the request without modifications.');	$e['401'] = array('401 Unauthorized', 'The request requires user authentication. The client may repeat the request with a suitable Authorization. If the request already included Authorization credentials, then the this response indicates that authorization has been refused.');	$e['402'] = array('402 Payment Required', 'This code is reserved for future use.');	$e['403'] = array('403 Forbidden', 'The server understood the request, but is refusing to fulfill it. Authorization will not help and the request should not be repeated.');	$e['404'] = array('404 Not Found', 'The server has not found anything matching the requested url "'.$_SERVER['REQUEST_URI'].'" and no indication is given of whether the condition is temporary or permanent.');	$e['405'] = array('405 Method Not Allowed', 'The method specified in the Request-Line is not allowed for the resource identified by the requested url "'.$_SERVER['REQUEST_URI'].'" and the response must include an Allow header containing a list of valid methods for the requested resource.');	$e['406'] = array('406 Not Acceptable', 'The server has found a resource matching the requested url "'.$_SERVER['REQUEST_URI'].'" but not one that satisfies the conditions identified by the Accept and Accept-Encoding request headers.');	$e['407'] = array('407 Proxy Authentication Required', 'The client must first authenticate itself with the proxy. The proxy must return a Proxy-Authenticate header field containing a challenge applicable to the proxy for the requested resource. The client may repeat the request with a suitable Proxy-Authorization header field.');	$e['408'] = array('408 Request Timeout', 'The client did not produce a request within the time that the server was prepared to wait. The client may repeat the request without modifications at any later time.');	$e['409'] = array('409 Conflict', 'The request could not be completed due to a conflict with the current state of the resource.');	$e['410'] = array('410 Gone', 'The requested resource is no longer available at the server and no forwarding address is known. This condition is considered permanent. Clients with link editing capabilities delete references to the requested url "'.$_SERVER['REQUEST_URI'].'" after user approval.');	$e['411'] = array('411 Length Required', 'The server refuses to accept the request without a defined Content-Length. The client may repeat the request if it adds a valid Content-Length header field containing the length of the entity body in the request message.');	$e['412'] = array('412 Unless True', 'The condition given in the Unless request-header field evaluated to true when it was tested on the server');	$e['413'] = array('413 Request Entity Too Large', 'The requested document is bigger than the server wants to handle now. If the server thinks it can handle it later, it should include a Retry-After header.');	$e['414'] = array('414 Request URI Too Long', 'The URI is too long.');	$e['415'] = array('415 Unsupported Media Type', 'Request is in an unknown format.');	$e['416'] = array('416 Requested Range Not Satisfiable', 'Client included an unsatisfiable Range header in request.');	$e['417'] = array('417 Expectation Failed', 'Value in the Expect request header could not be met.');	/* Server Error 5xx */	$e['500'] = array('500 Internal Server Error', 'The server encountered an unexpected condition which prevented it from fulfilling the request.');	$e['501'] = array('501 Not Implemented', 'The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.');	$e['502'] = array('502 Bad Gateway', 'The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.');	$e['503'] = array('503 Service Unavailable', 'The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay.');	$e['504'] = array('504 Gateway Timeout', 'The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server it accessed in attempting to complete the request.');	$e['505'] = array('505 HTTP Version Not Supported', 'The server, while acting as a gateway or proxy, does not support version of HTTP indicated in request line.');	/* Check, default is 404 Not Found */   $e[$code] = isset($e[$code]) ? $e[$code] : $e['404'];	/*  Remove the output buffer and turn off output buffering */	ob_get_clean(); set_time_limit(0);	/* Create Output */	$output = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML><HEAD><META NAME="ROBOTS" CONTENT="NOINDEX, FOLLOW, NOARCHIVE"><META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; CHARSET=ISO-8859-1"><META HTTP-EQUIV="CONTENT-STYLE-TYPE" CONTENT="text/css"><META NAME="DESCRIPTION" CONTENT="'.$e[$code][0].'"><TITLE>'.$e[$code][0].'</TITLE><STYLE>body {	padding: 6px 24px 6px 14px;	font-family: Verdana, sans-serif;}a {	text-decoration: none;}a:hover {	text-decoration: underline;}p {	font-size: 15px;}h1 {	font-size: 32px;}small {	font-size: 11px;}address {	font-size: 13px;}hr {	border-style: dashed;	border-width: 2px 4px;	border-color: #8f8f8f;	margin-left: 0;	text-align: left;	width: 60%;}</STYLE></HEAD><BODY><H1>'.substr($e[$code][0], 4, strlen($e[$code][0])).'</H1>  '.wordwrap($e[$code][1], 64, "<BR>\n").'<P>Go back » <A HREF="http://'.str_replace('http://', '', $_SERVER['SERVER_NAME']).'">My Site</A> the Main Web Site</P><P><A HREF="http://validator.w3.org"><SMALL>Valid HTML 3.2</SMALL></A><HR>'.$_SERVER['SERVER_SIGNATURE'].'</BODY></HTML>';	/* Send the Headers */	if (!headers_sent()) {  header("Content-Encoding: none");  header("Cache-Control: no-store, no-cache");  header("Cache-Control: post-check=0, pre-check=0");  header("Pragma: no-cache");  header("HTTP/1.1 ".$e[$code][0]);  header("Status: ".substr($e[$code][0], 0, 3));  header("Content-type: text/html");  header("Content-Length: ".strlen($output));	}	/* Display Error */	echo $output;	return TRUE;}?>

If You know php and html you can change the things you want

Best Regards,
Quatrux.
Edited by szupie (see edit history)

Share this post


Link to post
Share on other sites

This is something very helpful for webmasters, that want to change their server configuration but don't know how. It is a textfile that you load up to your web server to give it instructions on changing the configuration, but he actually explained that.Posts like yours (that don't contribute anything to the topic) are considered spam.I think that this is a great tutorial, thanks a lot for it. It would be of great help though, if you could mention your sources so that one can search for advanced knowledge of the topic.Did you write this by yourself? Because then I think you deserve more credits than you got because so much "real" information is included as comment in the code.

Share this post


Link to post
Share on other sites

I wrote this myself, I had been using .htaccess for a long time for personal things, but when I gathered up my info to know this, I just browsed google for maybe ".httaccess tutorial" and browsed some links and used what was useful :huh: but the error code explanaitions in the php $e array - I just copied and pasted the text and edited it a bit.

 

by the way, I think that:

 

php_flag serversignature off

php_flag servertokens minimal

 

does not work, I am not sure because it is httpd.conf settings..

Share this post


Link to post
Share on other sites

Recommendation to all of you

Always include a new line at the end of your .htaccess document.

It is not important until you change something in Cpanel.

I had a very hard time, trying to figure out why I got an internal server error (was to stupid to read the error log, but anyway), but in the end I figured out, that it happened because I changed some Handlers in the Cpanel, which led to the last line of my .htaccess looking like this:

magic_quotes_runtime offAddHandler php php4
or something like that..

It took me ages to figure out what was wrong, because I didn't remember screwing anything up. So be careful regarding this behaviour.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.