Tuesday, 24 December 2013

Interesting jQuery Mobile Tutorials

Friday, 20 December 2013

http://corporate.tuenti.com/en/dev/blog/top-13-javascript-mistakes

1. Usage of for..in to iterate Arrays

Example:

var myArray = [ “a”, “b”, “c” ];
var totalElements = myArray.length;
for (var i = 0; i < totalElements; i++) {
   console.log(myArray[i]);
}
The main problem here is that the for..in statement does not guarantee the order. Effectively this means that you could obtain different results at different executions. Moreover, if someone augmented Array.prototype with some other custom functions, your loop will iterate over those functions as well as the original array items.
Solution: always use regular for loops to iterate arrays.

var myArray = [ “a”, “b”, “c” ];
for (var i=0; i<myArray.length; i++) {
    console.log(myArray[i]);
}

2. Array dimensions

Example:

var myArray = new Array(10);
There are two different problems here. First, the developer is trying to create an array already containing 10 items, and it will create an array with 10 empty slots. However, if you try to get an array item, you will get ‘undefined’ as result. In other words, the effect is the same as if you did not reserved that memory space. There is no really good reason to predefine the array length.
The second problem is that the developer is creating an array using Array constructor. This is technically correct. However it’s slower than the literal notation.
Solution: Use literal notation to initialize arrays. Do not predefine array length.

var myArray = [];

3. Undefined properties

Example:

var myObject = {
    someProperty: “value”,
    someOtherProperty: undefined
}
Undefined properties (such as someOtherProperty in the above example) will create an element in the object with key 'someOtherProperty' and value 'undefined'. If you loop through your array checking the existence of an element the following 2 statements will both return 'undefined':
typeof myObject['someOtherProperty'] // undefined typeof myObject['unknownProperty'] // undefined
Solution: if you want to explicitly declare a uninitialized properties inside an object, mark them as null

var myObject = {
    someProperty: “value”,
    someOtherProperty: null
}

4. Misuse of Closures

Example:

function(a, b, c) {
    var d = 10;
    var element = document.getElementById(‘myID’);
    element.onclick = (function(a, b, c, d) {
        return function() {
            alert (a + b + c + d);
        }
    })(a, b, c, d);
}
Here the developer is using two functions to pass the arguments a, b and c to the onclick handler. The double function is not needed only adding complexity to the code.
The variables a, b and c are already defined in the inner function because they are already declared as parameters in the main function. Any function inside the inner function will create a closure with all variables defined by main function. This includes ‘regular’ variables (like d) and arguments (like a, b and c). Thus It is not necessary to pass them again as parameters using a auto-executable function.
See JavaScript Closures FAQ for an awesome explanation about closures and contexts.
Solution: use closures to simplify your code

function (a, b, c) {
    var d = 10;
    var element = document.getElementById(‘myID’);
    element.onclick = function() {
        //a, b, and c come from the outer function arguments.
        //d come from the outer function variable declarations.
        //and all of them are in my closure
        alert (a + b + c + d);
}; }

5. Closures in loops

Example:

var elements = document.getElementByTagName(‘div’);
for (var i = 0; i<elements.length; i++) {
    elements[i].onclick = function() {
        alert(“Div number “ + i);
    }
}
In this example, we want to trigger an action (display “Div number 1”, “Div number 2”... etc) when the user clicks on the different divs on the page. However, if we have 10 divs in the page, all of them will display “Div number 10”.
The problem is that we are creating a closure with the inner function, so the code inside the function has access to variable i. The point is that i inside the function and i outside the function refers to the same variable (i.e.: the same position in memory). When our loop ends, i points to the value 10. So the value of i inside the inner function will be 10.
See JavaScript Closures FAQ for an awesome explanation about closures and contexts.
Solution: use a second function to pass the correct value.

var elements = document.getElementsByTagName(‘div’);
for (var i = 0; i<elements.length; i++) {
    elements[i].onclick = (function(idx) { //Outer function
        return function() { //Inner function
            alert(“Div number “ + idx);
        }
    })(i);
}
The outer function is a function that executes inmediatly, receiving i as a parameter. That parameter is called idx inside the outer function, thus inner function creates a closure with idx (instead of i). Therefore idx is completly different from across iterations (i.e. they point to different memory address). This example is very important to understand how closures work. Be sure to read it and play with the code in your browser until you fully understand what’s going on there.

