Gaurav
Gaurav

Reputation: 1972

Prevent double 301 redirects in .htaccess?

Here is my current .htaccess file code.

  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteCond %{HTTPS} off

  # First rewrite to HTTPS:
  # Don't put www. here. If it is already there it will be included, if not
  # the subsequent rule will catch it.
  RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

  # Now, rewrite any request to the wrong domain to use www.
  RewriteCond %{HTTP_HOST} !^www\.
  RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Note : I have checked this question - Remove double 301 redirect from my htacess? But it doesn't apply here as there is no Redirect in this code.

Upvotes: 1

Views: 953

Answers (1)

anubhava
anubhava

Reputation: 786061

You can use this rule to avoid double 301 redirect:

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

Make sure to clear your browser cache before testing.

Upvotes: 3

Related Questions