Posts Tagged ‘Code’

An Event Apart: CSS Best Practices

December 25, 2011 - 3:00 pm No Comments

Summary: This is a very interesting article that estate the use of the CSS and how important it is and necessary to take care when writing CSS code for the next designer/developer. Enjoy!

 

Article: In her Our Best Practices Are Killing Us presentation at An Event Apart in Minneapolis MN, Nicole Sullivan walked through common CSS best practices that have outlived their usefulness and what we can do instead to improve CSS performance and maintenance long term. Here’s my notes from her talk:

 

Problems with CSS

 

  • Performance is an important part of the Web experience, with poor performance people engage less, use the site less, etc. CSS on many sites is responsible for poor performance.
  • Facebook had 706 CSS files, they declared the Facebook blue color 261 times, used 548 unique hex values for colors, had 6498 declarations of color. Salesforce.com had 3,669 padding declarations.
  • You can use GREP, regular expressions to analyze CSS files to find matches like this.
  • Looking at the Alexa top 1,000 sites revealed some interesting data. One site had 518 declarations of !important. One had 733 declared float elements. One had 889 font-size declarations. All this makes it hard for a new or existing developer to work with the CSS code. This is a Web-wide problem.
  • Even though we think each project will be “different”, our existing best practices mean these problems keep coming up.
  • It’s time to rethink our best practices and do things differently. CSS will allow us to do anything no matter how stupid. But just because we can doesn’t mean we should.

 

Pixel Based Sites

 

  • Myth: pixel based sites are bad. Why did we stop using pixels for layout? Internet Explorer 6 wouldn’t allow fonts to be resized when specced in pixels. As a result, we had to use percentages and ems.
  • Today browsers use page zoom and resize everything (pixels, ems, and percentages) on the page (IE 7+). So fonts declared in pixels can be resized.
  • Nested percentages and ems are not predictable.
  • Pixel based fonts can be resized on all modern browsers with page zoom. Check how many users are still on IE6.
  • If you must use percentages/ems, only change font-size on the body and leaf nodes, nowhere in between.

 

Extra Markup

 

  • Myth: don’t add any extra mark-up.
  • A predictable box structure allows you to debug more easily. A module body plays an important role: Trapping margin collapse, Trapping floats, Creating a new formatting context.
  • When you cross lines between elements solving different problems you have problems.
  • Separation of concerns: process of separating a computer program into distinct features that overlap in functionality as little as possible.
  • Solve one problem at a time (isolate into mark-up) but add mark-up judiciously. Don’t go nuts with extra HTML but know that bugs can come up when you try to have modules do too much.

 

Semantic Markup

 

  • Myth: more semantic the better.
  • Class names and IDs are not read by search engines, accessibility devices, or users (except other developers). So let’s make sure that our class names & IDs work for other developers.
  • Very semantic class names can prevent re-use. More semantic is not always better.
  • CSS can be too tightly coupled to content. Repeatable patterns are likely better for CSS maintenance and performance. DRY: don’t repeat yourself.
  • Find common elements and presentation, and abstract them out into separate code. Look at what things are known and common amongst a set of modules and what differs.
  • A new formatting context says “I’m a box, nothing comes out of me.” This is very useful for managing floats and varying content.
  • Facebook reduced file size by finding a common abstraction for all the items in their news feed: cut average CSS bytes per page by 19% (after gzip) and HTML bytes per page by 44% (before gzip).
  • This is great for performance but the savings in work and maintenance can be more important. Repetition, Duplication, and Legacy Code make it really hard to work on Web sites. It can snowball out of control.
  • Find a middle ground with abstracted styles and semantic enhancements where they are applicable.
  • Choose good semantic elements: headings, lists, paragraphs
  • The CSS shouldn’t be tightly coupled with the display or with the content.

 

Classitis

 

  • Myth: Some people believe IDs are better than classes but they can be overly specific but specificity is much more dangerous for duplication than extra classes.
  • Specificity can be limiting for re-use. When we use descendent selectors, specificity can get complex quickly. Specificity grows over time and it becomes difficult to know which rules will take precedence.
  • The order of classes does not guarantee which one will be applied first. The last property value pair in a CSS declaration is the one that applies. The order of style sheets also matters. The last style sheet wins.
  • CSS inheritance: properties are inherited by child elements. For example, paragraphs inherit the font-size of the body.
  • IDs win over classes. Inline styles win over external style sheets. !important wins even over inline styles.
  • A hostile work environment can develop when it’s too difficult to tell which styles will take precedence. The only way you can code is with Firebug and eventually it becomes impossible to get the look and feel you want.
  • We want semantically styled elements but styled the way we need.
  • Separate visual semantics from element semantics.
  • Classes are far more flexible & reusable
  • Keep specificity low: avoid ID, inline and !important when styling elements.
  • Avoid the descendent selector
  • Add classes to the element you wish to change rather than a parent node.
  • Great developers can create great things is we move our worst best practices out of the way. CSS is fine but we’ve been trying too hard to follow practices that lead us into painful maintenance situations and overly complex code.

 

Source: http://www.lukew.com/

8 Snippets for a More Client-Friendly WordPress CMS

December 11, 2011 - 4:00 pm No Comments

Summary: An advanced article about 8 sample of codes that will turn your WordPress into a client friendly CMS. Enjoy!

 

Article: Out of the box, WordPress is a great content management system. It has tons of functionality, and it’s easy to learn for both developers/designers and their clients who will be managing the site content. However, a little customization can go a long way to creating a more user-friendly theme, a better CMS and a more positive overall user experience for your clients. In this article, we’ll use specific “snippets” (small code samples) to achieve this goal. highlighting 8 great snippets for a more client-friendly WordPress CMS.

 

wordpress-snippets

Note: all these code snippets go in your functions.php file unless otherwise stated.

 

Remove Update Notification

 

The update notification is handy, but you might not always want your client (or all users of a site) to see it. Use the code below to disable it:

 

if ( !current_user_can(‘administrator’) ) { add_action( ‘init’, create_function( ‘$a’, “remove_action( ‘init’, ‘wp_version_check’ );” ), 2 ); add_filter( ‘pre_option_update_core’, create_function( ‘$a’, “return null;” ) ); }

 

Note: the current_user_can tag as above allows the administrator of the site to still see the update, but no other users with different permissions (editors, authors etc).

 

