I need to use the HTTP_HOST header in a RewriteRule but change the port I cannot use SERVER_NAME as it will be different from the host header (which is what I need)
Is there a way to trim the :port off of the HTTP_HOST variable for mod_rewrite?
X variable http_host. The Host header always contains the requested host name (which may be a Host Domain Name string or an IP address), and will also contain the requested service port whenever a non-standard port is specified (other than 80 for HTTP, other than 443 for HTTPS).
The HTTP_HOST server variable contains www.mysite.com . The SERVER_PORT server variable contains 80 . The SERVER_PORT_SECURE server variable contains 0 and HTTPS contains OFF . The REQUEST_URI server variable contains /content/default.
The condition ( RewriteCond directive) will never be successful (because the Host header never contains a slash), so the redirect will never occur. As mentioned above, the HTTP_HOST server variable contains the hostname only, eg. example.com or www.example.com .
A rewrite rule can be invoked in httpd. conf or in . htaccess . The path generated by a rewrite rule can include a query string, or can lead to internal sub-processing, external request redirection, or internal proxy throughput.
Yes, you can trim the port off of the host header. Just match against %{HTTP_HOST} and use a %1 backreference. For example:
RewriteCond %{HTTP_HOST} ^([^:]+)(:[0-9]+)?$
RewriteRule ^ http://%1:12345/ [R,L]
Just keep in mind that the %1 backreference can only be used in the first parameter of a RewriteCond, and not in a match:
RewriteCond %{HTTP_HOST} ^([^:]+)(:[0-9]+)?$
RewriteCond %1 ^the.hostname.com$ [NC]
is ok
RewriteCond %{HTTP_HOST} ^([^:]+)(:[0-9]+)?$
RewriteCond %{REQUEST_URI} ^%1
is NOT ok
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With