.htaccess snippets to optimize your website

 .htaccess snippets to optimize your website

Apache .htaccess file is at the heart of your web server and control how your website will react to different actions performed by your visitors. I’ve compiled 10+ awesome .htaccess snippets to optimize your website in many ways: Redirections, performances, ease of use… Enjoy!

All of the snippets below have to be pasted into your .htaccess file, which is located on the root of your Apache server.

Warning: 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: http://www.kavoir.com/2010/07/how-to-execute-run-php-code-inside-javascript-files.html

Image Optimization for Search Engines

Image Optimization for Search Engines – Image SEO

Image Optimization Tools for your images is one of the many on-page SEO steps that you need to undertake. Optimizing your images is an important SEO step, it is in fact connected to other SEO factors such as bounce rate, site speed and others.

Image Optimization for Search Engines

  • SEO Friendly Images WP Plugin by no less than Vladimir Prelovac.
  • Udinra All Image Sitemap WP Plugin creates sitemap.xml file for your images.
  • DynamicDrive a web image optimizer that compresses and converts your images to render it for suitable for online use. This is one of my favorite tools, perfect when optimizing single or few images.
  • ImageOptimizer is another web image optimizer that treats your images per upload. There is also a desktop version.
  • Shrink O Matic is one of my most favorite tools. It runs on Adobe Air and can help you optimize images in bulk by a simple gesture of drag and drop. I personally used it to optimize thousands of images for a recent project.
  • FeedtheBot tool checks Alt Texts, Titles and Dimensions for you automatically.

MayDay Changes of Search Industry Highlights

Google monthly updates for May has been less 39 when compared to the previous month April 50 updates

Well I would always look into the items, which are closely related to one, other like Inorganic Backlinks & Penguin Improvements

Below mentioned snippets shared from Google. 

Better application of inorganic backlinks signals. [Launch codename "improv-fix", project codename "Page Quality"] We have algorithms in place designed to detect a variety of link schemes, a common spam technique. This change ensures we’re using those signals appropriately in the rest of our ranking.

Improvements to Penguin. [Launch codename "twref2", project codename "Page Quality"] This month we rolled out a couple minor tweaks to improve signals and refresh the data used by the penguin algorithm.

The Below mentioned changes are the main things which I preferably feel most importance for Integrated Digital Marketing Person. Here is the list of Google May Updates for 2012 of Search Industry

Read More : The May 2012 Changes of Search Industry Highlights

Optimize Your Dated Permalinks

How to streamline and maximize the effectiveness of your WordPress URLs by using htaccess to remove extraneous post-date information: years, months, and days.

/%year%/%monthnum%/%day%/%postname%/

The benefits of using this format are primarily organizational in nature. Post-date information that is “built-in” to every URLprovides immediate, “at-a-glance” knowledge of post “freshness”. Looking ahead ten, twenty or even a hundred years into the future of the blogosphere, there will be trillions of posts and articles, each with their own unique URL. Archived copies of content may or may not include creation date: dynamically archived pages require deliberate database queries, while those archived statically may no longer have access to post-date data. Including post dates in permalinks provides permanent, facilitative record of content origination. Needless to say, most adopters of dated permalinks probably jump on board because the WordPress Admin makes it super-easy to follow the crowd.

Over time, however, as understanding of search engine optimization permeated the blogosphere, many people who had embraced such “dated URLs” began rethinking their approach to permalinks. Eventually, the trend had reversed, as SEO-savvy bloggers avoided dated permalinks like spider pig. These days, a majority of bloggers initialize their permalinks with either a “category/name” or even a name-only URL

format:

/%category%/%postname%/ (or) /%postname%/

Of course, the benefits to this simplified structure are largely utilitarian in nature. Removal of post-date information effectively reduces the length of permalinks. Shorter permalinks provide greater usability for both humans and machines: people may find such URLeasier to read, while search engines may interpret the permalink as containing a more concentrated array of keywords. Further, search engines such as Google often display a limited number of characters in their search results. Elimination of expendable characters from your URLs results in more (if not all) of your actual post title being displayed to people as they scan the search results. Finally, shorter permalinks are simply easier to work with. They are easier to share, require (slightly) less bandwidth, and look considerably cleaner.

So, as we make our way into 2008, it appears that it is time to evolve our permalinks toward cleaner, shorter, more concise formats, with redundant information such as “year/month/day” either entirely omitted or dutifully removed. If you are setting up a new WordPress-powered site, and have not yet decided on a permalink structure, I would highly advise against inclusion of date information. Likewise, if you are running an established site that has been using dated permalinks for any length of time, you may want to join fellow bloggers such as Rick Beckman and remove the dates from your URLs.