Hide Custom Post Types from Search

 

Custom Post Types are an invaluable tool when using WordPress as a CMS, but you might not always want them to show up in a search. Use the code below to hide Custom Post Types in your site’s search.

 

function SearchFilter($query) { if ($query->is_search) { $query->set(‘post_type’,array(‘post’,'page’)); } return $query; } add_filter(‘pre_get_posts’,'SearchFilter’);

 

Change the Logo on Admin Login Screen

 

There’s nothing wrong with having the WordPress logo on the admin login screen for a client site, but going that extra mile to brand it to their business is a nice touch. Add this code and edit the path to your needs:

 

function custom_login_logo() { echo ”; } add_action(‘login_head’, ‘custom_login_logo’);

 

Also, you might want to change the URL of that image so that it goes to the site homepage (default is WordPress.org):

 

function change_wp_login_url() { echo bloginfo(‘url’); } add_filter(‘login_headerurl’, ‘change_wp_login_url’);

 

Allow Custom Role Access to Menus & Widgets

 

Menus & widgets are great parts of the WordPress core, and often used in CMS applications. However, only Admins can see them. Here’s how to change that:

 

$role_object = get_role(‘editor’); $role_object->add_cap(‘edit_theme_options’);

 

“Edit This” Button on Posts/Pages

 

This simple little fix doesn’t seem like much, but your clients will love it. Adding this code to your page template(s) will add an “Edit This” link on the client side of the site, but one that only logged-in users with the correct permissions can see (ie. your clients editing the site, but not the site viewers). This way your clients have a nice, easy shortcut to edit a page or post’s content without having to go back through the Dashboard. It’s probably best to add this somewhere after the_content.

 

edit_post_link(__(‘Edit This’));

 

*Note: wrap in a php tag.

 

Remove Menu Items in WordPress Dashboard

 

Some of the links in the WordPress Dashboard navigation are sort of useless for most CMS builds. Like the “Links” section, which we’ve only ever used on one build. It’s easy to remove, with this code:

 

add_action( ‘admin_menu’, ‘devpress_remove_menus’, 999 ); function devpress_remove_menus() { remove_menu_page( ‘link-manager.php’ ); }

 

The slug ‘link-manager.php’ removes the link in the Dashboard. To remove a submenu item – for example, “Editor” under “Appearance”, use this:

 

add_action( ‘admin_menu’, ‘devpress_remove_menus’, 999 ); function devpress_remove_menus() { remove_submenu_page( ‘themes.php’, ‘theme-editor.php’ ); }

 

You can find all the slugs for the items you want to remove by simply clicking the link you want to remove and noting the URL in the browser bar.

 

Add Shortcode Functionality to Widgets

 

Shortcodes are handy, and lots of great plugins rely on them. It’s easy to add shortcode functionality to widgets too:

 

add_filter(‘widget_text’, ‘do_shortcode’)

 

Add Image Sizes

 

Wherever possible, I like to “lock-down” the styling in the custom client WordPress builds we do. It makes for greater design consistency down the road as your clients, and potentially their employees, manage the site content. One way to do this is to add custom image sizes.

 

if ( function_exists( ‘add_image_size’ ) ) { add_image_size( ‘category-thumb’, 300, 9999 ); //300 pixels wide (and unlimited height) add_image_size( ‘homepage-thumb’, 220, 180, true ); //(cropped) }

 

Then you can call it in your template files, like so (wrap the following in a php tag):

 

echo get_the_post_thumbnail($post->ID, ‘product-thumb’);

 

Sources: all of these brilliant snippets came from WP-Snippets, CSS-Tricks or DevPress!

 

Source: http://newdesignblog.com/

Case study in best practice: An old guys guide to building modern websites

December 3, 2011 - 4:00 pm No Comments

Summary: You might think that as a designer you should not be concerned about coding … Well, not in this article you not!! This article explains how much it is important to learn coding and converting statics images into a live HTML / CSS webpage. It is a great article explaining the Good and Bad in using latest technologies of webdesign. Enjoy!

 

Article: When you have such a talented bunch of coders you don’t tend to code much yourself. However, when it came to boagworld I was determined to do the majority of it myself. I had two reasons for this.

 

First, I believe that it is not just designers who should be able to code. I think most people involved in the web should have a good understanding of how sites are built (myself included).

 

Second, I was reading about so many cool things that I wanted to have a play. Boagworld gave me the perfect excuse to do so.

 

In this post I wanted to share my journey of playing with ‘the new’. I share what I loved, what I hated and what I never quite got around to.

 

But before I start, I should caveat everything I am about to write.

 

New techniques, old problems – browser support.

 

I am an old guy. I have been working with the web since 1994. I remember when the img tag was the latest big thing. Things have certainly changed a lot since then, but somethings never change. One of those things is browser support.

 

Whether it is Netscape 2 or IE7 there is always a browser that holds us back. That is why it is so important to look closely at your site analytics before you start building. Sometimes you get a nice surprise.

 

When I rummaged around boagworld’s web stats (as we do at the beginning of all projects) I discovered some great news. Only 9.48% of users used Internet Explorer. Of those only 17% used IE7 and 4.56% used IE6. I therefore decided not to provide these two browsers with anything other than basic styling. It felt perfectly reasonable to serve a basic stylesheet to only 2% of my total users.

 

Being free from IE6 & 7 allowed me to play with new CSS properties and adopt HTML5 (with a little help from HTML5shiv). Some may argue that relying on Javascript to support IE8 isn’t very accessible. However, IE8 only accounted 4.3% of users and only approximately 2% of those would have Javascript disabled.

 

Admittedly you might not be in the position to take this approach. However, coding becomes a lot more fun when you can.

 

The good

 

When I first started building boagworld, I felt like a kid in a candy store. I had my solid wireframes and strong design direction. It was time to start putting these together and I confess I got a little carried away. Nowhere more so than with CSS animation.

 

CSS Animation

 

I tried to be restrained and only use CSS animation subtly. However, like a web design student with his first pirated copy of flash, I started plastering animation everywhere.

 

I did eventually get my excitement under control and started to prune back the animation. Even so, I have left quite a lot in. Three types of animation can be found throughout the new boagworld design:

 

  • Image enlargement – You can rollover some images and they enlarge to provide a better view. I can imagine that on some websites this could prove useful. However, I admit this is a bit of a gimmick on boagworld.
  • Hover state transitions – In certain places rolling over some items will display a hover state. Instead of these hover states appearing instantly they fade up gradually. Originally I used this fade effect on all hover states (including links). However, interestingly it made the site feel slow and so I removed them.
  • Pulsing buttons – The primary call to action on the website is the subscribe button in the header. This now slowly pulses. The pulse is so slow you will barely notice it. However, a quick test seemed to indicate that people were more likely to click on it with this subtle animation.

 

Being able to introduce these kinds of subtle animations into your designs without turning to Javascript is great. A purist may argue that this kind of ‘behaviour’ should sit on the behaviour layer (e.g. Javascript) but I see this as more design than behaviour.

 

The obvious danger with CSS animation is that we overuse it. The last thing we want to see is a return to the world of animated gifs and marquee tags. It is worth noting that with the exception of the very subtle pulsing buttons my animation is triggered only on user action. Personally I feel this is a good rule of thumb.

 

Of course, animation is not the only cool feature CSS now offers.

 

CSS gradients, shadows and corners

 

Oh joy of joys! No more tiny images that eat away at performance for the sake of rounded corners, drop shadows and gradient backgrounds. Being able to add these design elements without resorting to images is just a wonder.

 

It improves performance, reduces the number of assets and cleans up your code. What more is there to say.

 

Best of all there are some great tools out there to do all of the coding for you.

 

CSS3_Generator

 

Now you can add beautiful shadows to all those gorgeous web fonts that are now available.

 

Web fonts

 

Were they to make a TV series called “the grumpy old men of web design” web fonts would have surely have been at the top of the list. What was so annoying about fonts on the web was that the biggest hurdle was licensing not technology.

 

But we have them now, so let us rejoice and be glad. They certainly made a world of difference to Boagworld, allowing me to use a font very similar to that used for the Headscape branding.

 

Best of all, whether you are using Google fonts or a service like Font Deck, web fonts are simple to implement. However, the old man in me feels obliged to say that web fonts are not everything. Good typography is about a lot more than choice of face. There has been some great online typography before web fonts and I am sure there will be some terrible examples that use the technology.

 

But web fonts were not the only improvement in typography I made use of on boagworld. There was also rems.

 

REM

 

I bloody hated ems. The maths involved made my brain dribble out of my ears. However, despite that I knew they were important. I knew that allowing users to resize type was important from an accessibility point of view.

 

Fortunately Jonathan Snook introduced me to REM just before I started building boagworld.

 

The problem with ems was a simple one. If you wanted to make a piece of copy appear to be 14px, you would have to calculate the ems value based on all its parents. This got complicated for deeply nested items. With rem that problem goes away.

 

When you set the text size of a particular piece of copy it is set relative to the HTML element, not its immediate parent. This makes life so much easier. Now you can still think in pixels but allow users to resize text.

 

I love rem because it makes your code so much easier to understand. Much in the same way as HTML5, which has helped bring about the demise of the DIV.

 

The demise of the DIV

 

One of the best things about building the new boagworld website is building it using HTML5. HTML5 has a lot of advantages over its predecessors, but the one that I personally find the most satisfying is the readability it introduces to my code.

 

Before HTML5 my code was div-tastic and I hated it. I tried to keep things tidy by putting comments after each closing div explaining what it related too, but inevitably things ended up a mess.

 

With the introduction of new semantic tags such as section, header, article, aside and footer, code suddenly makes so much more sense. Although I still use DIVs in places, generally code seems much easier to read.

 

Not that it is just the HTML 5 tags which makes my code easier to read. It is also some of the new CSS properties.

 

New layout approaches

 

One of the most exciting changes I was able to implement on the new Boagworld Website was giving floats the flick. When I moved from table-based design to CSS layout, one of the most challenging parts of the transition was getting my head around floats. To this day they are a momentous pain in the arse.

 

Fortunately, because I discovered that I could drop support for Internet Explorer 7 I was able to use a number of alternative layout options including display: table–cell and display: block–inline.

 

Block–inline has become my primary tool for creating multiple column layouts.

 

Table–cell has proved invaluable when you need two columns to have the same height. Another use for table-cell is when you want to equally space navigation items across the entire width of the page.

 

In my opinion these new layout approaches are the biggest reason for wanting to renegate Internet Explorer 7.

 

Talking of navigation there is one other CSS property I have embraced with enthusiasm.

 

nth child

 

The nth child property has helped clean up my code by removing unnecessary classes such as “first”, “last”, and “odd”. Typically I used these classes to identifying the first or last item in a list or the odd and even rows in a table that I would like to styled differently.

 

Using the nth child property I was able to style these elements without adding superfluous markup.

 

It may not seem like a big thing but for somebody who hasn’t coded HTML and CSS for a couple of years this was incredibly satisfying.

 

Not that everything is now a bed of roses. There are still some things that frustrate me.

 

The Bad

 

There is no doubt that things have improved a lot over the last couple of years and that they will only get better in the years to come. However while building Boagworld I did encounter a few things that frustrated me. My hope is that by sharing them here you will not feel so alone if you encounter those problems and that maybe some of you even have some solutions for me.

 

Here are the things the particularly frustrated me.

 

  • Percentages for layout: When building a responsive website working out the percentage widths of screen elements can get frustratingly complicated. Surely some smart Alec can build an application that calculates all this stuff for you?
  • Browser glitches: I noticed that CSS animation in particular would occasionally create frustrating little rendering issues in some browsers. For example I still get the occasional visual flicker when a user interacts with some screen elements on the Boagworld Website.
  • Confusion over using certain HTML5 tags: As I was using HTML 5 for the first time I spent a lot of time reading up on how the new tags should be used. Unfortunately I was seeing a lot of disagreement and I think it will take time before common consensus emerges over best practice.
  • Font rendering: Although I was incredibly excited to use web fonts it was slightly disappointing to see the rendering issues at some of these fonts were having on certain operating systems and browsers. I still think there is a long way to go in this area and I’m sure we will see font foundry’s adapting their fonts to be more suitable for the web.
  • Still no variables: It still amazes me that CSS does not natively support variables. It strikes me that this would be incredibly useful and significantly reduce the amount of code we need to write, so making sites download faster and code more readable.

 

Interestingly, when it comes to this last issue, I have since discovered that perhaps a bit more research on my part would have paid off.

 

The “should have done’s”

 

One of the problems with the web moving at such an incredible rate is that it can be hard to keep up with the latest techniques and you inevitably discover something mid-project that is too late to implement. For me that was LESS and the Semantic Grid System.

 

These 2 technologies combined solved 2 of the things that frustrated me.

 

LESS extends CSS with dynamic behaviours such as operators, functions and those variables I was so desperate to have. For me this would have opened up a world of possibilities. Unfortunately I did not discover LESS until well into the build process.

 

Combined with the Semantic Grid System, LESS also solved the mind bending maths involved in developing a responsive grid system. Admittedly there are other responsive grid frameworks available. However, these all involve superfluous markup and so I rejected them for use on Boagworld, instead building everything from scratch.

 

Because the Semantic Grid System is built upon LESS it means it can avoid the need for superfluous markup and so would have been perfect for my needs.

 

Although it is too late to use these technologies on Boagworld, I will certainly be considering them for any future projects and would suggest you do the same. To read more about LESS and the Semantic Grid System I recommend smashing Magazine’s article entitled “The Semantic Grid System: Page layout for tomorrow”.

 

Conclusions

 

I have loved building the Boagworld website. Although it has been frustrating at times, like modern exams, things are so much easier than in my day! Although I recognise that I was in a somewhat privileged position by not having to support Internet Explorer 7, it has given me a taste of what is to come.

 

If like me you have been building websites for years, I would encourage you to take the time to ensure your skills are up-to-date and you are aware of the latest tools available. Ultimately it will save you so much time and effort.

 

Source: http://boagworld.com/

Introduction To URL Rewriting

November 1, 2011 - 3:00 pm No Comments

Summary: An article for advanced users regarding the use of shortening and re-writing URLs of the published articles within Websites and Blogs. Enjoy! 

 

Article: Many Web companies spend hours and hours agonizing over the best domain names for their clients. They try to find a domain name that is relevant and appropriate, sounds professional yet is distinctive, is easy to spell and remember and read over the phone, looks good on business cards and is available as a dot-com.

 

Or else they spend thousands of dollars to purchase the one they really want, which just happened to be registered by a forward-thinking and hard-to-find squatter in 1998.

 

They go through all that trouble with the domain name but neglect the rest of the URL, the element after the domain name. It, too, should be relevant, appropriate, professional, memorable, easy to spell and readable. And for the same reasons: to attract customers and improve in search ranking.

 

Fortunately, there is a technique called URL rewriting that can turn unsightly URLs into nice ones — with a lot less agony and expense than picking a good domain name. It enables you to fill out your URLs with friendly, readable keywords without affecting the underlying structure of your pages.

 

This article covers the following:

  1. What is URL rewriting?
  2. How can URL rewriting help your search rankings?
  3. Examples of URL rewriting, including regular expressions, flags and conditionals;
  4. URL rewriting in the wild, such as on Wikipedia, WordPress and shopping websites;
  5. Creating friendly URLs;
  6. Changing pages names and URLs;
  7. Checklist and troubleshooting.

[Editor's note: A must-have for professional Web designers and developers: The Printed Smashing Books Bundle is full of practical insight for your daily work. Get the bundle right away!]

 

What Is URL Rewriting?

 

If you were writing a letter to your bank, you would probably open your word processor and create a file named something like lettertobank.doc. The file might sit in your Documents directory, with a full path like C:\Windows\users\julie\Documents\lettertobank.doc. One file path = one document.

 

Similarly, if you were creating a banking website, you might create a page named page1.html, upload it, and then point your browser to http://www.mybanksite.com/page1.html. One URL = one resource. In this case, the resource is a physical Web page, but it could be a page or product drawn from a CMS.

 

URL rewriting changes all that. It allows you to completely separate the URL from the resource. With URL rewriting, you could have http://www.mybanksite.com/aboutus.html taking the user to …/page1.html or to …/about-us/ or to …/about-this-website-and-me/ or to …/youll-never-find-out-about-me-hahaha-Xy2834/. Or to all of these. It’s a bit like shortcuts or symbolic links on your hard drive. One URL = one way to find a resource.

 

With URL rewriting, the URL and the resource that it leads to can be completely independent of each other. In practice, they’re usually not wholly independent: the URL usually contains some code or number or name that enables the CMS to look up the resource. But in theory, this is what URL rewriting provides: a complete separation.

 

How Does URL Rewriting Help?

 

Can you guess what this Web page sells?

 

http://www.diy.com/diy/jsp/bq/nav.jsp?action=detail&fh_secondid=11577676

 

B&Q went to all the trouble and expense of acquiring diy.com and implementing a stock controlled e-commerce website, but left its URLs indecipherable. If you guessed “brown guttering,” you might want to considering playing the lottery.

 

Even when you search directly for this “miniflow gutter brown” on Google UK, B&Q’s page comes up only seventh in the organic search results, below much smaller companies, such as a building supplier with a single outlet in Stirlingshire. B&Q has 300+ branches and so is probably much bigger in budget, size and exposure, so why is it not doing as well for this search term? Perhaps because the other search results have URLs like http://www.prof…co.uk/products/brown-miniflo-gutter-148/; that is, the URL itself contains the words in the search term.

 

Screenshot 1

Almost all of these results on Google have the search term in their URLs (highlighted in green). The one at the bottom does not.

 

Looking at the URL from B&Q, you would (probably correctly) assume that a file named nav.jsp within the directory /diy/jsp/bq/ is used to display products when given their ID number, 11577676 in this case. That is the resource intimately tied to this URL.

 

So, how would B&Q go about turning this into something more recognizable, like http://www.diy.com/products/miniflow-gutter-brown/11577676, without restructuring its whole website? The answer is URL rewriting.

 

Another way to look at URL rewriting is like a thin layer that sits on top of a website, translating human- and search-engine-friendly URLs into actual URLs. Doing it is easy because it requires hardly any changes to the website’s underlying structure — no moving files around or renaming things.

 

URL rewriting basically tells the Web server that
/products/miniflow-gutter-brown/11577676 should show the Web page at: /diy/jsp/bq/nav.jsp?action=detail&fh_secondid=11577676,
without the customer or search engine knowing about it.

 

Many factors (or “signals”), of course, determine the search ranking for a particular term, over 200 of them according to Google. But friendly and readable URLs are consistently ranked as one of the most important of those factors. They also help humans to quickly figure out what a page is about.

 

The next section describes how this is done.

 

How To Rewrite URLs

 

Whether you can implement URL rewriting on a website depends on the Web server. Apache usually comes with the URL rewriting module, mod_rewrite, already installed. The set-up is very common and is the basis for all of the examples in this article. ISAPI Rewrite is a similar module for Windows IIS but requires payment (about $100 US) and installation.

 

The Simplest Case

 

The simplest case of URL rewriting is to rename a single static Web page, and this is far easier than the B&Q example above. To use Apache’s URL rewriting function, you will need to create or edit the .htaccess file in your website’s document root (or, less commonly, in a subdirectory).

 

For instance, if you have a Web page about horses named Xu8JuefAtua.htm, you could add these lines to .htaccess:

 

  • RewriteEngine On
  • RewriteRule horses.htm Xu8JuefAtua.htm

Now, if you visit http://www.mywebsite.com/horses.htm, you’ll actually be shown the Web page Xu8JuefAtua.htm. Furthermore, your browser will remain at horses.htm, so visitors and search engines will never know that you originally gave the page such a cryptic name.

 

Introducing Regular Expressions

 

In URL rewriting, you need only match the path of the URL, not including the domain name or the first slash. The rule above essentially tells Apache that if the path contains horses.htm, then show the Web page Xu8JuefAtua.htm. This is slightly problematic, because you could also visit http://www.mywebsite.com/reallyfasthorses.html, and it would still work. So, what we really need is this:

 

  • RewriteEngine On
  • RewriteRule ^horses.htm$ Xu8JuefAtua.htm

The ^horses.htm$ is not just a search string, but a regular expression, in which special characters — such as ^ . + * ? ^ ( ) [ ] { } and $ — have extra significance. The ^ matches the beginning of the URL’s path, and the $ matches the end. This says that the path must begin and end with horses.htm. So, only horses.htm will work, and not reallyfasthorses.htm or horses.html. This is important for search engines like Google, which can penalize what it views as duplicate content — identical pages that can be reached via multiple URLs.

 

Without File Endings

 

You can make this even better by ditching the file ending altogether, so that you can visit either http://www.mywebsite.com/horses or http://www.mywebsite.com/horses/:

 

  • RewriteEngine On
  • RewriteRule ^horses/?$ Xu8JuefAtua.html [NC]

The ? indicates that the preceding character is optional. So, in this case, the URL would work with or without the slash at the end. These would not be considered duplicate URLs by a search engine, but would help prevent confusion if people (or link checkers) accidentally added a slash. The stuff in brackets at the end of the rule gives Apache some further pointers. [NC] is a flag that means that the rule is case insensitive, so http://www.mywebsite.com/HoRsEs would also work.

 

Wikipedia Example

 

We can now look at a real-world example. Wikipedia appears to use URL rewriting, passing the title of the page to a PHP file. For instance…

 

http://en.wikipedia.org/wiki/Barack_obama

 

… is rewritten to:

 

http://en.wikipedia.org/w/index.php?title=Barack_obama

 

This could well be implemented with an .htaccess file, like so:

 

  • RewriteEngine On
  • #Look for the word “wiki” followed by a slash, and then the article title
  • RewriteRule ^wiki/(.+)$ w/index.php?title=$1 [L]

The previous rule had /?, which meant zero or one slashes. If it had said /+, it would have meant one or more slashes, so even http://www.mywebsite.com/horses//// would have worked. In this rule, the dot (.) matches any character, so .+ matches one or more of any character — that is, essentially anything. And the parentheses — ( ) — ask Apache to remember what the .+ is. The rule above, then, tells Apache to look for wiki/ followed by one or more of any character and to remember what it is. This is remembered and then rewritten as $1. So, when the rewriting is finished, wiki/Barack_obama becomes w/index.php?title=Barack_obama

 

Thus, the page w/index.php is called, passing Barack_obama as a parameter. The w/index.php is probably a PHP page that runs a database lookup — like SELECT * FROM articles WHERE title=’Barack obama’ — and then outputs the HTML.

 

Screenshot_2

You can also view Wikipedia entries directly, without the URL rewriting.

 

Comments and Flags

 

The example above also introduced comments. Anything after a # is ignored by Apache, so it’s a good idea to explain your rewriting rules so that future generations can understand them. The [L] flag means that if this rule matches, Apache can stop now. Otherwise, Apache would continue applying subsequent rules, which is a powerful feature but unnecessary for all but the most complex rule sets.

 

Implementing the B&Q Example

 

The recommendation for B&Q above could be implemented with an .htaccess file, like so:

  • RewriteEngine On
  • #Look for the word “products” followed by slash, product title, slash, id number
  • RewriteRule ^products/.*/([0-9]+)$ diy/jsp/bq/nav.jsp?action=detail&fh_secondid=$1 [NC,L]

Here, the .* matches zero or more of any character, so nothing or anything. And the [0-9] matches a single numerical digit, so [0-9]+ matches one or more numbers.

 

The next section covers a couple of more complex conditional examples. You can also read the Apache rewriting guide for much more information on all that URL rewriting has to offer.

 

Conditional Rewriting

 

URL rewriting can also include conditions and make use of environment variables. These two features make for an easy way to redirect requests from one domain alias to another. This is especially useful if a website changes its domain, from mywebsite.co.uk to mywebsite.com for example.

 

Domain Forwarding

 

Most domain registrars allow for domain forwarding, which redirects all requests from one domain to another domain, but which might send requests for www.mywebsite.co.uk/horses to the home page at www.mywebsite.com and not to www.mywebsite.com/horses. You can achieve this with URL rewriting instead:

 

  • RewriteEngine On
  • RewriteCond %{HTTP_HOST} !^www.mywebsite.com$ [NC]
  • RewriteRule (.*) http://www.mywebsite.com/$1 [L,R=301]

The second line in this example is a RewriteCond, rather than a RewriteRule. It is used to compare an Apache environment variable on the left (such as the host name in this case) with a regular expression on the right. Only if this condition is true will the rule on the next line be considered.

 

In this case, %{HTTP_HOST} represents www.mywebsite.co.uk, the host (i.e. domain) that the browser is trying to visit. The ! means “not.” This tells Apache, if the host does not begin and end with www.mywebsite.com, then remember and rewrite zero or more of any character to www.mywebsite.com/$1. This converts www.mywebsite.co.uk/anything-at-all to www.mywebsite.com/anything-at-all. And it will work for all other aliases as well, like www.mywebsite.biz/anything-at-all and mywebsite.com/anything-at-all.

 

The flag [R=301] is very important. It tells Apache to do a 301 (i.e. permanent) redirect. Apache will send the new URL back to the browser or search engine, and the browser or search engine will have to request it again. Unlike all of the examples above, the new URL will now appear in the browser’s location bar. And search engines will take note of the new URL and update their databases. [R] by itself is the same as [R=302] and signifies a temporary redirect.

 

File Existence and WordPress

 

Smashing Magazine runs on the popular blogging software WordPress. WordPress enables the author to choose their own URL, called a “slug.” Then, it automatically prepends the date, such as http://coding.smashingmagazine.com/2011/09/05/getting-started-with-the-paypal-api/. In your pre-URL rewriting days, you might have assumed that Smashing Magazine’s Web server was actually serving up a file located at …/2011/09/05/getting-started-with-the-paypal-api/index.html. In fact, WordPress uses URL rewriting extensively.

 

Screenshot_3

WordPress enables the author to choose their own URL for an article.

 

WordPress’ .htaccess file looks like this:

 

  • RewriteEngine On
  • RewriteBase /
  • RewriteCond %{REQUEST_FILENAME} !-f
  • RewriteCond %{REQUEST_FILENAME} !-d
  • RewriteRule . /index.php [L]

 

The -f means “this is a file” and -d means “this is a directory.” This tells Apache, if the requested file name is not a file, and the requested file name is not a directory, then rewrite everything (i.e. any path containing any character) to the page index.php. If you are requesting an existing image or the log-in page wp-login.php, then the rule is not triggered. But if you request anything else, like /2011/09/05/getting-started-with-the-paypal-api/, then the file index.php jumps into action.

 

Internally, index.php (probably) looks at the environment variable $_SERVER['REQUEST_URI'] and extracts the information that it needs to find out what it is looking for. This gives it even more flexibility than Apache’s rewrite rules and enables WordPress to mimic some very sophisticated URL rewriting rules. In fact, when administering a WordPress blog, you can go to Settings → Permalink on the left side, and choose the type of URL rewriting that you would like to mimic.

 

Screenshot_4

WordPress’ permalink settings, letting you choose the type of URL rewriting that you would like to mimic.

 

Rewriting Query Strings

 

If you are hired to recreate an existing website from scratch, you might use URL rewriting to redirect the 20 most popular URLs on the old website to the locations on the new website. This could involve redirecting things like prod.php?id=20 to products/great-product/2342, which itself gets redirected to the actual product page.

 

Apache’s RewriteRule applies only to the path in the URL, not to parameters like id=20. To do this type of rewriting, you will need to refer to the Apache environment variable %{QUERY_STRING}. This can be accomplished like so:

 

  • RewriteEngine On
  • RewriteCond %{QUERY_STRING} ^id=20$
  • RewriteRule ^prod.php$ ^products/great-product/2342$ [L,R=301]
  • RewriteRule ^products/(.*)/([0-9]+)$ ^productview.php?id=$1 [L]

In this example, the first RewriteRule triggers a permanent redirect from the old website’s URL to the new website’s URL. The second rule rewrites the new URL to the actual PHP page that displays the product.

 

Examples Of URL Rewriting On Shopping Websites

 

For complex content-managed websites, there is still the issue of how to map friendly URLs to underlying resources. The simple examples above did that mapping by hand, manually associating a URL like horses.htm with the file or resource Xu8JuefAtua.htm. Wikipedia looks up the resource based on the title, and WordPress applies some complex internal rule sets. But what if your data is more complex, with thousands of products in hundreds of categories? This section shows the approach that Amazon and many other shopping websites take.

 

If you’ve ever come across a URL like this on Amazon, http://www.amazon.co.uk/High-Voltage-AC-DC/dp/B00008AJL3, you might have assumed that Amazon’s website has a subdirectory named /High-Voltage-AC-DC/dp/ that contains a file named B00008AJL3.

 

This is very unlikely. You could try changing the name of the top-level “directory” and you would still arrive on the same page, http://www.amazon.co.uk/Test-Voltage-AC-DC/dp/B00008AJL3.

 

The bit at the end is what really matters. Looking down the page, you’ll see that B00008AJL3 is this AC/DC album’s ASIN (Amazon Standard Identification Number). If you change that, you’ll get a “Page not found” or an entirely different product: http://www.amazon.co.uk/High-Voltage-AC-DC/dp/B003BEZ7HI.

 

The /dp/ also matters. Changing this leads to a “Page not found.” So, the B00008AJL3 probably tells Amazon what to display, and the dp tells the website how to display it. This is URL rewriting in action, with the original URL possibly ending up getting rewritten to something like:
http://www.amazon.co.uk/displayproduct.php?asin=B00008AJL3.

 

Features of an Amazon URL

 

This introduces some important features of Amazon’s URLs that can be applied to any website with a complex set of resources. It shows that the URL can be automatically generated and can include up to three parts:

 

  1. The wordsIn this case, the words are based on the album and artist, and all non-alphanumeric characters are replaced. So, the slash in AC/DC becomes a hyphen. This is the bit that helps humans and search engines.
  2. An ID numberOr something that tells the website what to look up, such as B00008AJL3.
  3. An identifierOr something that tells the website where to look for it and how to display it. If dp tells Amazon to look for a product, then somewhere along the line, it probably triggers a database statement such as SELECT * FROM products WHERE id=’B00008AJL3′.

Other Shopping Examples

 

Many other shopping websites have URLs like this. In the list below, the ID number and (suspected) identifier are in bold:

 

  • http://www.ebay.co.uk/itm/Ian-Rankin-Set-Darkness-Rebus-Novel-/140604842997
  • http://www.kelkoo.com/c-138201-lighting/brand/caravan
  • http://www.ciao.co.uk/Fridge_Freezers_5266430_3
  • http://www.gumtree.com/p/for-sale/boys-bmx-bronx-blaze/97669042
  • http://www.comet.co.uk/c/Televisions/LCD-Plasma-LED-TVs/1844

A significant benefit of this type of URL is that the actual words can be changed, as shown below. As long as the ID number stays the same, the URL will still work. So products can be renamed without breaking old links. More sophisticated websites (like Ciao above) will redirect the changed URL back to the real one and thus avoid creating the appearance of duplicate content (see below for more on this topic).

 

Screenshot_5

Websites that use URL rewriting are more flexible with their URLs — the words can change but the page will still be found.

 

Friendly URLs

 

Now you know how to map nice friendly URLs to their underlying Web pages, but how should you create those friendly URLs in the first place?

 

If we followed the current advice, we would separate words with hyphens rather than underscores and capitalize consistently. Lowercase might be preferable because most people search in lowercase. Punctuation such as dots and commas should also be turned into hyphens, otherwise they would get turned into things like %2C, which look ugly and might break the URL when copied and pasted. You might want to remove apostrophes and parentheses entirely for the same reason.

 

Whether to replace accented characters is debatable. URLs with accents (or any non-Roman characters) might look bad or break when rendered in a different character format. But replacing them with their non-accented equivalents might make the URLs harder for search engines to find (and even harder if replaced with hyphens). If your website is for a predominately French audience, then perhaps leave the French accents in. But substitute them if the French words are few and far between on a mainly English website.

 

This PHP function succinctly handles all of the above suggestions:

 

function GenerateUrl ($s) {
//Convert accented characters, and remove parentheses and apostrophes
$from = explode (‘,’, “ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u,(,),[,],’”);
$to = explode (‘,’, ‘c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u,,,,,,’);
//Do the replacements, and convert all other non-alphanumeric characters to spaces
$s = preg_replace (‘~[^\w\d]+~’, ‘-’, str_replace ($from, $to, trim ($s)));
//Remove a – at the beginning or end and make lowercase
return strtolower (preg_replace (‘/^-/’, ”, preg_replace (‘/-$/’, ”, $s)));
}

This would generate URLs like this:

 

echo GenerateUrl (“Pâtisserie (Always FRESH!)”); //returns “patisserie-always-fresh”

Or, if you wanted a link to a $product variable to be pulled from a database:

 

$product = array (‘title’=>’Great product’, ‘id’=>100);
echo ‘<a href=”‘ . GenerateUrl ($product['title']) . ‘/’ . $product['id'] . ‘”>’;
echo $product['title'] . ‘</a>’;

Changing Page Names

 

Search engines generally ignore duplicate content (i.e. multiple pages with the same information). But if they think they are being manipulated, search engines will actively penalize the website, so avoid this where possible. Google recommends using 301 redirects to send users from old pages to new ones.

 

When a URL-rewritten page is renamed, the old URL and new URL should both still work. Furthermore, to avoid any risk of duplication, the old URL should automatically redirect to the new one, as WordPress does.

 

Doing this in PHP is relatively easy. The following function looks at the current URL, and if it’s not the same as the desired URL, it redirects the user:

 

function CheckUrl ($s) {
// Get the current URL without the query string, with the initial slash
$myurl = preg_replace (‘/\?.*$/’, ”, $_SERVER['REQUEST_URI']);
//If it is not the same as the desired URL, then redirect
if ($myurl != “/$s”) {Header (“Location: /$s”, true, 301); exit;}
}

This would be used like so:

 

$producturl = GenerateUrl ($product['title']) . ‘/’ . $product['id'];
CheckUrl ($producturl); //redirects the user if they are at the wrong place

If you would like to use this function, be sure to test it in your environment first and with your rewrite rules, to make sure that it does not cause any infinite redirects. This is what that would look like:

 

Screenshot_6

This is what happens when Google Chrome visits a page that redirects to itself.

 

Checklist And Troubleshooting

 

Use the following checklist to implement URL rewriting.

 

1. Check That It’s Supported

 

Not all Web servers support URL rewriting. If you put up your .htaccess file on one that doesn’t, it will be ignored or will throw up a “500 Internal Server Error.”

 

2. Plan Your Approach

 

Figure out what will get mapped to what, and how the correct information will still get found. Perhaps you want to introduce new URLs, like my-great-product/p/123, to replace your current product URLs, like product.php?id=123, and to substitute new-category/c/12 for category.php?id=12.

 

3. Create Your Rewrite Rules

 

Create an .htaccess file for your new rules. You can initially do this in a /testing/ subdirectory and using the [R] flag, so that you can see where things go:

 

  • RewriteEngine On
  • RewriteRule ^.+/p/([0-9]+) product.php?id=$1 [NC,L,R]
  • RewriteRule ^.+/c/([0-9]+) category.php?id=$1 [NC,L,R]

Now, if you visit www.mywebsite.com/testing/my-great-product/p/123, you should be sent to www.mywebsite.com/testing/product.php?id=123. You’ll get a “Page not found” because product.php is not in your /testing/ subdirectory, but at least you’ll know that your rules work. Once you’re satisfied, move the .htaccess file to your document root and remove the [R] flag. Now www.mywebsite.com/my-great-product/p/123 should work.

 

4. Check Your Pages

 

Test that your new URLs bring in all the correct images, CSS and JavaScript files. For example, the Web browser now believes that your Web page is named 123 in a directory named my-great-product/p/. If the HTML refers to a file named images/logo.jpg, then the Web browser would request the image from www.mywebsite.com/my-great-product/p/images/logo.jpg and would come up with a “File not found.”

 

You would need to also rewrite the image locations or make the references absolute (like <img src=”/images/logo.jpg”/>) or put a base href at the top of the <head> of the page (<base href=”/product.php”/>). But if you do that, you would need to fully specify any internal links that begin with # or ? because they would now go to something like product.php#details.

 

5. Change Your URLs

 

Now find all references to your old URLs, and replace them with your new URLs, using a function such as GenerateUrl to consistently create the new URLs. This is the only step that might require looking deep into the underlying code of your website.

 

6. Automatically Redirect Your Old URLs

 

Now that the URL rewriting is in place, you probably want Google to forget about your old URLs and start using the new ones. That is, when a search result brings up product.php?id=20, you’d want the user to be visibly redirected to my-great-product/p/123, which would then be internally redirected back to product.php?id=20.

 

This is the reverse of what your URL rewriting already does. In fact, you could add another rule to .htaccess to achieve this, but if you get the rules in the wrong order, then the browser would go into a redirect loop.

 

Another approach is to do the first redirect in PHP, using something like the CheckUrl function above. This has the added advantage that if you rename the product, the old URL will immediately become invalid and redirect to the newest one.

 

7. Update and Resubmit Your Site Map

 

Make sure to carry through your new URLs to your site map, your product feeds and everywhere else they appear.

 

Conclusion

 

URL rewriting is a relatively quick and easy way to improve your website’s appeal to customers and search engines. We’ve tried to explain some real examples of URL rewriting and to provide the technical details for implementing it on your own website. Please leave any comments or suggestions below.

 

Source: http://coding.smashingmagazine.com/

10+ .htaccess snippets to optimize your website

October 25, 2011 - 4:10 pm No Comments

Summary: Another technical article for advanced users. Very interesting website with more than 10 tips regarding the use of .htaccess files to optimize your website. Have a look and feel free to try the code within. Enjoy!

 

Article: All of the snippets below have to be pasted into your .htaccess file, which is located on the root of your Apache server.
Waring: Always make sure you have a working backup before editing your .htaccess file!

 

Force trailing slash
Many clients of mine asked me for always having a trailing slash at the end of their urls. Looks like it’s great for SEO. The following snippet will alwyas add a trailing slash to your site urls.

 

<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
</IfModule>

Source: http://perishablepress.com/code-snippets/

 

Prevent hotlinking
Hotlinking (the act of using images from another site than yours) is unfortunely a common practice which can waste lots of your precious bandwidth. This useful snippets will redirect all hotlinked images to a specific image, defined on line 6.

 

RewriteEngine On
#Replace ?mysite\.com/ with your blog url
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mysite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
#Replace /images/nohotlink.jpg with your “don’t hotlink” image url
RewriteRule .*\.(jpe?g|gif|bmp|png)$ /images/nohotlink.jpg [L]

Source: http://www.wprecipes.com/how-to-protect-your…

 

Redirect mobile devices
If your site is not using responsive web design yet, it could be very useful to be able to redirect mobile device to a mobile-specific version of your website.

 

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/m/.*$
RewriteCond %{HTTP_ACCEPT} “text/vnd.wap.wml|application/vnd.wap.xhtml+xml” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “wapp|wapr|webc|winw|winw|xda|xda-” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “up.browser|up.link|windowssce|iemobile|mini|mmp” [NC,OR]
RewriteCond %{HTTP_USER_AGENT} “symbian|midp|wap|phone|pocket|mobile|pda|psp” [NC]
#————- The line below excludes the iPad
RewriteCond %{HTTP_USER_AGENT} !^.*iPad.*$
#————-
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC] #*SEE NOTE BELOW
RewriteRule ^(.*)$ /m/ [L,R=302]

 

Source: http://snipplr.com/view.php?codeview&id=55114


Force download of a specific filetype
For some reasons you may need to force download of specific files, such as MP3s or XLS. This code snippets will prevent your visitor’s browser to read the file and force downloading instead.

 

<Files *.xls>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>
<Files *.eps>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>

 

Source: http://snipplr.com/view.php?codeview&id=54752

 

Cross Domain Font embedding for Firefox
When embedding a font, Firefox do not allow you to embed from an external website. Using the .htaccess snippet below, you can bypass this limitation.

 

<FilesMatch “\.(ttf|otf|eot|woff)$”>
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin “http://yourdomain.com”
</IfModule>
</FilesMatch>

Source: http://snipplr.com/view/53703

 

Speed up your site with .htaccess caching
This is probably the most useful snippet of this whole list. By using some simple .htaccess file cahing, you can dramatically increase your website speed. A snippet you should always have on your toolbox!

 

# 1 YEAR
<FilesMatch “\.(ico|pdf|flv)$”>
Header set Cache-Control “max-age=29030400, public”
</FilesMatch>
# 1 WEEK
<FilesMatch “\.(jpg|jpeg|png|gif|swf)$”>
Header set Cache-Control “max-age=604800, public”
</FilesMatch>
# 2 DAYS
<FilesMatch “\.(xml|txt|css|js)$”>
Header set Cache-Control “max-age=172800, proxy-revalidate”
</FilesMatch>
# 1 MIN
<FilesMatch “\.(html|htm|php)$”>
Header set Cache-Control “max-age=60, private, proxy-revalidate”
</FilesMatch>

Source: http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html

 

Stop spam on your WordPress blog
Sick of spammers on your WordPress blog? Of course, Akismet helps a lot, but your .htaccess file can also help: Today’s recipe is a snippet that prevent spam bots to directly access your wp-comments-post.php file, which is used to post comments on your blog.

 

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*yourdomainname.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]
</IfModule>

Source: http://www.wprecipes.com/reduce-spam-on-your-wordpress-blog-by-using-htaccess

 

Redirect different feeds to a single format
Years ago, differents feed formats, such as RSS, Atom or Rdf were used. Nowadays, it seems that RSS is definitely the most used. This snippets allows you to redirect all feeds formats to a single feed. This snippet can be used “as it” on WordPress blogs.

 

<IfModule mod_alias.c>
RedirectMatch 301 /feed/(atom|rdf|rss|rss2)/?$ http://example.com/feed/
RedirectMatch 301 /comments/feed/(atom|rdf|rss|rss2)/?$ http://example.com/comments/feed/
</IfModule>

Source: http://www.wprecipes.com/redirect-feeds-to-a-single-format

 

Configure your website for HTML5 videos
HTML5 is bringing lots of new exiting options in the world of web development. Among other cool features, being able to play videos without using Flash is really cool. Though, you have to configure your server properly to work with the latest HTML5 video standards. This snippet will definitely help.

 

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
AddType video/ogg .ogv
AddType video/ogg .ogg
AddType video/mp4 .mp4
AddType video/webm .webm
AddType application/x-shockwave-flash swf

Source: http://snipplr.com/view.php?codeview&id=53437

 

Log PHP errors
Instead of displaying PHP errors to your site (and to possible hackers…) this code snippet will log it into a .log file while hiding errors to visitors.

 

# display no errs to user
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
# log to file
php_flag log_errors on
php_value error_log /location/to/php_error.log

Source: http://css-tricks.com/snippets/htaccess/php-error-logging/

 

Run PHP inside JavaScript files
When coding in JavaScript, it can very useful to be able to use PHP inside the .js files, for example for retrieving data from your database. Here is a snippet to allow the use of PHP inside .js files.

 

AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch “\.(js|php)$”>
SetHandler application/x-httpd-php
</FilesMatch>

 

Source – Article: http://newdesignblog.com/