Redirections with .htaccess file

Redirect the entire site (permanently)

Redirect 301 /

Redirect a single page

Redirect 301 /oldpage.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} ^ [OR]
RewriteCond %{HTTP_HOST} ^ [OR]
RewriteRule ^(.*)$$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 many RewriteConds 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 ^(.*)$$1 [L,R=301,NC]


  • RewriteCond only applies to the RewriteRule 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 the RedirectRule or RedirectCond and will match that rule/cond
  • Matches in the regular expressions contained in the RewriteConds can be used as part of the Substitution in the RewriteRule 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 redirect
  • L is to make mod_rewrite stop processing the rule set. If the rule matches, don’t process any further rules
  • If you’re using R, use L 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