[PATCH] implement a $location variable

David Gwynne david at gwynne.id.au
Fri Jan 4 01:22:04 UTC 2013


here's a diff that provides $location for use in not regex location
blocks.

we're using it to provide easy to use mass hosting of drupals:

xdlg at argon nginx$ cat drupal-controller.conf
        root /var/www/apps/drupal;
        try_files /index.php =404;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $location$fastcgi_script_name;
        fastcgi_intercept_errors on;
        fastcgi_pass localhost:9000;

which is used in server blocks like this:

	server {
		listen			80;
		server_name		www.example.com;

		location /		{ include drupal-controller.conf; }
		location /foo		{ include drupal-controller.conf; }
		location /bar		{ include drupal-controller.conf; }
		location /baz		{ include drupal-controller.conf; }
	}

i cannot otherwise find a nice way to use the locations name as a
parameter without specifying the value as a variable again within
the location.

--- src/http/ngx_http_variables.c.orig	Tue Jul  3 03:41:52 2012
+++ src/http/ngx_http_variables.c	Fri Jan  4 10:49:50 2013
@@ -65,6 +65,8 @@ static ngx_int_t ngx_http_variable_request_filename(ng
     ngx_http_variable_value_t *v, uintptr_t data);
 static ngx_int_t ngx_http_variable_server_name(ngx_http_request_t *r,
     ngx_http_variable_value_t *v, uintptr_t data);
+static ngx_int_t ngx_http_variable_location(ngx_http_request_t *r,
+    ngx_http_variable_value_t *v, uintptr_t data);
 static ngx_int_t ngx_http_variable_request_method(ngx_http_request_t *r,
     ngx_http_variable_value_t *v, uintptr_t data);
 static ngx_int_t ngx_http_variable_remote_user(ngx_http_request_t *r,
@@ -206,6 +208,10 @@ static ngx_http_variable_t  ngx_http_core_variables[] 
 
     { ngx_string("server_name"), NULL, ngx_http_variable_server_name, 0, 0, 0 },
 
+    { ngx_string("location"), NULL,
+      ngx_http_variable_location, 0,
+      NGX_HTTP_VAR_NOCACHEABLE, 0 },
+
     { ngx_string("request_method"), NULL,
       ngx_http_variable_request_method, 0,
       NGX_HTTP_VAR_NOCACHEABLE, 0 },
@@ -1382,6 +1388,28 @@ ngx_http_variable_server_name(ngx_http_request_t *r,
     v->no_cacheable = 0;
     v->not_found = 0;
     v->data = cscf->server_name.data;
+
+    return NGX_OK;
+}
+
+
+static ngx_int_t
+ngx_http_variable_location(ngx_http_request_t *r,
+    ngx_http_variable_value_t *v, uintptr_t data)
+{
+    ngx_http_core_loc_conf_t  *clcf;
+
+    clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);
+
+    if (clcf->regex) {
+        v->not_found = 1;
+    } else {
+        v->len = clcf->name.len;
+        v->valid = 1;
+        v->no_cacheable = 0;
+        v->not_found = 0;
+        v->data = clcf->name.data;
+    }
 
     return NGX_OK;
 }



More information about the nginx-devel mailing list