Apache RewriteRule to remove port by any domain name
I have a virtual server with one IP, serving several different sites. One of them has an SSL certificate.
I needed to add the SSL certificate to the second domain for personal use myself, and since I only have one IP address, I added it to port 8080 instead. This works great.
Now my problem is that all domains pointing to the server will render my private site if port 8080 is requested on that domain.
https://example1.com:8080/ -> will show my private site, but shouldn't
https://example2.com:8080/ -> will show my private site, but shouldn't
https://desired-domain.com:8080/ -> will show my private site, this is correct!
Any visit https://example1.com:8080/
should be redirected to http://example1.com/
as well as example2.com
.
I tried...
RewriteCond %{HTTP_HOST} !desired\-domain\.com [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}$1 [L,R=301]
... but the port is added to the HTTP_HOST, so it outputs as http://example1.com:8080/
So, in short, my question is, how can I redirect to the requested host, but ignore the request port?
EXTRA
I tried this ...
RewriteCond %{HTTP_HOST} !(desired-domain.com):8080$ [NC]
RewriteRule ^(.*)$ http://%1$1 [L,R=301]
... but it gets redirected to http://localhost/
. This is better than showing the wrong site page, although no one should be requesting port 8080 on any other domain!
I suspect there is a better expression 'wish-domain.com', but my regex is not leaking today.
source to share
Maybe try:
RewriteCond %{HTTP_HOST} ^(example[12].com):8080$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [L,R=301]
Obviously you need to be a little clever about your HTTP_HOST regex, if there is no easy way to encapsulate your examples1 and example2 within a single regex, you can have 2 of them and use [OR] :
RewriteCond %{HTTP_HOST} ^(example1.com):8080$ [NC,OR]
RewriteCond %{HTTP_HOST} ^(example2.com):8080$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [L,R=301]
EDIT:
You cannot match a backlink, for example !(desired-domain.com):8080$
, since ! means it doesn't match. But you can try something like this:
RewriteCond %{HTTP_HOST} !^desired-domain.com(:8080)?$ [NC]
RewriteCond %{HTTP_HOST} ^(.*):8080$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [L,R=301]
source to share