Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL rewriting for different protocols in .htaccess

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.

like image 681
Alex Avatar asked Sep 03 '10 08:09

Alex


People also ask

What is RewriteCond and RewriteRule?

There are two main directive of this module: RewriteCond & RewriteRule . RewriteRule is used to rewrite the url as the name signifies if all the conditions defined in RewriteCond are matching. One or more RewriteCond can precede a RewriteRule directive.

What is the difference between URL rewriting and redirecting?

Simply put, a redirect is a client-side request to have the web browser go to another URL. This means that the URL that you see in the browser will update to the new URL. A rewrite is a server-side rewrite of the URL before it's fully processed by IIS.


1 Answers

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]
like image 57
Tim Stone Avatar answered Oct 16 '22 19:10

Tim Stone