Reputation: 51
I have an httpd server configured to handle HTTPS connections and forward the connections to a Tomcat (via http or ajp) where the requests are processed. One of the requirements I have in the Tomcat server is to log the remote port number of each request. If I hit the Tomcat directly, retrieving the remote port number is straight forward and we are currently doing it using the getRemotePort()
function (HttpServletRequest).
However, since I'm doing a reverse proxy (forwarding HTTPS requests via HTTP/AJP) a new connection will be created and I'll always get the remote port (and remote IP for that matter) for the connection from my httpd server to tomcat (except when I use AJP. In this case the remote server IP info comes correctly).
I've tried different configurations on httpd, like:
ProxyPreserveHost On
ProxyPass / ajp://localhost:8009/
or
ProxyPreserveHost On
ProxyPass / http://localhost:8081/
I also played a little bit with RewriteRules, but couldn't make things work.
Reading httpd documentation, mod_proxy offers request header information for things like X-Forwarded-Host
, X-Forwarded-For
, etc. But there is no info about source port.
I've even found a bug, where apparently a X-Forwarded-Port
attribute was added to the proxy request header, but that code doesn't seem to have made to the main line/branch.
So, in summary, how can I retrieve the source port of the client (not the reverse proxy) when HTTPD is forwarding requests to Tomcat?
Upvotes: 5
Views: 3702
Reputation: 10329
You can add a request header called X-Forwarded-SourcePort with mod_rewrite + mod_headers
RewriteEngine on
RewriteRule .* - [E=REMOTE_PORT:%{REMOTE_PORT},NE]
RequestHeader set X-Forwarded-SourcePort %{REMOTE_PORT}e
Apache will forward the request with the client source port to the backend server, so you can get the X-Forwarded-SourcePort request header from your application.
Upvotes: 3
Reputation: 29814
I believe you can do this using the mod_rewrite module
In a RewriteRule you can specify server variables in the Substitution String as stated in the documentation
In addition to plain text, the Substition string can include
back-references ($N) to the RewriteRule pattern
back-references (%N) to the last matched RewriteCond pattern
server-variables as in rule condition test-strings (%{VARNAME})
One of these variables is REMOTE_PORT
.
You can then rewrite your URL and pass it as an URL parameter to to your Tomcat servlet call e.g.
http://url.to.tomcat/mycontext?remoteport=${REMOTE_PORT}
Upvotes: 0