NaviServer Built-in Commands – 5.0.0a
ns_serverrootproc - Callback for Determining Server Root
This command registers a Tcl callback that dynamically computes the server root directory. It is commonly used to determine the per-request "serverdir" based on attributes of the current connection (for example, using the Host: header field).
Registers a script that returns the server root directory as an absolute or relative path. The result of this callback overrides the default value of the serverdir parameter. For more details, see Customizing File Locations.
If additional arguments are provided, they will be passed to the callback. Thus, the callback can be specified as either a (multi-line) script or as a command with arguments. (Note: When the callback is registered via a configuration parameter, the multi-argument invocation style is not available.)
The serverrootproc callback can be defined directly in the configuration file or registered via the ns_serverrootproc command. Defining it in the configuration file has the advantage that it can be used (for example, for setting log file paths) before the server (here named "default") fully starts.
ns_section ns/server/default { ns_param serverdir /var/www ns_param serverrootproc { # # Compute the per-request "serverdir": # set rootDir [ns_server serverdir] set host [ns_conn host ""] if {$host ne "" && [file isdirectory $rootDir/$host ]} { # Use the directory corresponding to the Host header. set serverDir $rootDir/$host } else { # Fall back to the default server directory. set serverDir $rootDir/[ns_info server] ns_log notice "... $rootDir/$host does not exist, use default '$serverDir'" } return $serverDir } }
Alternatively, you can register the callback via ns_serverrootproc within the Tcl initialization script of a server. This approach was standard in NaviServer 4.99 but is more complex since the callback must be registered after the server is initialized. One way to do this is by using the initcmd parameter in the tcl section of a server configuration:
ns_section ns/server/default/tcl { ns_param initcmds { # # Use the Tcl namespace "::default" for the "default" server. # namespace eval ::default { # # Define the callback procedure. # proc serverroot {args} { # # Compute the per-request "serverdir": # set rootDir [ns_server serverdir] set host [ns_conn host ""] if {$host ne "" && [file isdirectory $rootDir/$host ]} { set serverDir $rootDir/$host } else { set serverDir $rootDir/[ns_info server] ns_log notice "... $rootDir/$host does not exist, use default '$serverDir'" } return $serverDir } # # Register the callback: # ns_serverrootproc [namespace current]::serverroot } } }