Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application Request Routing: Get Original URL

Tags:

iis

arr

I'm trying to get the original URL from within my application (MVC 5) after a reverse proxy rewrite has occurred.

I've tried everything I can find e.g.

  • Setting my own server variable to the value of {HTTP_HOST} (my server variable started with HTTP). This either contains the current URL or null.
  • Using HTTP_X_ORIGINAL_URL server variable which does not include the hostname.
  • Looking at all the built in server variables.
  • Setting the value preserveHostHeaders as detailed here: https://stackoverflow.com/a/7180527/4950, this caused the site to hang

Any ideas?

Tried on IIS7 and IIS7.5 with ARR 3.0 and Url Rewrite 2.0

like image 558
Rob Stevenson-Leggett Avatar asked Nov 01 '22 19:11

Rob Stevenson-Leggett


1 Answers

This answer is inspired by Setting HTTP request headers and IIS server variables in the IIS documentation. They do something similar, but oddly it avoids detecting whether the original URL was accessed with HTTP or HTTPS.

First, you need to have administrative access to your IIS server in order to set up a new allowed server variable in the URL Rewrite module. This is described in the linked article, but here are the basic steps:

  1. In IIS Manager, navigate to your web site or application folder.
  2. Open the URL Rewrite feature.
  3. In the Actions pane, click "View Server Variables...", then click "Add..."
  4. Enter a name for your server variable.
    • If you want to access it as an HTTP header, prefix it with HTTP. For example, HTTP_X_MY_HEADER is accessible as the X-MY-HEADER header.

Then, in your rewrite rule, set the server variable value to {CACHE_URL}. You can do this through the UI, or directly in web.config, as shown below.

NOTE: be sure to set your match, conditions, and actions as needed.

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="original URL sample" stopProcessing="true">
          ...
          <serverVariables>
            <set name="HTTP_X_MY_HEADER" value="{CACHE_URL}" />
          </serverVariables> 
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration> 

The resulting header will explicitly include the port number, e.g. http://foo.example:80/bar, so you may need to deal with that depending on your needs.

like image 173
Holistic Developer Avatar answered Nov 11 '22 15:11

Holistic Developer