I can't get mod_rewrite work with the following Rules.
RewriteCond "%{SERVER_NAME}" "home.myhome.net"
RewriteCond "%{SERVER_PORT}" "^4388$"
RewriteRule (.*) https://home.myhome.net:4389%{REQUEST_URI} [QSA,R=301,L]
This Rule is set on my http virtual host section. Problem is, that redirect only works the first time. The second time when I enter a differnt URL on http port 4388 I get redirected to https://home.myhome.net:4388/...
for example:
- first I enter http://home.myhome.net:4388/pageA I get redirected to https://home.myhome.net:4389/pageA
- next time I enter http://home.myhome.net:4388/pageB and get redirected to https://home.myhome.net:4388/pageB
Any Idea how to fix that?
My OS details:
root@host:~# dpkg -l|grep apache
ii apache2 2.4.18-2ubuntu3.5 amd64 Apache HTTP Server
ii apache2-bin 2.4.18-2ubuntu3.5 amd64 Apache HTTP Server (modules and other binary files)
ii apache2-data 2.4.18-2ubuntu3.5 all Apache HTTP Server (common files)
ii apache2-utils 2.4.18-2ubuntu3.5 amd64 Apache HTTP Server (utility programs for web servers)
ii python-certbot-apache 0.17.0-1+ubuntu16.04.1+certbot+1 all Apache plugin for Certbot
root@host:~# lsb_release -d
Description: Ubuntu 16.04.3 LTS
That's my Virtual Host Config, it is something different because I made some more tests, but same behavior. I also dropped for testing all other rewrite rules, with same result (and how I told in comments, for every test I flush my browser cache).
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot /var/www/html
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond "%{SERVER_NAME}" "home.myhome.net"
RewriteCond "%{SERVER_PORT}" "^4388$"
RewriteRule ^ https://%{SERVER_NAME}:4389%{REQUEST_URI} [noescape,qsappend,redirect=301,last]
</IfModule>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Oh, and I forgot to say, that this server is behind a NAT Gateway, which does a port forwarding from external port 4388 to internal host port 80 and also external port 4389 to internal port 443. Thats why I need to check for the port and hostname to match only external traffic.
EDIT: Okay, I have found something, but also don't have a solution: I compared the first and following browser request/response with the browser developer tools->network tab:
The first request give me the "301 Moved Permanently", but the following request gives me a "307 Internal Redirect".
So this seems a Server problem. Question is only, if it is a Bug in mod_rewrite or is it my fault, because the Rule is not okay.
EDIT: I tested now also with the current apache version 2.4.27-5.1+ubuntu16.04.1+deb.sury.org+1 from Ondřej Surý's Apache PPA
Regards, Thomas
Ok, after long search I finally found the reason. I had set the HTTP Strict-Transport-Security (HSTS) on my https website, thats why the browser don't start again to open a http website on that url and force https protocol.
The given examples are all working.