Htaccess Redirects Explained: 301 vs 302, Forcing https and www on Apache
Updated December 2026
Written by the Toolpuffin team. Tools in this guide are tested in the browser.
A redirect sends visitors, and search engines, from an old address to a new one. On an Apache server you can set redirects in a file called .htaccess. This guide explains the difference between a permanent and a temporary redirect, shows the usual https rule and tells you how to test before and after.
Try the tool: Htaccess Redirect Generator
Permanent or temporary
| Code | Meaning | Use it for |
|---|---|---|
| 301 | Moved permanently | The old address is gone for good, such as a renamed page or a new domain |
| 302 | Moved temporarily | A short-term detour, such as maintenance |
The Apache documentation says that R=301 issues a permanent redirect, which tells search engines to update their index. IONOS notes that in many setups a redirect without a code becomes a 302, so always give the code yourself.
Source: Apache HTTP Server: Redirecting and Remapping with mod_rewrite
Source: IONOS: Apache redirects
If you are not sure, start with a 302, test, and change it to a 301 when everything works. Browsers remember a 301, so a mistake is harder to undo.
Forcing https
The Apache documentation gives a rule that redirects http to https. In an .htaccess file it looks like this:
| Line | What it does |
|---|---|
| RewriteEngine On | Switches the rewrite engine on. |
| RewriteCond "%{HTTPS}" !=on | Only goes on when the connection is not https. |
| RewriteRule "^(.*)" "https://%{SERVER_NAME}$1" [R=301,L] | Sends the visitor to the https address with a permanent redirect and stops processing rules. |
Behind a load balancer or a CDN, the server may not see that the visitor used https. The documentation then checks the X-Forwarded-Proto header that most load balancers set. The generator has an option for sites behind a CDN or proxy.
www or no www, and moving a site
- Pick one version, with or without www, and redirect the other to it with a 301, so every page has one address.
- When you move a site to a new domain, send each old address to the same page on the new domain.
- The generator makes one redirect per path. Rules that depend on a query string or that match many pages with a pattern have to be written by hand.
Test before and after
- Keep a copy of your current .htaccess before you change it.
- Test in a private window, because browsers remember 301 redirects.
- Look for redirect loops and server errors. If the site breaks, put the old file back.
- Only Apache and servers that read .htaccess files, such as LiteSpeed, use these rules. Nginx ignores them.
The generator cannot test the rules on your server, so test every redirect after you save the file.