Skip to main content

Crate url_parse_nginx

Crate url_parse_nginx 

Source
Expand description

Parse and normalize URL paths using nginx semantics.

url-parse-nginx is a one-to-one Rust port of nginx’s URI parser and normalizer. Within the supported scope described below, it matches nginx’s accept/reject decisions and produces byte-for-byte identical normalized paths and query strings. This equivalence is continuously checked by differential fuzzing against nginx’s C implementation.

parse_origin_form accepts an origin-form request target, normalizes its path, and returns the query string separately. Path normalization percent-decodes %XX, resolves . and .. segments, and optionally merges adjacent slashes.

Origin-form is the usual HTTP request-target format: a path starting with /, optionally followed by ? and a query string, such as /search?q=rust.

Other request-target forms, such as absolute-form (http://example.com/path), authority-form (example.com:443), and asterisk-form (*), are not supported. The parsing behavior follows nginx on Linux; Windows-specific nginx behavior is not supported.

The crate supports no_std environments with alloc.

§Example

use url_parse_nginx::parse_origin_form;

let parsed = parse_origin_form(b"/docs/../hello%20world?x=1", true)?;
assert_eq!(&*parsed.path, b"/hello world"); // ".." resolved, "%20" decoded
assert_eq!(parsed.args.unwrap(), b"x=1");

§Percent-encoding the normalized path

Some nginx processing paths, including some proxy_pass cases, first normalize and percent-decode the request path, then percent-encode the normalized path again. To reproduce this decode-then-encode flow, pass Parsed::path to percent_encoding::percent_encode with PATH_ESCAPE_SET. The set is available when the percent-encoding feature is enabled (enabled by default).

The default percent-encoding feature also supports nginx-compatible re-encoding:

use percent_encoding::percent_encode;
use url_parse_nginx::{parse_origin_form, PATH_ESCAPE_SET};

let parsed = parse_origin_form(b"/docs/../hello%20world", true)?;
let encoded = percent_encode(&parsed.path, PATH_ESCAPE_SET);
assert_eq!(encoded.to_string(), "/hello%20world");

Using percent_encoding::percent_encode requires a direct dependency on the percent-encoding crate.

Structs§

ParseError
An error returned when a request target cannot be parsed.
Parsed
The result of parsing an origin-form request target.

Constants§

PATH_ESCAPE_SET
The percent-encode set nginx uses when escaping normalized paths.

Functions§

parse_origin_form
Parse a single origin-form request target exactly as nginx does.