.htaccess Redirect Examples

Examples on how to redirect using mod_alias and mod_rewrite.

Redirect a single page (same domain)

Redirect 301 /page.php /page.html

Redirect a single page (different domain)

Redirect 301 /page.php https://example.com/page.html

Redirect an entire site

Redirect 301 / https://example.com/

Redirect entire site to a sub-directory

Redirect 301 / https://example.com/subdirectory/

Redirect from a sub-directory to another website

Redirect 301 /subdirectory https://example.com/

Redirect from .html to .php

RedirectMatch 301 (.*)\.html https://example.com/$1.php

Forbid access to a page

Redirect 403 /page.html

Tell visitors a page is gone

Redirect 410 /page.html

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 (.*) https://newdomain.com/$1 [R=301,L]

Redirect all paths from old domain to homepage of new domain

RewriteRule (.*) https://newdomain.com/ [R=301,L]

Redirect new domain with query string

RewriteRule (.*) https://www.newdomain.com/%{REQUEST_URI} [R=301,L]

Redirect new domain sub-directory with query string

RewriteCond %{REQUEST_URI} ^/subdirectory/(.*) [NC]
RewriteRule (.*) https://example.com/%1 [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 sub-directory with ID query parameter

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

www to non-www

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

Non-www to www

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