9

I need help with url-rewriting in .htaccess.

So the issue is about different protocols: https and http. The main purpose of rewriting is to remove "www" from URL, but protocol should stay the same it was before.

For example, when I have URL like http://www.domain.com/request, it should be redirected to the http://domain.com/request. I resolve it with these rules:

RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

But in case, when URL looks like https://www.domain.com/request it should be redirected to https://domain.com/request.

Unfortunately, the above rule will redirect to http regardless current protocol.

Thanks in advance.

Alex
  • 2,960
  • 2
  • 18
  • 21
  • possible duplicate of [htaccess redirect for non-www both http and https](http://stackoverflow.com/questions/2015159/htaccess-redirect-for-non-www-both-http-and-https) – Pekka Sep 03 '10 at 08:38
  • Thank you for the link. I've missed this question during searching. Unfortuntely, that exapmle doesn't work. It redirects https:// domain.com/request to the http:// www.domain.com/request, instead of https:// www.domain.com/request. – Alex Sep 03 '10 at 09:18

1 Answers1

9

This is fairly similar to the linked possible duplicate, but since that one forces www where you want to remove it, it might warrant a separate answer.

Try something like this:

RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]
Tim Stone
  • 18,831
  • 6
  • 54
  • 66
  • 2
    An explanation of those above rules will definitely be very helpful as reference for people looking for www to non www redirection. – Alex Le Mar 06 '13 at 16:15
  • seriously, apache API creators... why not just have a variable like `HTTP_PROTOCOL`, and have the second argument follow the same pattern like all the other ones? `RewriteCond %{HTTP_PROTOCOL} ^http$` or `RewriteCond %{HTTP_PROTOCOL} ^https$` instead of making an exception to the rule? Less knowledge requirements is better. Extra knowledge is good, but extra required knowledge is bad. And you have to know the exact syntax and value. Who is going to guess `^on(s)|off`. Freaken old PHP-related tools... – ahnbizcad Sep 12 '16 at 21:01
  • brilliant answer (compliments the DigitalOcean documentation on redirecting www) although for maximum compatibility with case sensitivity `[NC]` should be set on the RewriteCond see https://stackoverflow.com/a/5582488/614616 – hozza Jun 20 '17 at 12:39