Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect only HTTP subdomain to HTTPS subdomain in htaccess

How do you redirect only the HTTP subdomain to HTTPS subdomain in .htaccess? The main site is in WordPress and already redirected to HTTPS with a plugin, but the subdomain is a PHP created site. I have looked and not seen a conclusive solution to this on here.

I copy and pasted this suggested code but it did nothing:

#Redirect Subdomain
RewriteEngine on
RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$ [NC]
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
like image 242
JJ100 Avatar asked Sep 27 '18 13:09

JJ100


People also ask

How do I redirect a subdomain to HTTPS?

In order to redirect from HTTP to HTTPS you need to first check you are not already on HTTPS (otherwise you will get a redirect loop). These directives would need to go in the . htaccess in the document root of your subdomain. Or at the top of your root (WordPress) .

Can you redirect HTTP to HTTPS?

If you are using the popular Apache Web server, you can easily redirect all traffic from unsecured HTTP to HTTPS. When a visitor goes to your site will be redirected to the secure HTTPS protocol. The server must allow you to use module mod_rewrite, but it's not a problem for most webhosting providers.


1 Answers

RewriteEngine on
RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$ [NC]
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

This would create a redirect loop (if executed at all). In order to redirect from HTTP to HTTPS you need to first check you are not already on HTTPS (otherwise you will get a redirect loop).

These directives would need to go in the .htaccess in the document root of your subdomain. Or at the top of your root (WordPress) .htaccess file if the subdomain points to the document root of the main site. The important thing is that the redirect must go before the WordPress front-controller.

This also assumes your SSL cert is installed directly on your application server and not a proxy.

Try the following:

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^subdomain\.example\.com [NC]
RewriteRule .? https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

This checks that HTTPS does not contain "on" and the subdomain is being requested before redirecting to HTTPS on the same host.

Although if WP is simply redirecting the main domain, then you could do all this in .htaccess and simply remove the condition that checks against HTTP_HOST. Although if you have other subdomains that should not be redirected to HTTPS then alter the CondPattern to match just the subdomain or main domain (and www subdomain). For example:

RewriteCond %{HTTP_HOST} ^((subdomain|www)\.)?example\.com [NC]
like image 125
MrWhite Avatar answered Sep 19 '22 04:09

MrWhite