kirby-secrets icon indicating copy to clipboard operation
kirby-secrets copied to clipboard

Htaccess redirect to https and www

Open olach opened this issue 7 years ago • 2 comments

For the page Htaccess redirect to https non www I would like to add a code snippet for Htaccess redirect to https *and* www.

# Redirect http to https and add www.
# 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.
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Source: http://stackoverflow.com/a/13997498

I agree that the url looks more nice without www, but in some cases adding www is a better option. For example, if using a url without www, all cookies will be sent to all subdomains. This can slow down access to images and js/css if you use a subdomain as a cdn for static content.

More information here: http://www.yes-www.org/why-use-www/

olach avatar Apr 12 '17 11:04 olach

Have you tested that the code above work? Or did you just copy/paste from Stackoverflow?

jenstornell avatar Oct 17 '17 14:10 jenstornell

Yes I tried it and it worked. But I ended up using a slightly modified version for a project. The problem was that I used the same .htaccess file on my local dev setup and on the production server. When working locally I did not want any redirects. So the version I ended up using is this one:

# Redirect http > https and add www
# ---------------------------------
# First rewrite to https:
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?example\.com$ [NC]
RewriteRule .* https://www.example.com%{REQUEST_URI} [L,R=301]
# Now, rewrite any request without www to use www:
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule .* https://www.example.com%{REQUEST_URI} [L,R=301]

Change example.com to the domain that you are using.

olach avatar Oct 26 '17 21:10 olach