zecaluis
zecaluis

Reputation: 155

Force www and redirect root directory

I couldn't find a question that answered mine, or maybe I couldn't search using the right terms, but come on. I have the following rule in my htaccess:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com\.br$ [OR]
RewriteCond %{HTTP_HOST} ^www\.domain\.com\.br$
RewriteRule ^(.*)$ "https\:\/\/www\.domain\.com\.br\/site" [R=301,L]

This works when the user enters only the URL (domain.com.br or www.domain.com.br), but I need it to redirect when the user accesses this way:

domain.com.br or www.domain.com.br --> https://www.domain.com.br/site
domain.com.br/XXX --> https://www.domain.com.br/XXX

What rule should I use for this?

Update: the server already has a default rule to force SSL, in which case it is unnecessary to put it in htaccess

Rule update:

**On virtual host:**
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

**On htaccess file:**
RewriteCond %{HTTP_HOST} ^domain\.com\.br$ [OR]
RewriteCond %{HTTP_HOST} ^www\.domain\.com\.br$
RewriteRule ^/?$ https://www.domain.com.br/site/ [R=301,L]

Upvotes: 2

Views: 199

Answers (1)

Justin Iurman
Justin Iurman

Reputation: 19016

Your code generates a redirect loop. Also, you don't need to escape slashes on targets.

You could merge everything inside your virtual host block (faster than using a htaccess):

RewriteEngine On

# force https
RewriteCond %{HTTPS} off [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# force www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# redirect root directory to /site/
RewriteRule ^/?$ /site/ [R=301,L]

Of course, you will see a redirect chain for e.g. http://domain.tld/ as it will first redirect to https://domain.tld/ then to https://www.domain.tld/ and finally to https://www.domain/tld/site/. This is fine. However, if you really want to handle everything with only one redirect, you could. But, it will be less generic.

For instance, you would end up with those rules:

RewriteEngine On

# force root directory to /site/ (https+www)
RewriteRule ^/?$ https://www.domain.com.br/site/ [R=301,L]

# force any other pages to https+www if not the case already
RewriteCond %{HTTPS} off [NC,OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.domain.com.br%{REQUEST_URI} [R=301,L]

Upvotes: 1

Related Questions