2

I have two redirects (one for http and one for https):

# Option 1a: rewrite www.example.com → example.com

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>

# Option 1b: rewrite https://www.example.com → https://example.com

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
</IfModule>

Is it possible to combine them, and remove the subdomain for both http and https with one ruleset (without having to specify the exact domain, like the current rules)?

  • 1
    check this post http://stackoverflow.com/questions/19372594/preserve-http-https-protocol-in-htaccess-redirects – tzafar Dec 17 '14 at 12:40
  • @tzafar Yes, I've seen that, but that requires the domain to be specified, which is what I'm trying to avoid. I've tried to adapt it to my use-case, but am stuck with trying to make the domain a variable.. – vkjb38sjhbv98h4jgvx98hah3fef Dec 17 '14 at 12:44

2 Answers2

2

Here is how you can combine both rules into one without hardcoding hostname:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST}#%{HTTPS}s ^www\.([^#]+)#(?:off|on(s)) [NC]
    RewriteRule ^ http%2://%1%{REQUEST_URI} [R=301,L]
</IfModule>
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Try this

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTPS}:s on:(s)
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^ http%1://%2%{REQUEST_URI} [R=301,QSA,L]
</IfModule>
tzafar
  • 674
  • 3
  • 12
  • 1
    Would `%1` not contain the domain name in cases where the request isn't https? Surely if there's no match the group won't get populated? – arco444 Dec 17 '14 at 13:47