skip to Main Content

I am writing an Apache module in C and I’m looking to apply a regular expression across the entire HTTP URL for the current request (via request_rec). I cannot find any member of request_rec that contains this information. I’ve tried

  • the_request
  • unparsed_uri
  • uri
  • ap_get_server_name(r)
  • path_info
  • parsed_uri.path

… to name a few.

How can I get the entire URL as a single char *?

I understand this question is similar to the one linked below, but this is for the C language (they’re using C++) and their solution (I tried anyways) has not worked for me.

How to get the full HTTP request URL using Apache httpd API (request_rec)?

2

Answers


  1. Chosen as BEST ANSWER

    I was not able to find this information already available in the httpd API (as Cheatah suggested), so I used the following function to build the information myself.

    DISCLAIMER: When I was testing this against the url sub.localhost/a/b/c?query=param the port values under request_rec were unpopulated, so I'm not attempting at this time to handle different ports as it's not important for my use-case.

    const char *buildUrl(request_rec *r)
    {
        char *url = apr_pcalloc(r->pool, urlMaxLength);
    
        // <scheme>://<host><:port(IFF!=80)><unparsed-uri>
        snprintf(url, urlMaxLength, "%s://%s%s%s",
            ap_http_scheme(r),
            r->hostname,
            "", // could not get port # from request_rec... let's just assume that won't be needed...
            r->unparsed_uri
        );
    
        return url;
    }
    

  2. static int on_request(request_rec *r) {
    
      // Substraction for request uri (r->uri is broken when use mod_rewrite)
      char *request_uri = calloc(strlen(r->the_request), 1);
      long unsigned int i;
      for(i = strlen(r->method) + 1; i <= (strlen(r->the_request) - strlen(r->protocol) - 1); i++) {
          request_uri[i - strlen(r->method) - 1] = r->the_request[i];
      }
    
      // Use it
    
      free(request_uri);
    
      // ...
    

    For http://example.com/abc/def.html?ghi=jkl the request_uri is /abc/def.html?ghi=jkl.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search