Russ Back
Russ Back

Reputation: 923

Avoiding multiple Apache redirects for multiple rules

I have a need to put some redirects in place to enforce some rules and handle some URL changes.

Specifically as follows:

  1. If the protocol is http, enforce https
  2. If there is no subdomain or the subdomain is not www, enforce www
  3. If the domain is www.domainA.com and the path does not begin with /en/, /fr/, /de/ or /es/, enforce /en/
  4. If the domain is www.domainB.com and the path does not begin with /b_en/, /b_fr/, /b_de/ or /b_es/, enforce /b_en/

I've been trying to get this working so that only one 301 happens at any one time and we don't end up with a chain of 301s. For example a request to http://domainA.com could potentially be redirected 3 times:

  1. http://domainA.com 301 to...
  2. https://domainA.com 301 to...
  3. https://www.domainA.com 301 to...
  4. https://www.domainA.com/en/

However I've not been able to come with a solution.

This would live in a .htaccess file.

Upvotes: 0

Views: 204

Answers (1)

Croises
Croises

Reputation: 18671

You can use in your .htaccess:

# domainA
RewriteCond %{HTTP_HOST} domainA\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/(?:en|fr|de|es) [NC]
RewriteRule ^ https://www.domainA.com/en%{REQUEST_URI} [NE,L,R=301]

# domainB
RewriteCond %{HTTP_HOST} domainB\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/b_(?:en|fr|de|es) [NC]
RewriteRule ^ https://www.domainB.com/b_en%{REQUEST_URI} [NE,L,R=301]

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

Never more than one redirection.

Upvotes: 1

Related Questions