How to remove the “year/month/date” portion of dated permalinks

Although there are free WordPress plugins available for changing your permalinks, we prefer to handle URL redirection withApache/htaccess rather than PHP because it requires fewer system resources and is executed with greater speed. One final note before we begin: the purpose of this tutorial involves removing date information from all future permalinks and redirecting allpreexisting permalinks to their restructured counterparts. Thus, if you are setting up permalinks for a new blog (or one with only a few posts), the second part of this tutorial may not be required — a simple change of permalink structure via the WP Admin (as explained below) may be all that is needed. That said, let’s begin..

Part 1: Update your WordPress Options

The first step in creating “post-name-only” permalinks is to update your WordPress permalink structure in the Permalinks Options page of the WordPress Admin. Using the Custom structure option, customize your permalink structure as follows:

/%postname%/

After entering the post-name-only permalink structure, save the changes and test your pages. Remember to check different types of views — home, single, archive, page, search, etc. — to ensure that your new permalinks are working as expected. Once this is done, all future posts will feature the dateless permalink structure. In the second part of our tutorial, we will redirect all requests for old versions of your URLs to their newly configured counterparts.

Part 2: Update your htaccess file

The second step in creating “post-name-only” permalinks involves modifying your root or subdirectory htaccess file to ensure that old permalinks are redirected to, and served as, your new permalinks. Examine each of the scenarios described below, determine which method applies to your specific setup, and implement the required steps.

Option 1: Remove “year/month/day” from permalinks with WordPress installed in the ROOT directory

This method removes the “year/month/day” portion of permalinks for blogs located within the domain’s root directory. So, for example, if your old permalinks looked like this:

http://domain.tld/2008/08/08/post-title/

..then the htaccess code provided in this section will transform them into this:

http://domain.tld/post-title/

Locate your blog’s permalink htaccess rules. Then, place the following code directly after the line containing the RewriteBasedirective:

# remove all permalink date info for blog in root directory RewriteRule ^([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/([^/]+)/?$ http://domain.tld/$4/ [R=301,L]

Remember to edit the “domain.tld” to match that of your own. No other changes are necessary. Test like crazy. After verifying that everything works as intended, sit back and enjoy your new optimized permalinks!

Option 2: Remove “year/month/day” from permalinks with WordPress installed in SUBDIRECTORY

This method removes the “year/month/day” portion of permalinks for blogs located within a subdirectory. So, for example, if your old permalinks looked like this:

http://domain.tld/subdirectory/2008/08/08/post-title/

..then the htaccess code provided in this section will transform them into this:

http://domain.tld/subdirectory/post-title/

Locate your blog’s permalink htaccess rules. Then, place the following code directly after the line containing the RewriteBasedirective:

# remove all permalink date info for blog in subdirectory RewriteRule ^([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/([^/]+)/?$ http://domain.tld/subdirectory/$4/ [R=301,L]

Remember to edit the “domain.tld/subdirectory” to match that of your own. No other changes are necessary. Test like crazy. After verifying that everything works as intended, sit back and enjoy your new optimized permalinks!

Option 3: Remove “year/month” from permalinks with WordPress installed in ROOT directory

This method removes the “year/month” portion of permalinks for blogs located within the domain’s root directory. So, for example, if your old permalinks looked like this:

http://domain.tld/2008/08/post-title/

..then the htaccess code provided in this section will transform them into this:

http://domain.tld/post-title/

Locate your blog’s permalink htaccess rules. Then, place the following code directly after the line containing the RewriteBasedirective:

# remove year and month info from permalinks for blog in root directory RewriteRule ^([0-9]{4})/([0-9]{1,2})/([^/]+)/?$ http://domain.tld/$3/ [R=301,L]

Remember to edit the “domain.tld” to match that of your own. No other changes are necessary. Test like crazy. After verifying that everything works as intended, sit back and enjoy your new optimized permalinks!

Option 4: Remove “year/month” from permalinks with WordPress installed in SUBDIRECTORY

This method removes the “year/month/day” portion of permalinks for blogs located within a subdirectory. So, for example, if your old permalinks looked like this:

http://domain.tld/subdirectory/2008/08/post-title/

..then the htaccess code provided in this section will transform them into this:

http://domain.tld/subdirectory/post-title/

Locate your blog’s permalink htaccess rules. Then, place the following code directly after the line containing the RewriteBasedirective:

# remove year and month info from permalinks for blog in subdirectory RewriteRule ^([0-9]{4})/([0-9]{1,2})/([^/]+)/?$ http://domain.tld/subdirectory/$3/ [R=301,L]

Remember to edit the “domain.tld/subdirectory” to match that of your own. No other changes are necessary. Test like crazy. After verifying that everything works as intended, sit back and enjoy your new optimized permalinks!

Option 5: Remove the “year” from permalinks with WordPress installed in ROOT directory

This method removes the “year” portion of permalinks for blogs located within the domain’s root directory. So, for example, if your old permalinks looked like this:

http://domain.tld/2008/post-title/

..then the htaccess code provided in this section will transform them into this:

http://domain.tld/post-title/

Locate your blog’s permalink htaccess rules. Then, place the following code directly after the line containing the RewriteBasedirective:

# remove year info from permalinks for blog in root directory RewriteRule ^([0-9]{4})/([^/]+)/?$ http://domain.tld/$2/ [R=301,L]

Remember to edit the “domain.tld” to match that of your own. No other changes are necessary. Test like crazy. After verifying that everything works as intended, sit back and enjoy your new optimized permalinks!

Option 6: Remove “year” from permalinks with WordPress installed in SUBDIRECTORY

This method removes the “year” portion of permalinks for blogs located within a subdirectory. So, for example, if your old permalinks looked like this:

http://domain.tld/subdirectory/2008/post-title/

..then the htaccess code provided in this section will transform them into this:

http://domain.tld/subdirectory/post-title/

Locate your blog’s permalink htaccess rules. Then, place the following code directly after the line containing the RewriteBasedirective:

# remove year info from permalinks for blog in subdirectory RewriteRule ^([0-9]{4})/([^/]+)/?$ http://domain.tld/subdirectory/$2/ [R=301,L]

Remember to edit the “domain.tld/subdirectory” to match that of your own. No other changes are necessary. Test like crazy. After verifying that everything works as intended, sit back and enjoy your new optimized permalinks!

I wanted to change my Word­Press perma­link set­tings from being date and name based to some­thing which was sim­ply name based.

Why did I want to do this?

  1. Perma­links would be shorter; remov­ing the date infor­ma­tion results in URIs which are eleven char­ac­ters shorter.
  2. Perma­links would not only be more read­able, they would be more mean­ing­ful to humans; dates aren’t as impor­tant as the con­tent the page itself con­tains. If pre­sented with a list of perma­links from this site, users should have a good idea of what they’ll get when they click them. There’s no rea­son to muddy those waters by inject­ing date infor­ma­tion into the mix, dilut­ing the impact of the domain and post slug.
  3. The con­tent part of the perma­links (domain name + post slug) would carry more impact in var­i­ous search engines, with­out date infor­ma­tion (that may or may not be rec­og­nized as dates by search engine algo­rithms) dilut­ing the value of what­ever key­words may be present.
  4. Yes, this is a blog, and yes infor­ma­tion is posted chrono­log­i­cally; how­ever, this isn’t a novel, and the mate­r­ial here need not be read in a chrono­log­i­cal man­ner in order to under­stand it. Hav­ing date-based perma­links cre­ates the illu­sion that the date the mate­r­ial was posted is more impor­tant than it really is. Besides, posts are dis­played with the date any­way; why give it to the user twice when I’m bet­ting the date included with the post is glanced over by most users.

404! You broke the Inter­net! File not found! It’s the end of the world as you know it!

But don’t worry, you can feel fine about it because I have a solu­tion, pro­vided that you are using Apache as your server envi­ron­ment (chances are, you are) and mod_alias is enabled (I’m unsure how com­mon it is). We’ll be fix­ing our prob­lem using the RedirectMatch direc­tive of mod_alias.

  1. Down­load your blog’s pri­mary .htaccess file; most likely, it’ll be in the same direc­tory as your blog’s wp-config.php file.
  2. Open it up, and find Word­Press’ perma­links code. If you’ve never edited your .htaccess file before, it will most likely be the only code present. The code looks like this, give or take a line break:
    # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
  3. Before that Word­Press code, you’ll want to add one of the following:
    • If your Word­Press is installed in your domain’s root direc­tory (e.g., example.com/wp-config.php), add this code, adjust­ing example.com to your proper domain name:
      RedirectMatch permanent ^/[0-9]{4}/[0-9]{2}/[0-9]{2}/([a-z0-9\-/]+) http://example.com/$1
    • If your Word­Press is installed in a sub­di­rec­tory of your domain (e.g.,example.com/blog/wp-config.php), add this code, adjust­ing example.com/blog to your proper domain name and directory:
      RedirectMatch permanent /blog/[0-9]{4}/[0-9]{2}/[0-9]{2}/([a-z0-9\-/]+) http://example.com/blog/$1
  4. Save & upload the .htaccess file, and revisit one of your older date-based perma­links. If all went accord­ing to plan, you should be seam­lessly redi­rected to your new name-based permalinks.