6. Memory leaks with DOM objects

Example:

function attachEvents() {
    var element = document.getElementById(‘myID’);
    element.onclick = function() {
        alert(“Element clicked”);
    }
};
attachEvents();
This code creates a reference loop. The variable element contains a reference to the function (it is assigned to onclick properties). Also, function is keeping a reference to the DOM element (note that inside the function you have access to element because of the closure). So JavaScript garbage collector cannot clean neither element nor the function, because both are referenced by each other. Most JavaScript engines aren’t clever enough to clean circular references.
Solution: avoid those closures or undo the circular reference inside the function

function attachEvents() {
    var element = document.getElementById(‘myID’);
    element.onclick = function() {
        //Remove element, so function can be collected by GC
        delete element;
        alert(“Element clicked”);
    }
};
attachEvents();

7. Differentiate float numbers from integer numbers

Example:

var myNumber = 3.5;
var myResult = 3.5 + 1.0; //We use .0 to keep the result as float
In JavaScript, there is no difference between float and integers. Actually, every number in JavaScript is represented using double-precision 64-bits format IEEE 754. In plain words, all numbers are floats.
Solution: don’t use decimals to “convert” numbers to floats.

var myNumber = 3.5;
var myResult = 3.5 + 1; //Result is 4.5, as expected

8. Usage of with() as a shortcut

Example:

team.attackers.myWarrior = { attack: 1, speed: 3, magic: 5};
with (team.attackers.myWarrior){
    console.log ( “Your warrior power is ” + (attack * speed));
}
Before talking about with(), let’s see how JavaScript contexts works. Each function has an execution context that, put in simple words, holds all the variables that the function can access. Thus the context contain arguments and defined variables. Also a context points to a “parent” context (the context that our caller function has). For example, if functionA() calls functionB(), functionB’s context points to functionA’s context as its parent context. When accessing any variable inside a function, the engine first search in his own context. If not found, it switches to the parent context and so on until it finds the variable or it reaches the end of the context chain. Execution contexts are what makes closures work.
What with() actually does, is to insert an object into our context chain. It injects between my current context and my parent’s context. In this way, the engine first searches in the current context for the requested variable, and then it searches for it in the recently injected object, and finally in the “real” parent context. As you can see, the shortcut used in the example code above is a side effect of using context injection. However usage of with() is very slow, and thus using it for shortcuts is just insane.
Just a side note. Every book recommends not to use with(). Nevertheless all of them are focused on its usage as a shortcut. Context injection is really useful and you may find that you need to use it in advanced JavaScript. In those cases, it’s acceptable to use with() with its real meaning. Although be aware that it’s it’s still very slow from a performance perspective.
See JavaScript Closures FAQ for an awesome explanation about closures and contexts.
Solution: don’t use with() for shortcuts. Only for context injection when you really need it.

team.attackers.myWarrior = { attack: 1, speed: 3, magic: 5};
var sc = team.attackers.myWarrior;
console.log(“Your warrior power is ” + (sc.attack * sc.speed));

9. Usage of strings with setTimeout/setInterval

Example:

function log1() { console.log(document.location); }
function log2(arg) { console.log(arg); }
var myValue = “test”;
setTimeout(“log1()”, 100);
setTimeout(“log2(” + myValue + “)”, 200);
Both setTimeout() and setInterval() can accept either a function or a string as the first parameter. If you pass a string, the engine will create a new function using Function constructor. This is very slow in some browsers. Instead pass the function itself as the first argument; it’s faster, more powerful and clearer.
Solution: never use strings for setTimeout()or setInterval()

function log1() { console.log(document.location); }
function log2(arg) { console.log(arg); }
var myValue = “test”;
setTimeout(log1, 100); //Reference to a function
setTimeout(function(){ //Get arg value using closures
    log2(arg);
}, 200);

10. Usage of setInterval() for heavy functions

Example:

