arcyqwerty
arcyqwerty

Reputation: 10685

RewriteRule using HTTP_HOST and a different port

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?

Upvotes: 8

Views: 11849

Answers (1)

Jon Lin
Jon Lin

Reputation: 143906

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

Upvotes: 11

Related Questions