That’s all there is to it! If any­one can pro­vide a bet­ter means, I’m open to it, but I’ve tested this out, and it works exactly as I want it to — posts work, paged posts work, pages work, and so on. I can’t promise this won’t break any Word­Press plu­g­ins, so be pre­pared to give up this method (which is as easy as delet­ing what­ever you add to .htaccess and switch­ing your perma­link struc­ture back).

For the curi­ous, this is what the code above does, piece by piece:

Redi­rect­Match
Begins the call to Apache’s mod_alias module.
per­ma­nent
Sends the client (i.e., the user, whether human or robot) instruc­tion that this redi­rect is a per­ma­nent redi­rect and that the old address is invalid and should be from now on replaced with the new.
^/[0–9]{4}
The address which we’re try­ing to match begins with a four-digit year stamp, so we first look for a slash fol­lowed by four numbers.
/[0–9]{2}
The address will next have a two-digit month stamp, so we check for another slash fol­lowed by two numbers.
/[0–9]{2}
The address will next have a two-digit day stamp, so we check for yet another slash fol­lowed again by two numbers.
/([a-z0-9\-/]*)
The address will then have the post slug, which can con­sist of a vari­ety of low­er­case let­ters, num­bers, and dashes. So we look for any num­ber of those. A post slug may include addi­tional infor­ma­tion after it, such as a page num­ber on paged posts, so we include any num­ber of slashes in our search as well. It’s enclosed in paren­the­ses so we can cap­ture that data and use it in the next section.
http://example.com/$1
This is the loca­tion of where we want to redi­rect to. The $1 at the end will be replaced by what­ever was matched by the code in paren­the­ses in the pre­vi­ous statement.

SEO Friendly jQuery Tips

jQuery is a JavaScript library that has seen a massive growth in usage other the last couple of years as it allows developers to code functionality into their webpages to turn their static HTML into a much more dynamic User Interface. However there are a few pitfalls in using jQuery (or any javascript for that matter) that can have a detrimental effect on the Search Engine Optimisation of your page, in this post I will look to outline a few tips that should help you avoid these so that your page not only has a great User Interface but your search engine rankings stay high aswell. Not only should these tips help with SEO but can also have good accessibility benefits too, something that is making a resurgence with users accessing the web from an increasing variety of devices.

1. Streamline your (x)HTML

Many jQuery based features I have come accross involve a lot of extra HTML tags used for the UI that is not irrelevant as far as the search engine spiders are concerned. There are two main ways to ensure your HTML is slimmed down:

a) Dynamically add elements after the page load.

The principle of this is that the HTML served up to javascript free users and arguably more importantly the search engine spiders contains just the basic content, code required for the workings of your UI are then added in dynamically after the page is loaded (or better yet only when it is needed).

Below is an example to add a callback form to the page after the page has loaded.

01.$(function(){
02.
03.var contactForm = ‘<form action=”formhandler.php” method=”post”>’
04.
05.+’<label for=”name”>Name</label><input type=”text” name=”name” />’
06.
07.+’<label for=”phone”>Phone Number</label><input type=”text” name=”phone”/>’
08.
09.+’</form>’;
10.
11.$(“body”).append(contactForm);
12.
13.});

In this example the HTML code is atually written within the JavaScript which isn’t exactly best practice, we can get away with it in this instance as there are only a few lines of code, however for longer chunks of code you should consider using an AJAX call to load the content.

b) Optimise the structure to remove unnecessary code.

Even better than adding code dynamically its removing it all together if it is not needed, one of the main cause of excess code is divitis , so have a look through your code and see if you really need that wrapper div or with a bit of clever CSS can you target the content in a different way?

2. Avoid blank/useless links

All too often the button/trigger used for a jQuery event is an anchor tag with a href that points nowhere, or worse still contains the javascript call, for example:

1.<a href=”#” onclick=”myfunction(); return false”>My button</a>
2.
3.<a href=”javascript:myfunction();”>My Button</a>

A better method is to use some other element such as a span as the trigger then dynamically add an on click listener.

HTML:

1.<span id=”myButton”>My Button</span>

