Redirects with .htaccess

Published

Updated

Route traffic with smart redirects.

Redirect URLs with `mod_rewrite` in `.htaccess`: send all domains to the primary one and move single pages. fortrabbit redirects HTTP to HTTPS on its own, no rule needed.

HTTPS needs no rule

fortrabbit answers every request on http:// with a 301 redirect to https://, for every domain of the environment. Rules that force HTTPS with X-Forwarded-Proto or %{HTTPS} are not needed. To keep browsers from trying http:// at all, add HSTS.

Redirect to the primary domain

The default domain and every other domain of the environment serve the same content. Send them all to the primary domain, so search engines index one address.

For a domain added in the dashboard, such as example.com next to www.example.com, the domain forwarding service sends the 301 without any .htaccess rule. Redirect the default domain in .htaccess, once the primary domain works:

RewriteEngine On
RewriteCond %{HTTP_HOST} \.frbit\.app$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]
apache
.htaccess

After that, the default domain no longer works for testing. Place the rule at the top of the file, above the framework's front controller rules. Many CMS also set a canonical URL; point it to the primary domain as well.

Redirect a moved page

RewriteEngine On
RewriteRule ^old-page/?$ /new-page [R=301,L]
RewriteRule ^blog/(.*)$ /news/$1 [R=301,L]
apache
.htaccess

The pattern matches the path without the leading slash, relative to the folder of the .htaccess file. Redirect 301 /old-page /new-page from mod_alias works as well, but runs after all RewriteRule lines, so a front controller rule can catch the request first.

301 or 302

R=301 sends a permanent 301 redirect. Browsers cache it, so a wrong 301 stays in visitors' browsers after the rule is fixed. Use R=302, a temporary 302 redirect, while testing, and switch to 301 once the rule works. Test with curl -I, which ignores the browser cache.

Written by humans and AI in collaboration.

AI use & editorial processEdit on GitHub ↗