URL Redirect Code
Code for HTTP URL Redirect
URL redirect to a different extension
/path/.htaccessRewriteEngine On RewriteRule ^(.+).<#ext1#>$ /<#path/#>$1.<#ext2#> [NC,R=permanent,L]
URL redirect to a different page
/old-path/.htaccessRewriteEngine On RewriteRule ^<#old-page.html#>$ /<#new-path/new-page.html#> [NC,R=permanent,L]
URL redirect to a different directory
/old-path/.htaccessRewriteEngine On RewriteRule ^(.*)$ /<#new-path/#>$1 [R=permanent,L]
Although this is the simplest way to redirect all requests to a different directory, it blindly does the redirect to the new page. To verify that the target page exists, include a RewriteCond
with -f
:
RewriteEngine On RewriteCond %{REQUEST_URI} ^/<#old-path/#>(.*)$ [NC] RewriteCond %{DOCUMENT_ROOT}/<#new-path/#>%1 -f RewriteRule ^(.*)$ /<#new-path/#>$1 [R=permanent,L] RewriteCond %{DOCUMENT_ROOT}/<#new-path/#>index.html -f RewriteRule ^(.*)$ /<#new-path/#> [R=permanent,L]
The RewriteCond
with -f
for the first RewriteRule
will verify that the file for the target page exists before doing the redirection there. The %1
back reference in that condition matches the regular expression group ((.*)
) in the RewriteCond
above it. The RewriteCond
for the second RewriteRule
will verify that an index.html file exists before the following RewriteRule does a redirect of any request for a document that does not exist in the new location, including a directory level request for the DirectoryIndex
document. That one can be omitted if you already know that the index.html file exists in the target directory.
URL redirect to a script
/doc-root/.htaccessRewriteEngine On RewriteCond %{REQUEST_URI} !\.<#ext#> RewriteCond %{REQUEST_URI} ^/(.+)$ RewriteCond %{DOCUMENT_ROOT}/%1 !-d RewriteCond %{DOCUMENT_ROOT}/%1 !-f RewriteRule ^([^/]+)$ /index.<#ext#>?url=$1 [R=temp,L]
Here is a line-by-line explanation of that code:
- Line 1 eliminates the index.ext file right off the bat, to avoid redirecting requests to the script itself.
- 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 "/".
- Line 3 makes sure a directory does not exist at the requested URL.
- Line 4 makes sure a file does not exist at the requested URL.
- Line 5 does a temporary redirect (HTTP 302) to the index.ext script with the original URL path as the
url
parameter in the query part of the rewritten URL.
HTTP Status Code Flags in Redirect RewriteRules
- R
- R=temp
- R=302
- Found - use See Other or Temporary Redirect at user agent's discretion
- R=permanent
- R=301
- Moved Permanently (Permanent Redirect)
- R=303
- See Other
- R=307
- Temporary Redirect