Javascript:

1.$(“#myButton”).click(function(){ myfunction(); });

Of course there are times when using an anchor tag is fine as the trigger, such as if the jQuery script is providing an alternative on page option to the page at which the link is pointed. An example of which would be launching a pop up contact form when clicking on a link pointing to the contact form page. This way non-JavaScript users go through to the contact page and fill out the form on there, while javascript users get the alternative pop up form saving a page load. In such instances though it may be worth considering if such links should be nofollow.

3. Always offer a non-JavaScript version of any relevant content

This may seem slightly contradiction of the previous points, however if any SEO relevant content is not available when your script is disabled then it is likely the search engine spiders cannot find it. For example if you are loading relevant content via AJAX then from an SEO point of view it is useful to have a link to a static version of this content on the page too.

4. Code your javacript to fit your HTML and not the other way round.

When coding a page I always try to code a static version of the page then from this foundation code any javascript based around this markup and only add in any extra html tags etc if and when absolutely necessary (and where possible adding such markup dynamically as per point 1).  Developing your page this way is one of the fundamental principles of progressive enhancement which has not only accessibility benefits but also SEO benefits.

For example if you want to have tabbed content on the page it is best that the basic page just has the content of all the tabs one after the other then use jQuery to assign CSS classes and eventHandlers on page load to change collapse the content you want hidden to start with, this way if the page is loaded without javascript then all the content is still visible.

5. Keep your script to external files

It is an age old one but is still relevant as ever, keep your javscript out of your HTML page and in an external javascript file refernced in the head.

1.<script src=”myScript.js” type=”text/JavaScript” ></script>

It may have been a case in the past that you needed to drop blocks of JavaScript in the mark-up elsewhere in the code as to ensure it is only executed once an element had been written into the DOM. However using the ready() function of jQuery you can keep the code in external files and will only execute once the required element has loaded.

Multilingual SEO

Google has recently done a series on the usability of multilingual websites and it got me thinking about multilingual SEO. How do you, in fact, optimize the same website for keywords in multiple languages?

Multilingual SEO: Things to Remember

But let’s start with the core basics. In simple terms, a multilingual website is a website that has content in more than one language. And such website has a lot of on-page stuff that is often done wrong. Let’s take a look at some common issues:

1) Language recognition

Once Google’s crawler lands on your multilingual website, it starts with determining the main language on every page. Google can recognize a page as being in more than one language but you can avoid crawler confusion by doing the following:

  • Stick to only one language per page
  • Avoid side-by-side translations
  • Use the same language for all elements of the page: headers, sidebars, menus, etc.

Some web editors create code-level attributes automatically but these attributes are not very reliable, so keep in mind that Google ignores all code-level information (from “lang” attributes to DTD (Document Type Definitions) during language recognition.

2) URL structure

A typical pet peeve of SEO but even more so with multilingual websites. To make the most of your URLs, consider language-specific extensions. Language-specific extensions are often used on multilingual websites to help users (and crawlers) identify the sections of the website they are on and the language the page is in. For example:

http://www.website.ca/en/content.html

http://www.en.website.ca/content.html

http://www.website.ca/fr/content.html

http://www.fr.website.ca/content.html

This is a great way to organize URLs on a multilingual website because not only does it help the user, but it also makes it easier for the crawler to analyze the indexing of your content. But what if you want to create URLs with characters other than English? Here’s how to do it right:

  • Use UTF-8 encoding for non-English characters
  • Make sure your UTF-8 encoded URLs are properly escaped when linked from within your content

i.e. if a URL contains an é, which is a non-English character: http://www.website.ca/fr/contént.html

here’s how it will look properly escaped: http://www.website.ca/fr/cont%C3%A9nt.html

It is important to note that Google directly extracts character encodings from HTTP headers, HTML page headers, and content. There isn’t much you need to do about character encoding, other than watching out for conflicting information – for example, between content and headers. While Google can recognize different character encodings, use UTF-8 on your website whenever possible.

3) Crawling and Indexing

Another common area of focus for SEO. On multilingual websites, follow these recommendations to get more pages crawled:

  • Avoid redirects based on user’s perceived language: they could, in fact, prevent both users and SEs from looking at more pages on your site.
  • Keep the content for each language on separate URLs
  • Don’t use cookies to show translated page versions
  • Cross-link page by page

Last but not least, please remember that Google does not recommend automatic translations.

By getting the on-page basics right, you will set a great base for your multilingual SEO in the future and, unlike so many others, you will not have to beg (in multiple languages) SE crawlers to come and index your content.