Wednesday, May 18, 2011

How to Redirects for Web with .htaccess for Developers

Apache and .htaccessThe Apache .htaccess file is used to control access to directories on a web server. As a web developer, it can be useful to know how to use this file for redirecting pages and controlling access to areas of your website. Here’s a few good .htaccess snippets that may help your on some of your web development tasks.

Redirect One Page to Another – Classic 301 Redirect

The classic 301 redirect allows you to direct a page on your site to a page on the same or another website.
RewriteCond %{HTTP_HOST} ^mywebsite.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.mywebsite.com$
RewriteRule ^some\-page\/?$ "http\:\/\/.mywebsite\.com\/" [R=301,L]

Redirect All Pages to One Page

Sometimes you may want to redirect all occurrences of a URL to another website. Rather than writing a bunch of individual 301 redirects you can use regular expressions to point all instances of a url to one location. Example http://www.somesiteA.com -> http://www.somesiteB.com and http://www.somesiteA.com/whatever goes to -> http://www.somesiteB.com
RewriteCond %{HTTP_HOST} ^somewebsite.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.somewebsite.com$
RewriteRule ^ "http\:\/\/www\.somewebsite\.com\/" [R=301,L]

Redirect all Pages to Subdomain

Suppose that you moved your blog to a subdomain from a subdirectory. You’re going to want to implement a global redirect to keep Google happy.
RewriteCond %{HTTP_HOST} ^mywebsite.com [OR]
RewriteCond %{HTTP_HOST} ^www.mywebsite.com$
RewriteRule ^blog$ "http\:\/\/blog\.mywebsite\.com\/catalog" [R=301,L]

Forbid Hotlinking

Don’t like others taking your content and wasting your bandwidth? Prevent hotlinking using .htaccess and forbid other websites from leeching your content.
RewriteCond %{HTTP_REFERER} !^http://example\.net/?.*$ [NC]  
RewriteCond %{HTTP_REFERER} !^http://example\.com/?.*$ [NC]  
RewriteRule \.(gif|jpe?g|png|bmp)$ – [F,NC]
The code above will check the referring site against the sites allowed to access the content. The RewriteRule protects specified file extensions from access from other websites and insteads presents a 403 forbidden page.

Custom 404 Page

It’s always good to have a nice 404 page with useful information to get your visitor back on track. Here’s how to enable a custom 404 page using
# Generic 404 to show the "custom_404.html" page  
# If the requested page is not a file or directory  
# Silent Redirect: the user's URL bar is unchanged.  
RewriteEngine on  
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule .* custom_404.html [L]


No comments:

Post a Comment