Home .htaccess rewrite https to www, but not when IP-address is used

# .htaccess rewrite https to www, but not when IP-address is used

user8206
1#
user8206 Published in September 20, 2018, 4:35 pm

I have got a Nextcloud installed on my Raspberry Pi. Https is set up and the rewrite engine is on. Rewrite is also working so far. Now I have got the following problem: If I am invoking my cloud inside the LAN-network I have to use the internal IP-address (192.168.1.20) and using the Internet to reach the cloud over the browser I set up an URL.

For always having a proper URL I want to use a .htaccess-file (and later a IfModule rewrite) to rewrite the URL. The following cases should be rewritten:

http://example.com/xyz -> https://www.example.com/xyz
http://www.example.com/xyz -> https://www.example.com/xyz
http://192.168.1.20/xyz -> https://192.168.1.20/xyz


I am not very familiar with the syntax and so I tried the following without success:

RewriteEngine on

# for URL
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^192.168.1.20
RewriteRule ^https://www.example.com%{REQUEST_URI} [R=301,L,NE]

# for IP
#RewriteCond %{SERVER_NAME} ^192.168.1.20
#RewriteCond %{HTTPS} off
#RewriteRule ^https://192.168.1.20%{REQUEST_URI} [R=301,L,NE]


I would be glad if someone could help me...

EDIT: My "000-default.conf" definitions are:

<VirtualHost _default_:80>
DocumentRoot /var/www/html
ServerName www.example.com
ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost _default_:443>
DocumentRoot /var/www/html
ServerName 192.168.1.20
</IfModule>
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/cloud.crt
SSLCertificateKeyFile /etc/apache2/ssl/cloud.key
</VirtualHost>


And my "default-ssl.conf" definitions:

<IfModule mod_ssl.c>
<VirtualHost _default_:443>

DocumentRoot /var/www/html

ServerName=www.example.com

ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog${APACHE_LOG_DIR}/access.log combined

SSLEngine on

SSLCertificateFile  /etc/apache2/ssl/cloud.crt
SSLCertificateKeyFile   /etc/apache2/ssl/cloud.key

<FilesMatch "\.(cgi|shtml|phtml|php)\$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory /usr/lib/cgi-bin>
SSLOptions +StdEnvVars
</Directory>
</VirtualHost>
</IfModule>

• When Apache receives a request, it looks at the domain asked for to select which VirtualHost to respond with. When you ask with the IP, it will take the first it finds, reading the file top to bottom. Add your VirtualHost definitions in here, otherwise it's hard to provide a full answer. – Nic3500 Feb 14 at 1:55
• Thank you for your answer! I did an edit in my original post with the definitions... – Florian Feb 14 at 14:17