How do I 301 redirect URLs with an .htaccess file on Apache?
Among other things, the .htaccess
file on Apache handles (301 redirects). In it, you can implement redirects for entire sites, whole sections or just a few URLs.
In this article we'll discuss the most common use-cases of redirecting using the .htaccess
file, including working code snippets.
What you need to get started
You need to use RewriteEngine
, which is part of the modrewrite module which essentially supercharges your .htaccess
file.
The modrewrite module
is loaded by default in Apache, but if it's not being loaded, make sure you specifically load it in your Apache configuration using the following directives:
<IfModule mod_rewrite.c> RewriteEngine On </IfModule>
In the examples below, every time we'll add rules underneath RewriteEngine On
.
301 redirecting a single URL
The rule below 301 redirects /old-page/
to /new-page/
:
RedirectMatch 301 /old-page/ /new-page/
301 redirecting a single folder
The rule below 301 redirects the entire /blog/
subfolder to /news/
:
RewriteRule ^/?blog/(.\*)$ /news/$1 [R,L]
301 redirecting non-www to www
When visitors and search engines request URLs without the www
subdomain, you want to forward them to the URL that does contain the www
subdomain with these rules:
RewriteCond %{HTTP_HOST} \*!^www\*.example.com [NC] RewriteRule (.\*) http://www.example.org/$1 [L,R=301]
301 redirecting www to non-www
If you don't want to use the www
subdomain, then you need to redirect visitors and search engines to the non-www URL variant when they request the variant with www
. You can do that with these rules:
RewriteCond %{HTTP_HOST} ^www.example.com$ RewriteRule (.\*) https://example.com/$1 [L,R=301]
301 redirecting to another domain
If you want to 301 redirect to another domain, use these rules:
RewriteEngine on RewriteRule ^(.\*)$ http://example.com/$1 [L,R=301]