Notes

Redirections with .htaccess file

Edit on GitHub

System Administration
2 minutes

Redirect the entire site (permanently)

1Redirect 301 / https://newsite.com

Redirect a single page

1Redirect 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

1RewriteEngine On
2
3RewriteCond %{HTTP_HOST} ^mydomain.com [OR]
4RewriteCond %{HTTP_HOST} ^www.mydomain.com [OR]
5RewriteRule ^(.*)$ 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 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

1RewriteEngine On
2
3RewriteCond %{REQUEST_URI} !^(/wp-admin)$
4RewriteCond %{REQUEST_URI} !^(/wp-login)$
5RewriteCond %{REQUEST_URI} !^(/wp-json)$
6RewriteRule ^(.*)$ https://www.newdomain.com/$1 [L,R=301,NC]

NOTES

  • 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