Latest TweetsTheme update! shapeSpace v2.4 #WordPress #theme
Perishable Press

.htaccess Redirect Examples

Finally put together a giant list of .htaccess redirect examples. It’s meant as a quick copy-&-paste resource for those who may be looking for an assortment of redirect techniques. Here you will find redirects via mod_alias and mod_rewrite. Examples include redirecting to and from any directory, subdirectory, resource, URL, and much more. Most of these examples are taken from my previous article, Stupid htaccess Tricks; other examples are taken from previous .htaccess tutorials here at Perishable Press. Enjoy! :)

Redirect via mod_alias

These examples show how to redirect from one location to another using Apache’s alias module. Also, you can change the status code to whatever you want (for example, change from 301 to 302). And then learn how to go further with even more awesome .htaccess redirect examples.

Redirect a page on same domain

Redirect 301 /page.php /page.html

Redirect a page on different domain

Redirect 301 /page.php

Redirect an entire site

Redirect 301 /

Redirect entire site to subdirectory

Redirect 301 /

Redirect from subdirectory to another site

Redirect 301 /subdirectory

Redirect from .html to .php

RedirectMatch 301 (.*)\.html$1.php

Forbid access to a page

Redirect 403 /page.html

Tell visitors a page is gone

Redirect 410 /page.html

Redirect via mod_rewrite

If you need more power, Apache’s rewrite module can do much more in terms of redirecting. Here are some examples:

Redirect from old page to new page

RewriteRule ^/old-page/?$ /new-page/ [R=301,L]

Redirect all paths from old domain to same paths on new domain

RewriteRule (.*)$1 [R=301,L]

Redirect all paths from old domain to homepage of new domain

RewriteRule (.*) [R=301,L]

Redirect new domain with query string

RewriteRule (.*){REQUEST_URI} [R=301,L]

Redirect new domain subdirectory with query string

RewriteCond %{REQUEST_URI} ^/subdirectory/(.*) [NC]
RewriteRule (.*) [R=301,L]

Redirect URLs with ID query parameter

RewriteCond %{QUERY_STRING} ID=([0-9]+) [NC]
RewriteRule ^/index\.php /newpath/? [R=301,L]

Redirect URLs from subdirectory with ID query parameter

RewriteCond %{QUERY_STRING} ID=([0-9]+) [NC]
RewriteRule ^/subdirectory/index\.php /newpath/? [R=301,L]

Remove www from all URLs

RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule (.*)$1 [R=301,L]

Require www for all URLs

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule (.*)$1 [R=301,L]

Status Code

Note: You can change the status code (i.e., server response) for any of the previous redirects (either via mod_alias or mod_rewrite). Simply change the current 301 status to any of the following:

  • 301 — Permanent redirect
  • 302 — Temporary redirect
  • 403 — Forbidden
  • 410 — Gone
  • Any other valid status code

Jeff Starr
About the Author Jeff Starr = Fullstack Developer. Book Author. Teacher. Human Being.
Drop a Comment  ]