问题
I have a virtual server with one IP address, serving a few different sites. One of them has an SSL certificate on it.
I needed to add an SSL cert on a second domain for private use by myself, and as I only have one IP address, I added it on port 8080 instead. This works fine.
My problem now is that all the domains that point to the server will display 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!
Anyone visiting https://example1.com:8080/
should be redirected to http://example1.com/
, and the same for example2.com
.
I tried...
RewriteCond %{HTTP_HOST} !desired\-domain\.com [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}$1 [L,R=301]
...but the port is appended to HTTP_HOST, so it comes out as http://example1.com:8080/
So, in short, my question: how can I redirect to the requested host, but ignore the request port?
EXTRA
I've tried this...
RewriteCond %{HTTP_HOST} !(desired-domain.com):8080$ [NC]
RewriteRule ^(.*)$ http://%1$1 [L,R=301]
...but it redirects to http://localhost/
. That's better than showing the wrong site's page, though, as nobody should be requesting port 8080 on any other domain anyway!
I suspect there's a better 'desired-domain.com' regex, but my regex-mojo isn't flowing today.
回答1:
Maybe try:
RewriteCond %{HTTP_HOST} ^(example[12].com):8080$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [L,R=301]
Obviously, you'll need to be a bit clever about your HTTP_HOST regular expression, if there's no easy way of encapsulating your example1 and example2 domains within a single regex, you can have 2 of then and use the [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 backreference like !(desired-domain.com):8080$
, as the ! means that 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]
来源:https://stackoverflow.com/questions/9611521/apache-rewriterule-to-remove-port-on-any-domain-name