Redirections with .htaccess file
Redirect the entire site (permanently)
Redirect 301 / https://newsite.com
Redirect a single page
Redirect 301 /oldpage.html https://newsite.com/newpage.html
You can specify any 3xx
redirection code. Here is a list
Redirect an old domain to a new domain
RewriteEngine On
RewriteCond %{HTTP_HOST} ^mydomain.com [OR]
RewriteCond %{HTTP_HOST} ^www.mydomain.com [OR]
RewriteRule ^(.*)$ https://www.newdomain.com/$1 [L,R=301,NC]
If the requested page (condition) is not /wp-admin
, /wp-login
or wp-json
, redirect it (rule) to the the new domain while keeping the path intact (because we are checking for REQUEST_URI
)
REQUEST_URI
is the path component of the requested URI, such as “/index.html”. It does not include the domain before or the query string after- a
RewriteRule
comes after one or manyRewriteCond
s and must much all the specified conditions bpreceding it in order to work
Redirect an old domain to new domain, except a few pages
RewriteEngine On
RewriteCond %{REQUEST_URI} !^(/wp-admin)$
RewriteCond %{REQUEST_URI} !^(/wp-login)$
RewriteCond %{REQUEST_URI} !^(/wp-json)$
RewriteRule ^(.*)$ https://www.newdomain.com/$1 [L,R=301,NC]
NOTES
RewriteCond
only applies to theRewriteRule
immediately following it(.*)
is different from/(.*)
./(.*)
will match everything after the first/
(excluding domain) while(.*)
will match the entire URL (including domain)
RewriteCond directives
- the
$1
is a backreference. It matches the first grouped part (in parantheses) of the pattern. It is a reference that you can specify in theRedirectRule
orRedirectCond
and will match that rule/cond - Matches in the regular expressions contained in the
RewriteCond
s can be used as part of the Substitution in theRewriteRule
using the variables%1
,%2
, etc.
Common rewrite flags
- Flags aren’t supposed to conatin spaces.
[R=301,NC,L]
, not[R=301, NC, L]
. Spaces between flags is likely to get you a bad flag delimiters error R=301
is for permanent redirectL
is to makemod_rewrite
stop processing the rule set. If the rule matches, don’t process any further rules- If you’re using
R
, useL
as well to make sure you don’t get Invalid URI in request warnings. NC
is for no case, meaning do a case-insensitive match