Redirections with .htaccess file
October 30, 2019
Redirect the entire site (permanently)
code
Redirect 301 / https://newsite.com
Redirect a single page
code
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
code
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_URIis the path component of the requested URI, such as "/index.html". It does not include the domain before or the query string after- a
RewriteRulecomes after one or manyRewriteConds and must much all the specified conditions bpreceding it in order to work
Redirect an old domain to new domain, except a few pages
code
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
RewriteCondonly applies to theRewriteRuleimmediately following it(.*)is different from/(.*)./(.*)will match everything after the first/(excluding domain) while(.*)will match the entire URL (including domain)
RewriteCond directives
- the
$1is a backreference. It matches the first grouped part (in parantheses) of the pattern. It is a reference that you can specify in theRedirectRuleorRedirectCondand will match that rule/cond - Matches in the regular expressions contained in the
RewriteConds can be used as part of the Substitution in theRewriteRuleusing 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=301is for permanent redirectLis to makemod_rewritestop processing the rule set. If the rule matches, don't process any further rules- If you're using
R, useLas well to make sure you don't get Invalid URI in request warnings. NCis for no case, meaning do a case-insensitive match