matsbauer
matsbauer

Reputation: 434

HTTPS forwarding for subdomain

I have a domain, let's make it example.com, and a subdomain, sub.example.com. For the subdomain I have a SSL certificate, for the main domain I don't. On my server I have a .htaccess file for my main domain, but none for my subdomain. How do I specify, in this file, to forward from http://sub.example.com to https://sub.example.com? Or do I need a second .htaccess file in the folder for my subdomain?

Upvotes: 2

Views: 520

Answers (1)

MrWhite
MrWhite

Reputation: 45829

I assume your subdomain is hosted in a subdirectory off the main domain's document root? So the main domain's .htaccess file is in the parent directory? (If not, then you will need another .htaccess file in the root of the subdomain.)

Try the following mod_rewrite directives at the top of the main domain's .htaccess file.

RewriteEngine On

RewriteCond %{HTTP_HOST} ^sub\.example\.com [NC]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L]

This is a temporary (302) redirect. Change it to 301 only when you are sure it's working OK. (Permanent redirects are cached hard by the browser so can make testing problematic.)

You only need one RewriteEngine directive at the top of your file.

UPDATE: If the file structure is as mentioned above (ie. the subdomain is located in a subdirectory off the main domain's document root - where the .htaccess file is located) then you will need to use the REQUEST_URI server variable to reference the URL-path, not a backreference (ie. $1 - as I had initially) to the captured RewriteRule pattern, since the captured backreference will contain the subdirectory, which is not part of the URL-path.

Upvotes: 3

Related Questions