Apache mod_rewrite : rewrite or redirect if page not found using specific criteria
The following article provides details and examples for using Apach mod_rewrite (.htaccess) to rewrite or redirect requests based on specific criteria, such as the inclusion of "www" before the TLD (Top Level Domain), and rewriting requests to load a page with query string paramaters taken from compnents of the request.
Apache mod_rewrite (.htaccess) - Rewrite or Redirect Request URLs if page not found, or no www.
Mod_rewrite examples:Redirect to include www in the host: - Redirect "domain.com" to "www.domain.com"
Code:
RewriteBase /
RewriteCond %{HTTP_HOST} !^www(.*)
RewriteRule ^(.*) http://www.%{HTTP_HOST}%{REQUEST_URI} [R]
Rewrite request components to use as Query String paramaters for a specific page:- Rewrite "www.domain.com/display/2009/10/" to "www.domain.com/display.php?y=2009&m=10"
Code:
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^display/([0-9][0-9][0-9][0-9])/([0-9][0-9])(/?) display.php?y=$1&m=$2 [L]
Redirect to to site root if page not found:- Redirect 404 error (Page not Found) to root of domain ( "www.domain.com/non-existent-page" redirects to "www.domain.com/" )
Code:
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) http://%{HTTP_HOST} [R]
For more information, and more detailed examples of how and when to use Apache mod_rewrite to rewrite and redirect requests, see
Apache mod_rewrite (.htaccess) - Rewrite or Redirect Request URLs if page not found, or no www.