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 (opens in a new tab) which essentially supercharges your
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:
In the examples below, every time we'll add rules underneath
301 redirecting a single URL
The rule below 301 redirects
301 redirecting a single folder
The rule below 301 redirects the entire
/blog/ subfolder to
Check your website for excessive redirects, and incorrect configurations right now!
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:
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:
301 redirecting to another domain
If you want to 301 redirect to another domain, use these rules:
Do a quick check, and find out right away!