H
H
hior2011-06-21 15:22:13
Apache HTTP Server
hior, 2011-06-21 15:22:13

Redirect from https://www. to https:// using Apache mod_rewrite?

I'm trying to set up a simultaneous redirect from www.sitename.com to sitename.com and from http to https. The rules below work great except that there is no redirect from https://www.sitename.com to https://sitename.com . The rest of the options work.

<pre>
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</pre><br/>


Tried to do like this:

<pre>
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R,L]

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</pre><br/>


This option doesn't work either. It seems that RewriteCond %{HTTP_HOST} for https requests never works at all. Google didn't help.

Answer the question

In order to leave comments, you need to log in

8 answer(s)
D
Denis Turenko, 2011-06-21
@hior

It does not give https in .htaccess, you can catch it in php through $_SERVER['https'] .

D
demshyn, 2016-12-19
@demshyn

Try this code:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

Helped me. Taken from here .

S
Sergey, 2011-06-21
@bondbig

Do two rewrites, first from www to http:// and then to https://

X
xaker1, 2011-06-21
@xaker1

Try
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule (.*) site.ru/$1 [L,R=301]

V
videns, 2011-06-21
@videns

Yes, I have encountered this. As a result, I checked the port number. Like this:
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ www.domain.tld/ $1 [L,R]

M
MrCrock, 2011-06-21
@MrCrock

RewriteCond %{HTTPS} off
RewriteRule (.*) https ://%{HTTP_HOST}%{REQUEST_URI}

After https, remove the space (the habr parser distorts). Change %{HTTP_HOST} to your sitename.com

A
Alexander Borisovich, 2017-01-11
@Alexufo

Try this.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP:X-HTTPS} !1
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

E
Eugene Sherman, 2018-09-22
@freehostua

If the frontend is nginx, it may not be the https variable, so you can
RewriteCond %{HTTP_X_FORWARDED_PROTO} http
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question