Is it necessary to keep the HTTPS RewriteRule after a 301 Redirect?

Viewed 135

I've managed to do a wildcard 301 redirect successfully, but I'd like to know if it is necessary to keep the rewrite rule forcing HTTPS and if the order of the code in the .htaccess file matters.

For example, I should do a redirect chain like http://oldsite.com to https://oldsite.com to https://newsite.com

This is the .htacess file on the old site:

# HTTPS forced by SG-Optimizer
<IfModule mod_rewrite.c>
    RewriteEngine On
    
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
# END HTTPS

#REDIRECT
Redirect 301 / https://newsite.com/
#END REDIRECT
1 Answers

First, it is a bad idea to mix mod_rewrite directives with Redirect or RedirectMatch directives as these are different modules in Apache and different modules are executed in different order.

Second, you should also avoid causing multiple redirects in browser as that is considered bad user experience and will also cause unnecessary burden on your web server.

You should place your specific redirect rule before generic http -> https redirect like this:

<IfModule mod_rewrite.c>
    RewriteEngine On
    
    #REDIRECT
    RewriteCond %{HTTP_HOST} ^(?:www\.)?oldsite\.com$ [NC]
    RewriteRule ^ https://newsite.com%{REQUEST_URI} [L,NE,R=301]
    #END REDIRECT

    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
# END HTTPS

This way all the traffic for oldsite.com is redirected to https://newsite.com in single redirect.

Your http -> https redirect will be executed only if you are supporting any other site other than oldsite.com.

Related