URL Redirect Examples

Examples of URL Redirects
Permanent redirect after moving pages to a different directory
/old-path/.htaccess
RewriteEngine On

RewriteCond %{REQUEST_URI} ^/old-path/(.*)$ [NC]
RewriteCond %{DOCUMENT_ROOT}/new-path/%1 -f
RewriteRule ^(.*)$ /new-path/$1 [R=permanent,L]

RewriteRule ^(.*)$ /new-path/ [R=permanent,L]
Permanent redirect to fix extensions after converting them from DOS 8.3 names to long names
/path/.htaccess
DirectoryIndex index.html

RewriteEngine On

RewriteRule ^(.+).htm$ /path/$1.html [NC,R=permanent,L]
Permanent redirect after moving a single page to a new location
/old-path/.htaccess
RewriteEngine On

RewriteRule ^old-page.html$ /new-path/new-page.html [NC,R=permanent,L]

Any regular expression metacharacters in the RewriteRule must be escaped with a backslash (\). See Regular Expression Metacharacters above for the list of characters that need to be escaped. Therefore, in the following example, the plus sign (+) has been escaped:

/old-path/.htaccess
RewriteEngine On

RewriteRule ^Google\+-Terminology.html$ /Blog/Entries/2011/7/23_Terminology_on_Google_Plus.html [NC,R=permanent,L]
http://www.spitballs.com/Blog/Entries/2011/7/23_Terminology_on_Google_Plus.html
URL redirect to a PHP script
/doc-root/.htaccess
RewriteEngine On

RewriteCond %{REQUEST_URI} !\.php
RewriteCond %{REQUEST_URI} ^/(.+)$
RewriteCond %{DOCUMENT_ROOT}/%1 !-d
RewriteCond %{DOCUMENT_ROOT}/%1 !-f
RewriteRule ^([^/]+)$ /index.php?url=$1 [R=307,L]

Here is a line-by-line explanation of that code:

  1. Line 1 eliminates the index.php file right off the bat, to avoid redirecting requests to the script itself.
  2. In line 2, the %{REQUEST_URI}% will start with a "/" but it is not included in the subpattern, so the %1 back reference will not include the leading "/".
  3. Line 3 makes sure a directory does not exist at the requested URL.
  4. Line 4 makes sure a file does not exist at the requested URL.
  5. Line 5 does an HTTP 307 Temporary Redirect to the index.php script with the original URL path as the url parameter in the query part of the rewritten URL.