function domOperations() {
    //Heavy DOM operations, takes about 300ms
}
setInterval(domOperations, 200);
We can have a problem when using intervals where operation time is bigger than the interval step time. In the example we are doing a complex (i.e.: long) operation with DOM objects every 200ms. If the domOperations() function takes more than 200ms to complete, each step will overlap with the previous step and eventually some steps may get discarded. This can become a problem.
setInterval() schedules a function to be executed only if there isn’t another execution already waiting in the main execution queue. The JavaScript engine only adds the next execution to the queue if there is no another execution already in the queue. This may yield to skip executions or run two different executions without waiting 200ms between them. To make it clear, setInterval() doesn’t take in account how long it takes domOperations() to complete its job.
Solution: avoid setInterval(), use setTimeout()

function domOperations() {
    //Heavy DOM operations, takes about 300ms
//After all the job is done, set another timeout for 200 ms setTimeout(domOperations, 200); } setTimeout(domOperations, 200);
11. Misuse of ‘this’ There is no example for this common mistake as it is very difficult to build one to illustrate it. The value of this in JavaScript is very different from other languages, where the this behaviour is usually clearer. However, in JavaScript this is a bit different.
First of all, the value of this inside a function is defined when the function is called, not when it is declared. Its very important to understand this, because the value of this depends on how the function is called. In the following cases, this has a different meaning inside myFunction
* Regular function: myFunction(‘arg1’);
this points to the global object, wich is window for all browers.
* Method: someObject.myFunction(‘arg1’);
this points to object before the dot, someObject in this case.
* Constructor: var something = new myFunction(‘arg1’);
this points to an empty Object.
* Using call()/apply(): myFunction.call(someObject, ‘arg1’);
this points to the object passed as first argument.
In this way you can have the same function (myFunction in the example above), that internally use this. However, the value of this is not related to the function declaration itself, only to the way that function is called.

12. Usage of eval() to access dynamic properties

Example:

var myObject = { p1: 1, p2: 2, p3: 3};
var i = 2;
var myResult = eval(‘myObject.p’+i);
The main problem lies in that starting a new execution context with eval() is extremely slow. The same can be achieved using square bracket notation instead of dot notation.
Solution: use square bracket notation instead of eval()

var myObject = { p1: 1, p2: 2, p3: 3};
var i = 2;
var myResult = myObject[“p”+i];

13. Usage of undefined as a variable

Example:

if ( myVar === undefined ) {
    //Do something
}
This check usually works, but it does by pure chance. In the code above undefined is effectively a variable. All JavaScript engines will create the variable window.undefined initialized to undefined as its value. However note that variables isn’t read-only, and any other code can change its value. It’s very weird to find a scenario where window.undefined has a value different from undefined. (nobody will never actually do undefined = 10;). But why take the risk? It is better to use typeof checks.
Solution: use typeof when checking for undefined.

if ( typeof myVar === “undefined” ) {
    //Do something

Tuesday, 19 November 2013

Avoiding timezone nightmares in PHP and MySQL

Avoiding timezone nightmares in PHP and MySQL »

FERDY CHRISTANT - APR 19, 2010 (07:08:48 PM)

I am a developer that finds things like date handling, character encodings and such to be a pain. Like many developers, I pretend the problem does not exist and just hope that things turn out well. This is an attitude that I can no longer afford in this global village, which is why I'm getting to the bottom of things like this. An example is one of my earlier articles, where I had to take a deep dive into Unicode:
Although time zones and daylight savings time are entirely unrelated, they are similar, undesirable problems that you cannot hide from. In this little article I will tell you how I deal with timezones and DST in a PHP/MySQL context. The key of this article is in avoiding timezone issues in your date handling.
Introduction
There are three aspects to date/time handling where timezones can be relevant:
  • Storing date/times
  • Calculating with date/times
  • Displaying date/times
Storing date times
The key to storing date times is to explicitly set the timezone or to set it to a neutral timezone. You should never just take any date and insert it into a database without explicitly converting it to a specific timezone. In most cases, you are best of storing it in a neutral format, meaning the GMT timezone. The GMT timezone is also used by the UTC standard. This little PHP snippet converts the current date/time into GMT:
 $timestamp gmdate("Y-m-d H:i:s"time()); 
Next, one can insert this into MySQL without change if your table column is of type "timestamp". Note that in the example above, time() will give back the time using the timezone configured at the host. In my case it is on GMT+2. This means that if you actually look in the MySQL table, all dates will be 2 hours off. This is correct behavior, since we are storing the timestamp in the GMT timezone. The great thing here is that it does not matter in which timezone your host is.
(note: It is recommended though to set both your web host and MySQL to the same timezone explicitly)
Calculating with date times
Once we have stored timestamps in a neutral timezone, doing calculations on them is fairly easy. The thing to remember here is that if you are doing timestamp comparisons, your input timestamp first has to be converted to GMT too. This is best illustrated with an example:
SELECT COUNT(id) FROM c WHERE date_created > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 1 HOUR)
The line of SQL above returns the amount of comments that were made in the last hour. The date_created column contains the timezone neutral timestamp. Since we are calculating a date offset, our input parameter (the current timestamp) first has to be converted to GMT/UTC. That's all we need to do, because date offsets are not time zone dependent in any other way. What happens one hour ago in one part of the world happened one hour ago in any other part of the world.
Displaying date times
When it comes to displaying date/times that are sensitive to a user's timezone, it takes a conversion from the neutral timestamp to a timestamp that is optimized to the user's timezone. You can do this straight from MySQL using theConvert_TZ function.
That's only part of the story though. You will need a reliable way to detect the current user's timezone or let them set it theirselves. Next, you need a way to convert the user-friendly list of timezones to the one used in MySQL or PHP. Finally, you can then display a date/time for the user's timezone.
Luckily, in some projects you may be able to escape this mess. If your customer accepts a date format like this:
"3 days ago"
Instead of
"April 16, 2010"
...then the whole problem of displaying timezone specific dates goes away. In that case, you can use the technique used in this article.
Closing
This mini article was just me thinking out loud and structuring my thoughts around this topic. Still, I hope it helps someone else. Please do rate and comment below

Sunday, 17 November 2013

timezone issues

Summary of answers and other data: (please add yours)

Do:
  • Whenever you are referring to a particular moment in time, persist the time according to a unified standard that is not affected by daylight savings. GMT and UTC have been mentioned by different people, though UTC seems to be mentioned most often.
  • ?? Include the local time offset as is (including DST offset) when storing timestamps. ?? Store timestamps as UTC or epochs(number of seconds since 1970) without time zone or offset.
  • Include the original time zone name, so you can reconstruct the original time at a later point and display correct offsets if needed.
  • Remember that DST offsets are not always an integer number of hours (for example, Indian Standard Time is UTC+05:30).
  • If using Java, use Joda Time.
  • If using .NETconsider using Noda Time.
  • If using Perl, use DateTime.
  • If using Python, use pytz
  • If using PHP > 5.2, use the native time zones conversions provided by DateTime, and DateTimeZone classes. To keep PHP with up to date Olson data install periodically this PECL package. See answer
  • Create a table TZOffsets with three columns: RegionClassId, StartDateTime, and OffsetMinutes (int, in minutes). See answer
  • Business rules should always work on civil time (UTC/GMT).
  • Internally, keep timestamps in something like civil-time-seconds-from-epoch. See answer.
  • Only convert to local times at the last possible moment.
  • Remember that time zones and offsets are not fixed and may change. For instance, historically US and UK used the same dates to 'spring forward' and 'fall back'. However, in the mid 2000s the US changed the dates that the clocks get changed on. This now means that for 48 weeks of the year the difference between London time and New York time is 5 hours and for 4 weeks (3 in the spring, 1 in the autumn) it is 4 hours. Be aware of items like this in any calculations that involve multiple zones.
  • Consider the type of time (actual event time, broadcast time, relative time, historical time, recurring time) what elements (timestamp, time zone offset and time zone name) you need to store for correct retrieval - see "Types of Time" in answer.
  • Check if your DBMS needs to be shutdown during transition.
  • Keep your OS, database and application tzdata files in sync, between themselves and the rest of the world.
  • On Servers, set hardware clocks and OS clocks to UTC.
  • Use NTP services on all servers.
  • If doing historical auditing store both UTC and local time (this allows exact pinpointing of time, as conversion tables will change).
  • If using FAT32, remember that timestamps are stored in local time, not UTC.
  • When dealing with recurring events (weekly TV show, for example), remember that the time changes with DST and will be different across time zones.
Don't:
  • Do not use JavaScript date and time calculations in web applications unless you ABSOLUTELY have to.
  • Never trust client datetime. It may very well be incorrect.
  • Do not compare client datetimes with server datetimes.
Testing:
  • When testing make sure you test countries in the Western and Eastern hemispheres, with both DST in progress and not and a country that does not use DST (6 in total).
  • Test all third-party libraries and applications and make sure they handle time zone data correctly.
Reference:
Other:
  • Lobby your representative to end the abomination that is DST. We can always hope...
  • Lobby for EST

Monday, 21 October 2013

Webcam and Annotation With HTML5

Nowadays, Webcam is widely used for both personal and business. It is simple, cheap, and yet powerful for image acquisition.
Some developers prefer to create their own webcam libraries. In this case, you need to learn technologies like TWAIN,WIA and/or DirectShow.
Note: the WIA and DirectShow APIs are recommended to develop a webcam SDK. TWAIN, however, is a good option for scanners.
However, due to the complexity of learning the APIs, as well as the technologies such as COM interfaces, it’s not an easy task for developers to create and embed Webcam SDK into their web applications. There are two options to simplify the whole process:
  • Use a third-party plug-in/add-on to access and control the webcams, such as Flash, Silverlight, etc.
  • Adopt the new technology – HTML5.
I will talk more about the second option in this article.
Webcam devices will be supported by the new video element and the getUserMedia API in HTML5. This means we can capture video streams and images from Webcam devices with just a few lines of JavaScript and HTML code, and the end users do not need to install anything for the browsers.

Information you need to know:

  • HTML5 is not released yet. So this article is for early experimentations and it is not recommended to use the code snippet in the article for actual implementations.
  • Currently only the following browsers support getUserMedia and WebGL:
    • Google Chrome (Version 21 and above) – Recommended for testing.
    • Firefox (Nightly Build, version 17 and above)
    • Opera (Version 12 and above, need to enable WebGL in opera:config)

Access the Webcam

Thanks to Wes Bos. He posted a wonderful article on how to access the Webcam. If you are new to HTML5, I suggest you read this article first (you can skip the content for ccv and scripts.js).
Basically, there are two steps:
1. Getting the Webcam stream
We use the getUserMedia API to get the stream.
navigator.getUserMedia_ = navigator.getUserMedia || navigator.webkitGetUserMedia || 
  navigator.mozGetUserMedia || navigator.msGetUserMedia;
//Get the API according to the browser.
navigator.getUserMedia_({ video: true, audio: false }, success, error);
Unfortunately, different browsers have different names for the getUserMedia API. So we have to check and pick the correct one in the first step.
When we call the API, video:true indicates that we want video access and audio:false indicates that we don’t want audio. Error function will be called when the stream is not accessible.
Success is the function to receive the stream:
function success(stream) {
	var domURL = window.URL || window.webkitURL;
	//start streaming via the video element
	document.getElementById(‘myVideo’).src =
	domURL ? domURL.createObjectURL(stream) : stream;
}
When you access the page, the browser will ask for the permission to use your webcam. If you click Deny, the web application cannot access the Webcam and it will trigger the error function.
2. Output to canvas
We have the video stream for the Webcam and now we can output the images to canvas element.
var video = document.getElementById(‘myVideo’);
var canvas = document.getElementById(‘myCanvas’);
var ctx = canvas.getContext(’2d’);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
In the above code, we only capture an image from the video and draw on the canvas. So the question will be: how can we output the video? Well, you can set an interval and draw the image every few milliseconds, or, you can use therequestAnimationFrame API to perform an animation from the browser level. (You will find the sample in the attached source code).

Annotation

Annotation is always important for image processing. We can use it to mark or highlight some important information, add some notes, hide certain area, etc… If you have checked the face detection demo from Wes Bos, you will find it also useful for entertainment.
Since we have the canvas object, we can actually use the context of the canvas object to draw lines, arc, text or image on the canvas. It is pretty much just a simple annotation design (we won’t discuss the advanced annotation functions in this article).
You can find all the information from canvas and canvas 2D context.
For example, let’s draw a text on the video:
var canvas = document.getElementById(‘myCanvas’);
var ctx = canvas.getContext(’2d’);
ctx.font = “10px sans-serif”;
ctx.strokeText(“Hello World”, 0, 0); //output the text to (0,0)
Note: this code should be added into the repaint loop. Otherwise the text will be lost in the next repaint operation.
You can find a complete annotation sample in the source code .

Capture and save image from Webcam

Canvas object offers a method to save the current display to an image element. This allows us to capture and save both the image and the annotations.
var img = canvas.toDataURL(“image/png”);
window.open(img, “_blank”);
You can open a new window to display and save the captured image, or you can use the img element to hold the image.

A complete sample for Webcam and annotation with HTML5

Please test the web page as a web application (place the page in IIS/Apache/Tomcat/etc… and access the page via HTTP address). If you just double click the HTML file and run it from local file system, the browser will not be able to access the webcam resources.
Google Chrome Version 21 and above is recommended for the testing.

Conclusion

HTML5 provides a simple way for developers to create a webcam SDK. As you can see from the sample, we can easily enable our applications to interact with the webcams. However, this method also brings up some questions:
  1. Compatibility with the browsers.
  2. Security (since the app will access device directly)
Please let me know if you have the same concerns. Any comments are welcome.

Sunday, 20 October 2013

20 ways to Secure your Apache Configuration


20 ways to Secure your Apache Configuration

webHere are 20 things you can do to make your apache configuration more secure.
Disclaimer: The thing about security is that there are no guarantees or absolutes. These suggestions should make your server a bit tighter, but don't think your server is necessarily secure after following these suggestions.
Additionally some of these suggestions may decrease performance, or cause problems due to your environment. It is up to you to determine if any of the changes I suggest are not compatible with your requirements. In other words proceed at your own risk.

First, make sure you've installed latest security patches

There is no sense in putting locks on the windows, if your door is wide open. As such, if you're not patched up there isn't really much point in continuing any longer on this list. Go ahead and bookmark this page so you can come back later, and patch your server.

Hide the Apache Version number, and other sensitive information.

By default many Apache installations tell the world what version of Apache you're running, what operating system/version you're running, and even what Apache Modules are installed on the server. Attackers can use this information to their advantage when performing an attack. It also sends the message that you have left most defaults alone.
There are two directives that you need to add, or edit in your httpd.conf file:
ServerSignature Off
ServerTokens Prod

The ServerSignature appears on the bottom of pages generated by apache such as 404 pages, directory listings, etc.
The ServerTokens directive is used to determine what Apache will put in the Server HTTP response header. By setting it to Prod it sets the HTTP response header as follows:
Server: Apache
If you're super paranoid you could change this to something other than "Apache" by editing the source code, or by using mod_security (see below).

Make sure apache is running under its own user account and group

Several apache installations have it run as the user nobody. So suppose both Apache, and your mail server were running as nobodyan attack through Apache may allow the mail server to also be compromised, and vise versa.
User apache
Group apache

Ensure that files outside the web root are not served

We don't want apache to be able to access any files out side of its web root. So assuming all your web sites are placed under one directory (we will call this /web), you would set it up as follows:
<Directory />
  Order Deny,Allow
  Deny from all
  Options None
  AllowOverride None
</Directory>
<Directory /web>
  Order Allow,Deny
  Allow from all
</Directory>
Note that because we set Options None and AllowOverride None this will turn off all options and overrides for the server. You now have to add them explicitly for each directory that requires an Option or Override.

Turn off directory browsing

You can do this with an Options directive inside a Directory tag. Set Options to either None or -Indexes
Options -Indexes

Turn off server side includes

This is also done with the Options directive inside a Directory tag. Set Options to either None or -Includes
Options -Includes

Turn off CGI execution

If you're not using CGI turn it off with the Options directive inside a Directory tag. Set Options to either None or -ExecCGI
Options -ExecCGI

Don't allow apache to follow symbolic links

This can again can be done using the Options directive inside a Directory tag. Set Options to either None or -FollowSymLinks
Options -FollowSymLinks

Turning off multiple Options

If you want to turn off all Options simply use:
Options None
If you only want to turn off some separate each option with a space in your Options directive:
Options -ExecCGI -FollowSymLinks -Indexes

Turn off support for .htaccess files

This is done in a Directory tag but with the AllowOverride directive. Set it to None.
AllowOverride None
If you require Overrides ensure that they cannot be downloaded, and/or change the name to something other than .htaccess. For example we could change it to .httpdoverride, and block all files that start with .ht from being downloaded as follows:
AccessFileName .httpdoverride
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy All
</Files>

Run mod_security

mod_security is a super handy Apache module written by Ivan Ristic, the author of Apache Security from O'Reilly press.
You can do the following with mod_security:
  • Simple filtering
  • Regular Expression based filtering
  • URL Encoding Validation
  • Unicode Encoding Validation
  • Auditing
  • Null byte attack prevention
  • Upload memory limits
  • Server identity masking
  • Built in Chroot support
  • And more

Disable any unnecessary modules

Apache typically comes with several modules installed. Go through the apache module documentation and learn what each module you have enabled actually does. Many times you will find that you don't need to have the said module enabled.
Look for lines in your httpd.conf that contain LoadModule. To disable the module you can typically just add a # at the beginning of the line. To search for modules run:
grep LoadModule httpd.conf
Here are some modules that are typically enabled but often not needed: mod_imapmod_includemod_infomod_userdir,mod_statusmod_cgimod_autoindex.

Make sure only root has read access to apache's config and binaries

This can be done assuming your apache installation is located at /usr/local/apache as follows:
chown -R root:root /usr/local/apache
chmod -R o-rwx /usr/local/apache

Lower the Timeout value

By default the Timeout directive is set to 300 seconds. You can decrease help mitigate the potential effects of a denial of service attack.
Timeout 45

Limiting large requests

Apache has several directives that allow you to limit the size of a request, this can also be useful for mitigating the effects of a denial of service attack.
A good place to start is the LimitRequestBody directive. This directive is set to unlimited by default. If you are allowing file uploads of no larger than 1MB, you could set this setting to something like:
LimitRequestBody 1048576
If you're not allowing file uploads you can set it even smaller.
Some other directives to look at are LimitRequestFieldsLimitRequestFieldSize and LimitRequestLine. These directives are set to a reasonable defaults for most servers, but you may want to tweak them to best fit your needs. See the documentation for more info.

Limiting the size of an XML Body

If you're running mod_dav (typically used with subversion) then you may want to limit the max size of an XML request body. TheLimitXMLRequestBody directive is only available on Apache 2, and its default value is 1 million bytes (approx 1mb). Many tutorials will have you set this value to 0 which means files of any size may be uploaded, which may be necessary if you're using WebDAV to upload large files, but if you're simply using it for source control, you can probably get away with setting an upper bound, such as 10mb:
LimitXMLRequestBody 10485760

Limiting Concurrency

Apache has several configuration settings that can be used to adjust handling of concurrent requests. The MaxClients is the maximum number of child processes that will be created to serve requests. This may be set too high if your server doesn't have enough memory to handle a large number of concurrent requests.
Other directives such as MaxSpareServersMaxRequestsPerChild, and on Apache2 ThreadsPerChildServerLimit, andMaxSpareThreads are important to adjust to match your operating system, and hardware.

Restricting Access by IP

If you have a resource that should only by accessed by a certain network, or IP address you can enforce this in your apache configuration. For instance if you want to restrict access to your intranet to allow only the 176.16 network:

Order Deny,Allow
Deny from all
Allow from 176.16.0.0/16

Or by IP:
Order Deny,Allow
Deny from all
Allow from 127.0.0.1

Adjusting KeepAlive settings

According to the Apache documentation using HTTP Keep Alive's can improve client performance by as much as 50%, so be careful before changing these settings, you will be trading performance for a slight denial of service mitigation.
KeepAlive's are turned on by default and you should leave them on, but you may consider changing the MaxKeepAliveRequestswhich defaults to 100, and the KeepAliveTimeout which defaults to 15. Analyze your log files to determine the appropriate values.

Run Apache in a Chroot environment

chroot allows you to run a program in its own isolated jail. This prevents a break in on one service from being able to effect anything else on the server.
It can be fairly tricky to set this up using chroot due to library dependencies. I mentioned above that the mod_security module has built in chroot support. It makes the process as simple as adding a mod_security directive to your configuration:
SecChrootDir /chroot/apache
There are however some caveats however, so check out the docs for more info.

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...