Archive for the 'apache' Category
How to password protect a web directory
by Justin Silverton
This article will show you how to password protect a directory using the apache web server and a .htaccess file.
.htaccess file
The .htacess file should be in the directory that you would like to protect (everything below this directory will also be password protected).
AuthName “Password Protected Area”
AuthType Basic
AuthUserFile /full/path/to/.htpasswd
Require valid-user
Replace “Password protected Area” with the name of the area that you would like to protect. Also, the path needs to be changed to the path of the .htpasswd file (which will be explained further).
Generating a .htpasswd file
A program comes with apache for generating a .htpasswd file. Here is how it works:
htpasswd [ -c ] [ -m | -d | -s | -p ] passwdfile username
htpasswd -b [ -c ] [ -m | -d | -s | -p ] passwdfile username password
htpasswd -n [ -m | -d | -s | -p ] username
htpasswd -nb [ -m | -d | -s | -p ] username password
A full explanation of htpasswd can be found here
If everything is setup correctly you should see the following prompt when you try to access your newly protected directory (and the username/password combo created with htpasswd should allow access):
Using Ajax across multiple domains
By Justin Silverton
XMLHttpRequest, the main component behind AJAX, does not automatically work across multiple domains. This means that you cannot make a request to an ovject on a domain that is different from the web page’s domain. There is an easy solution to this issue: apache’s mod_rewrite module.
Example
function getXMLHttpObject()
{
if (window.XMLHTTPRequest)
return new XMLHttpRequest();
else if (window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");
else
return null;
}
function handleHTTPResponse()
{
if (http.readyState == 4) {
results = http.responseText;
}
}
var http = getXMLHttpObject();
http.open("POST"."http://www.yahoo.com/service");
http.onreadystatechange = handleHttpResponse;
The above example will fail with both Firefox and Internet Explorer (unless you are running it on a web page located on the yahoo domain). There are other ways to allow cross site ajax. Within Internet Exporer, the default security settings can be changed or a host can be added to the “trusted hosts” list. Firefox, on the other hand, has a concept called signed scripts. Both of these methods will not work for most websites on the Internet. This is because it would involve every user coming to your site adding your page to their trusted host list.
Apache setup
- Install apache with both mod_rewrite and proxy enabled.
- Create the following rule: RewriteRule ^/yahoo_proxy http://www.yahoo.com/service [P]
Note: The [P] indicates a pass-through proxy.
Replace the above line: (http.open("POST"."http://www.yahoo.com/service")) with
http.open("POST"."http://your_host/yahoo_proxy") and a connection will be made to the yahoo domains through your apache server while not violating the security restrictions of IE or Firefox.
1 commentmod_rewrite tips and tricks
By Justin Silverton
What is mod_rewrite?
Mod_rewrite is a rewriting engine (based on regular-expressions) built into the apache webserver and it is used to rewrite urls dynamically. The URL manipulations can depend on various tests, of server variables, environment variables, HTTP headers, or time stamps. Even external database lookups in various formats can be used to achieve highly granular URL matching.
How to install it
Apache by default comes with the mod_rewrite module installed but it is not enabled. So if you have Apache installed on your own server, you will need to enable it.
If you need to install apache on your system, there are many free, easy install packages available:
Xamp - http://www.apachefriends.org/en/xampp.html
apache2triad - http://apache2triad.net/
apachePHPMysql - http://apachephpmysql.narhoz.ru/
EasyWebServer - http://e.w.s.free.fr/index_fr.php
FoxServ - http://sourceforge.net/projects/foxserv/
Setting it up
Once installed, mod_rewrite basically relies on one file for all it’s functionality. It’s called .htaccess. This file should be placed in the root directory of your website.
A simple Redirect
Place the following in a .htaccess file:
RewriteEngine on
RewriteRule ^test\.html$ test2.html
RewriteEngine on should always be placed at the beginning of all your .htaccess files.
Note: If you are using a hosting provider, you may have to place the following line in your file (under rewrite_engine on): RewriteBase /
Script details:
- ^ is used before a URL. If a relative URL is used, it starts in the same directory as the .htaccess file
- $ is used for the end of a string that will be matched.
- \ is used to escape the period, periods need the \ before them if they are not going to be part of the actual rule (in this case, it is part of the filename).
This script will redirect all access from test.html to test2.html. IE: if a user goes to http://www.yoursite.com/test.html, they will be automatically forwarded to http://www.yoursite.com/test2.html
Other interesting uses
A) Blocking a specific Ip addressing from accessing your website.
RewriteCond %{REMOTE_ADDR} ^(W\.X\.Y\.Z)$
RewriteRule ^/* http://www.yoursite.com/sorry.htm [L]
Replace w.x.y.z with the IP you would like to block and http://www.yoursite.com/sorry.htm with the redirected URL.
B) Block/redirect a site that is linking to you
RewriteCond %{HTTP_REFERER} ^http://www\.blockedsite\.com [NC]
RewriteRule ^/* http://www.yoursite.com/sorry.htm [L]
Replace http://www.blockedsite.com/ with site you do not want linking to you, and http://www.yoursite.com/sorry.htm with the redirected URL.
C) preventing people from linking to your images
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yoursite\.com [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} ^http://.*$
RewriteRule \.(png |gif | bmp | jpe?g|)$ /images/stopstealing.png [L]
Replace http://www.blockedsite.com/ your site, and /images/stopstealing.png with an image path of choice.
Full Apache Docs: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
5 commentsPHP speed hacks
By Justin Silverton
A French Translation can be found here: http://www.vecteur-renaissance.com/vhoen/index.php/2006/04/15/27-10-conseils-pour-accelerer-des-scripts-php
- A PHP script will be served at least 5-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
- Enable the compression of HTML by putting in your php.ini:
output_handler = ob_gzhandler - Install a PHP caching suite. I have personally used zend (commercial), turck mmcache, and ioncube, and they all work very well.
- Switch from file based sessions to shared memory sessions. Compile PHP with the –with-mm option and set session.save_handler=mm in php.ini. This can drastically improve session management performance.
- Another caching technique that can be used when you have pages that don’t change too often is to cache the HTML output of your PHP pages. (a list of template solutions is posted within one of my previous articles).
- Use output buffering (See ob_start). This will speed up your PHP code by 5-15% if you frequently print or echo in your code.
- On Windows, FastCGI is the highest performance way of running PHP with Apache.
- In PHP4, objects and arrays should be passed to functions by reference (with &), and everything else by value. In PHP5, objects are already passed by reference.
- Don’t use images when text will do. Reduce your image sizes with a software like MacroMedia Fireworks or imagemagick.
- If possible, Run your database server on a different machine. If all static content is served from another server, then you can turn off KeepAlives in httpd.conf to speed up client disconnects.
improving php performance on apache
Apache is available on both Unix and Windows. It is the most popular web server in the world. Apache 1.3 uses a pre-forking model for web serving. When Apache starts up, it creates multiple child processes that handle HTTP requests. The initial parent process acts like a guardian angel, making sure that all the child processes are working properly and coordinating everything. As more HTTP requests come in, more child processes are spawned to process them. As the HTTP requests slow down, the parent will kill the idle child processes, freeing up resources for other processes. The beauty of this scheme is that it makes Apache extremely robust. Even if a child process crashes, the parent and the other child processes are insulated from the crashing child.
The pre-forking model is not as fast as some other possible designs, but to me that it is “much ado about nothing” on a server serving PHP scripts because other bottlenecks will kick in long before Apache performance issues become significant. The robustness and reliability of Apache is more important.
Apache 2.0 offers operation in multi-threaded mode. My benchmarks indicate there is little performance advantage in this mode. Also be warned that many PHP extensions are not compatible (e.g. GD and IMAP). Tested with Apache 2.0.47.
Apache is configured using the httpd.conf file. The following parameters are particularly important in configuring child processes:
MaxClients : default: 256
The maximum number of child processes to create. The default means that up to 256 HTTP requests can be handled concurrently. Any further connection requests are queued.
StartServers: default: 5
The number of child processes to create on startup.
MinSpareServers: default:5
The number of idle child processes that should be created. If the number of idle child processes falls to less than this number, 1 child is created initially, then 2 after another second, then 4 after another second, and so forth till 32 children are created per second.
MaxSpareServers: default:10
If more than this number of child processes are alive, then these extra processes will be terminated.
MaxRequestsPerChild: default: 0
Sets the number of HTTP requests a child can handle before terminating. Setting to 0 means never terminate. Set this to a value to between 100 to 10000 if you suspect memory leaks are occurring, or to free under-utilized resources
For large sites, values close to the following might be better:
MinSpareServers 32
MaxSpareServers 64
Apache on Windows behaves differently. Instead of using child processes, Apache uses threads. The above parameters are not used. Instead we have one parameter: ThreadsPerChild which defaults to 50. This parameter sets the number of threads that can be spawned by Apache. As there is only one child process in the Windows version, the default setting of 50 means only 50 concurrent HTTP requests can be handled. For web servers experiencing higher traffic, increase this value to between 256 to 1024.
Other useful performance parameters you can change include:
SendBufferSize: Set to OS default
Determines the size of the output buffer (in bytes) used in TCP/IP connections. This is primarily useful for congested or slow networks when packets need to be buffered; you then set this parameter close to the size of the largest file normally downloaded. One TCP/IP buffer will be created per client connection.
KeepAlive [onoff] default:On
In the original HTTP specification, every HTTP request had to establish a separate connection to the server. To reduce the overhead of frequent connects, the keep-alive header was developed. Keep-alives tells the server to reuse the same socket connection for multiple HTTP requests.
If a separate dedicated web server serves all images, you can disable this option. This technique can substantially improve resource utilization.
KeepAliveTimeout:default:15
The number of seconds to keep the socket connection alive. This time includes the generation of content by the server and acknowledgements by the client. If the client does not respond in time, it must make a new connection.
This value should be kept low as the socket will be idle for extended periods otherwise.
MaxKeepAliveRequests: default:100
Socket connections will be terminated when the number of requests set by MaxKeepAliveRequests is reached. Keep this to a high value below MaxClients or ThreadsPerChild.
TimeOut: default:300
Disconnect when idle time exceeds this value. You can set this value lower if your clients have low latencies.
LimitRequestBody: default:0
Maximum size of a PUT or POST. O means there is no limit.
If you do not require DNS lookups and you are not using the htaccess file to configure Apache settings for individual directories you can set:
# disable DNS lookups: PHP scripts only get the IP address
HostnameLookups off
# disable htaccess checks
<Directory />
AllowOverride none
</Directory>
If you are not worried about the directory security when accessing symbolic links, turn on FollowSymLinks and turn off SymLinksIfOwnerMatch to prevent additional lstat() system calls from being made:
Options FollowSymLinks
#Options SymLinksIfOwnerMatch
No comments




