code
stringlengths
2.5k
150k
kind
stringclasses
1 value
pony SignalHandler SignalHandler ============= [[Source]](https://stdlib.ponylang.io/src/signals/signal_handler/#L10) Listen for a specific signal. If the wait parameter is true, the program will not terminate until the SignalHandler's dispose method is called, or if the SignalNotify returns false, after handling the signal as this also disposes the SignalHandler and unsubscribes it. ``` actor tag SignalHandler ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/signals/signal_handler/#L20) Create a signal handler. ``` new tag create( notify: SignalNotify iso, sig: U32 val, wait: Bool val = false) : SignalHandler tag^ ``` #### Parameters * notify: [SignalNotify](signals-signalnotify) iso * sig: [U32](builtin-u32) val * wait: [Bool](builtin-bool) val = false #### Returns * [SignalHandler](index) tag^ Public Behaviours ----------------- ### raise [[Source]](https://stdlib.ponylang.io/src/signals/signal_handler/#L29) Raise the signal. ``` be raise() ``` ### dispose [[Source]](https://stdlib.ponylang.io/src/signals/signal_handler/#L35) Dispose of the signal handler. ``` be dispose() ``` pony ANSI ANSI ==== [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L1) These strings can be embedded in text when writing to a StdStream to create a text-based UI. ``` primitive val ANSI ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L1) ``` new val create() : ANSI val^ ``` #### Returns * [ANSI](index) val^ Public Functions ---------------- ### up [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L6) Move the cursor up n lines. 0 is the same as 1. ``` fun box up( n: U32 val = 0) : String val ``` #### Parameters * n: [U32](builtin-u32) val = 0 #### Returns * [String](builtin-string) val ### down [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L16) Move the cursor down n lines. 0 is the same as 1. ``` fun box down( n: U32 val = 0) : String val ``` #### Parameters * n: [U32](builtin-u32) val = 0 #### Returns * [String](builtin-string) val ### right [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L26) Move the cursor right n columns. 0 is the same as 1. ``` fun box right( n: U32 val = 0) : String val ``` #### Parameters * n: [U32](builtin-u32) val = 0 #### Returns * [String](builtin-string) val ### left [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L36) Move the cursor left n columns. 0 is the same as 1. ``` fun box left( n: U32 val = 0) : String val ``` #### Parameters * n: [U32](builtin-u32) val = 0 #### Returns * [String](builtin-string) val ### cursor [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L46) Move the cursor to line y, column x. 0 is the same as 1. This indexes from the top left corner of the screen. ``` fun box cursor( x: U32 val = 0, y: U32 val = 0) : String val ``` #### Parameters * x: [U32](builtin-u32) val = 0 * y: [U32](builtin-u32) val = 0 #### Returns * [String](builtin-string) val ### clear [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L57) Clear the screen and move the cursor to the top left corner. ``` fun box clear() : String val ``` #### Returns * [String](builtin-string) val ### erase [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L63) Erases everything to the left of the cursor on the line the cursor is on. ``` fun box erase() : String val ``` #### Returns * [String](builtin-string) val ### reset [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L69) Resets all colours and text styles to the default. ``` fun box reset() : String val ``` #### Returns * [String](builtin-string) val ### bold [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L75) Bold text. Does nothing on Windows. ``` fun box bold( state: Bool val = true) : String val ``` #### Parameters * state: [Bool](builtin-bool) val = true #### Returns * [String](builtin-string) val ### underline [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L81) Underlined text. Does nothing on Windows. ``` fun box underline( state: Bool val = true) : String val ``` #### Parameters * state: [Bool](builtin-bool) val = true #### Returns * [String](builtin-string) val ### blink [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L87) Blinking text. Does nothing on Windows. ``` fun box blink( state: Bool val = true) : String val ``` #### Parameters * state: [Bool](builtin-bool) val = true #### Returns * [String](builtin-string) val ### reverse [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L93) Swap foreground and background colour. ``` fun box reverse( state: Bool val = true) : String val ``` #### Parameters * state: [Bool](builtin-bool) val = true #### Returns * [String](builtin-string) val ### black [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L99) Black text. ``` fun box black() : String val ``` #### Returns * [String](builtin-string) val ### red [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L105) Red text. ``` fun box red() : String val ``` #### Returns * [String](builtin-string) val ### green [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L111) Green text. ``` fun box green() : String val ``` #### Returns * [String](builtin-string) val ### yellow [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L117) Yellow text. ``` fun box yellow() : String val ``` #### Returns * [String](builtin-string) val ### blue [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L123) Blue text. ``` fun box blue() : String val ``` #### Returns * [String](builtin-string) val ### magenta [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L129) Magenta text. ``` fun box magenta() : String val ``` #### Returns * [String](builtin-string) val ### cyan [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L135) Cyan text. ``` fun box cyan() : String val ``` #### Returns * [String](builtin-string) val ### grey [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L141) Grey text. ``` fun box grey() : String val ``` #### Returns * [String](builtin-string) val ### white [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L147) White text. ``` fun box white() : String val ``` #### Returns * [String](builtin-string) val ### bright\_red [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L153) Bright red text. ``` fun box bright_red() : String val ``` #### Returns * [String](builtin-string) val ### bright\_green [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L159) Bright green text. ``` fun box bright_green() : String val ``` #### Returns * [String](builtin-string) val ### bright\_yellow [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L165) Bright yellow text. ``` fun box bright_yellow() : String val ``` #### Returns * [String](builtin-string) val ### bright\_blue [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L171) Bright blue text. ``` fun box bright_blue() : String val ``` #### Returns * [String](builtin-string) val ### bright\_magenta [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L177) Bright magenta text. ``` fun box bright_magenta() : String val ``` #### Returns * [String](builtin-string) val ### bright\_cyan [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L183) Bright cyan text. ``` fun box bright_cyan() : String val ``` #### Returns * [String](builtin-string) val ### bright\_grey [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L189) Bright grey text. ``` fun box bright_grey() : String val ``` #### Returns * [String](builtin-string) val ### black\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L195) Black background. ``` fun box black_bg() : String val ``` #### Returns * [String](builtin-string) val ### red\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L201) Red background. ``` fun box red_bg() : String val ``` #### Returns * [String](builtin-string) val ### green\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L207) Green background. ``` fun box green_bg() : String val ``` #### Returns * [String](builtin-string) val ### yellow\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L213) Yellow background. ``` fun box yellow_bg() : String val ``` #### Returns * [String](builtin-string) val ### blue\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L219) Blue background. ``` fun box blue_bg() : String val ``` #### Returns * [String](builtin-string) val ### magenta\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L225) Magenta background. ``` fun box magenta_bg() : String val ``` #### Returns * [String](builtin-string) val ### cyan\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L231) Cyan background. ``` fun box cyan_bg() : String val ``` #### Returns * [String](builtin-string) val ### grey\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L237) Grey background. ``` fun box grey_bg() : String val ``` #### Returns * [String](builtin-string) val ### white\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L243) White background. ``` fun box white_bg() : String val ``` #### Returns * [String](builtin-string) val ### bright\_red\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L249) Bright red background. ``` fun box bright_red_bg() : String val ``` #### Returns * [String](builtin-string) val ### bright\_green\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L255) Bright green background. ``` fun box bright_green_bg() : String val ``` #### Returns * [String](builtin-string) val ### bright\_yellow\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L261) Bright yellow background. ``` fun box bright_yellow_bg() : String val ``` #### Returns * [String](builtin-string) val ### bright\_blue\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L267) Bright blue background. ``` fun box bright_blue_bg() : String val ``` #### Returns * [String](builtin-string) val ### bright\_magenta\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L273) Bright magenta background. ``` fun box bright_magenta_bg() : String val ``` #### Returns * [String](builtin-string) val ### bright\_cyan\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L279) Bright cyan background. ``` fun box bright_cyan_bg() : String val ``` #### Returns * [String](builtin-string) val ### bright\_grey\_bg [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L285) Bright grey background. ``` fun box bright_grey_bg() : String val ``` #### Returns * [String](builtin-string) val ### eq [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L6) ``` fun box eq( that: ANSI val) : Bool val ``` #### Parameters * that: [ANSI](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/term/ansi/#L6) ``` fun box ne( that: ANSI val) : Bool val ``` #### Parameters * that: [ANSI](index) val #### Returns * [Bool](builtin-bool) val pony XorOshiro128StarStar XorOshiro128StarStar ==================== [[Source]](https://stdlib.ponylang.io/src/random/xoroshiro/#L44) This is an implementation of xoroshiro128\*\*, as detailed at: http://xoshiro.di.unimi.it/ This Rand implementation is slightly slower than [XorOshiro128Plus](random-xoroshiro128plus) but does not exhibit "mild dependencies in Hamming weights" (the lower four bits might fail linearity tests). ``` class ref XorOshiro128StarStar is Random ref ``` #### Implements * [Random](random-random) ref Constructors ------------ ### from\_u64 [[Source]](https://stdlib.ponylang.io/src/random/xoroshiro/#L57) Use seed x to seed a [SplitMix64](random-splitmix64) and use this to initialize the 128 bits of state. ``` new ref from_u64( x: U64 val = 5489) : XorOshiro128StarStar ref^ ``` #### Parameters * x: [U64](builtin-u64) val = 5489 #### Returns * [XorOshiro128StarStar](index) ref^ ### create [[Source]](https://stdlib.ponylang.io/src/random/xoroshiro/#L66) ``` new ref create( x: U64 val = 5489, y: U64 val = 0) : XorOshiro128StarStar ref^ ``` #### Parameters * x: [U64](builtin-u64) val = 5489 * y: [U64](builtin-u64) val = 0 #### Returns * [XorOshiro128StarStar](index) ref^ Public Functions ---------------- ### next [[Source]](https://stdlib.ponylang.io/src/random/xoroshiro/#L71) ``` fun ref next() : U64 val ``` #### Returns * [U64](builtin-u64) val ### has\_next ``` fun tag has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### u8 ``` fun ref u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 ``` fun ref u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 ``` fun ref u32() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64 ``` fun ref u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 ``` fun ref u128() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong ``` fun ref ulong() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize ``` fun ref usize() : USize val ``` #### Returns * [USize](builtin-usize) val ### i8 ``` fun ref i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 ``` fun ref i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 ``` fun ref i32() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64 ``` fun ref i64() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128 ``` fun ref i128() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong ``` fun ref ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize ``` fun ref isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### int\_fp\_mult[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] ``` fun ref int_fp_mult[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### int[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] ``` fun ref int[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### int\_unbiased[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] ``` fun ref int_unbiased[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### real ``` fun ref real() : F64 val ``` #### Returns * [F64](builtin-f64) val ### shuffle[A: A] ``` fun ref shuffle[A: A]( array: Array[A] ref) : None val ``` #### Parameters * array: [Array](builtin-array)[A] ref #### Returns * [None](builtin-none) val pony Optional Optional ======== [[Source]](https://stdlib.ponylang.io/src/options/options/#L74) ``` primitive val Optional ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/options/options/#L74) ``` new val create() : Optional val^ ``` #### Returns * [Optional](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/options/options/#L76) ``` fun box eq( that: Optional val) : Bool val ``` #### Parameters * that: [Optional](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/options/options/#L76) ``` fun box ne( that: Optional val) : Bool val ``` #### Parameters * that: [Optional](index) val #### Returns * [Bool](builtin-bool) val pony Less Less ==== [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L1) ``` primitive val Less is Equatable[(Less val | Equal val | Greater val)] ref ``` #### Implements * [Equatable](builtin-equatable)[([Less](index) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val)] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L1) ``` new val create() : Less val^ ``` #### Returns * [Less](index) val^ Public Functions ---------------- ### string [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L2) ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### eq [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L19) ``` fun box eq( that: (Less val | Equal val | Greater val)) : Bool val ``` #### Parameters * that: ([Less](index) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val) #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L20) ``` fun box ne( that: (Less val | Equal val | Greater val)) : Bool val ``` #### Parameters * that: ([Less](index) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val) #### Returns * [Bool](builtin-bool) val pony Env Env === [[Source]](https://stdlib.ponylang.io/src/builtin/env/#L1) An environment holds the command line and other values injected into the program by default by the runtime. ``` class val Env ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/env/#L57) Build an artificial environment. A root capability may be supplied. ``` new val create( root': (AmbientAuth val | None val), input': InputStream tag, out': OutStream tag, err': OutStream tag, args': Array[String val] val, vars': Array[String val] val, exitcode': {(I32)} val) : Env val^ ``` #### Parameters * root': ([AmbientAuth](builtin-ambientauth) val | [None](builtin-none) val) * input': [InputStream](builtin-inputstream) tag * out': [OutStream](builtin-outstream) tag * err': [OutStream](builtin-outstream) tag * args': [Array](builtin-array)[[String](builtin-string) val] val * vars': [Array](builtin-array)[[String](builtin-string) val] val * exitcode': {(I32)} val #### Returns * [Env](index) val^ Public fields ------------- ### let root: ([AmbientAuth](builtin-ambientauth) val | [None](builtin-none) val) [[Source]](https://stdlib.ponylang.io/src/builtin/env/#L6) The root capability. Can be `None` for artificially constructed `Env` instances. ### let input: [InputStream](builtin-inputstream) tag [[Source]](https://stdlib.ponylang.io/src/builtin/env/#L13) Stdin represented as an actor. ### let out: [OutStream](builtin-outstream) tag [[Source]](https://stdlib.ponylang.io/src/builtin/env/#L18) Stdout ### let err: [OutStream](builtin-outstream) tag [[Source]](https://stdlib.ponylang.io/src/builtin/env/#L21) Stderr ### let args: [Array](builtin-array)[[String](builtin-string) val] val [[Source]](https://stdlib.ponylang.io/src/builtin/env/#L24) The command line used to start the program. ### let vars: [Array](builtin-array)[[String](builtin-string) val] val [[Source]](https://stdlib.ponylang.io/src/builtin/env/#L27) The program's environment variables. ### let exitcode: {(I32)} val [[Source]](https://stdlib.ponylang.io/src/builtin/env/#L30) Sets the environment's exit code. The exit code of the root environment will be the exit code of the application, which defaults to 0.
programming_docs
pony PonyBench PonyBench ========= [[Source]](https://stdlib.ponylang.io/src/ponybench/pony_bench/#L108) ``` actor tag PonyBench ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/ponybench/pony_bench/#L114) ``` new tag create( env: Env val, list: BenchmarkList tag) : PonyBench tag^ ``` #### Parameters * env: [Env](builtin-env) val * list: [BenchmarkList](ponybench-benchmarklist) tag #### Returns * [PonyBench](index) tag^ Public Behaviours ----------------- ### apply [[Source]](https://stdlib.ponylang.io/src/ponybench/pony_bench/#L128) ``` be apply( bench: (MicroBenchmark iso | AsyncMicroBenchmark iso)) ``` #### Parameters * bench: ([MicroBenchmark](ponybench-microbenchmark) iso | [AsyncMicroBenchmark](ponybench-asyncmicrobenchmark) iso) pony ArrayKeys[A: A, B: Array[A] #read] ArrayKeys[A: A, B: [Array](builtin-array)[A] #read] =================================================== [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L936) ``` class ref ArrayKeys[A: A, B: Array[A] #read] is Iterator[USize val] ref ``` #### Implements * [Iterator](builtin-iterator)[[USize](builtin-usize) val] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L940) ``` new ref create( array: B) : ArrayKeys[A, B] ref^ ``` #### Parameters * array: B #### Returns * [ArrayKeys](index)[A, B] ref^ Public Functions ---------------- ### has\_next [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L944) ``` fun box has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### next [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L947) ``` fun ref next() : USize val ``` #### Returns * [USize](builtin-usize) val pony List[A: A] List[A: A] ========== [[Source]](https://stdlib.ponylang.io/src/collections/list/#L1) A doubly linked list. (The following is paraphrased from [Wikipedia](https://en.wikipedia.org/wiki/Doubly_linked_list).) A doubly linked list is a linked data structure that consists of a set of sequentially linked records called nodes. (Implemented in Ponylang via the collections.ListNode class.) Each node contains four fields: two link fields (references to the previous and to the next node in the sequence of nodes), one data field, and the reference to the in which it resides. A doubly linked list can be conceptualized as two singly linked lists formed from the same data items, but in opposite sequential orders. As you would expect. functions are provided to perform all the common list operations such as creation, traversal, node addition and removal, iteration, mapping, filtering, etc. Example program --------------- There are a *lot* of functions in List. The following code picks out a few common examples. It outputs: ``` A new empty list has 0 nodes. Adding one node to our empty list means it now has a size of 1. The first (index 0) node has the value: A single String A list created by appending our second single-node list onto our first has size: 2 The List nodes of our first list are now: A single String Another String Append *moves* the nodes from the second list so that now has 0 nodes. A list created from an array of three strings has size: 3 First Second Third Mapping over our three-node list produces a new list of size: 3 Each node-value in the resulting list is now far more exciting: First BOOM! Second BOOM! Third BOOM! Filtering our three-node list produces a new list of size: 2 Second BOOM! Third BOOM! The size of our first partitioned list (matches predicate): 1 The size of our second partitioned list (doesn't match predicate): 1 Our matching partition elements are: Second BOOM! ``` ``` use "collections" actor Main new create(env:Env) => // Create a new empty List of type String let my_list = List[String]() env.out.print("A new empty list has " + my_list.size().string() + " nodes.") // 0 // Push a String literal onto our empty List my_list.push("A single String") env.out.print("Adding one node to our empty list means it now has a size of " + my_list.size().string() + ".") // 1 // Get the first element of our List try env.out.print("The first (index 0) node has the value: " + my_list.index(0)?()?.string()) end // A single String // Create a second List from a single String literal let my_second_list = List[String].unit("Another String") // Append the second List to the first my_list.append_list(my_second_list) env.out.print("A list created by appending our second single-node list onto our first has size: " + my_list.size().string()) // 2 env.out.print("The List nodes of our first list are now:") for n in my_list.values() do env.out.print("\t" + n.string()) end // NOTE: this _moves_ the elements so second_list consequently ends up empty env.out.print("Append *moves* the nodes from the second list so that now has " + my_second_list.size().string() + " nodes.") // 0 // Create a third List from a Seq(ence) // (In this case a literal array of Strings) let my_third_list = List[String].from(["First"; "Second"; "Third"]) env.out.print("A list created from an array of three strings has size: " + my_third_list.size().string()) // 3 for n in my_third_list.values() do env.out.print("\t" + n.string()) end // Map over the third List, concatenating some "BOOM!'s" into a new List let new_list = my_third_list.map[String]({ (n) => n + " BOOM!" }) env.out.print("Mapping over our three-node list produces a new list of size: " + new_list.size().string()) // 3 env.out.print("Each node-value in the resulting list is now far more exciting:") for n in new_list.values() do env.out.print("\t" + n.string()) end // Filter the new list to extract 2 elements let filtered_list = new_list.filter({ (n) => n.string().contains("d BOOM!") }) env.out.print("Filtering our three-node list produces a new list of size: " + filtered_list.size().string()) // 2 for n in filtered_list.values() do env.out.print("\t" + n.string()) // Second BOOM!\nThird BOOM! end // Partition the filtered list let partitioned_lists = filtered_list.partition({ (n) => n.string().contains("Second") }) env.out.print("The size of our first partitioned list (matches predicate): " + partitioned_lists._1.size().string()) // 1 env.out.print("The size of our second partitioned list (doesn't match predicate): " + partitioned_lists._2.size().string()) // 1 env.out.print("Our matching partition elements are:") for n in partitioned_lists._1.values() do env.out.print("\t" + n.string()) // Second BOOM! end ``` ``` class ref List[A: A] is Seq[A] ref ``` #### Implements * [Seq](builtin-seq)[A] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/list/#L123) Do nothing, but be compatible with Seq. ``` new ref create( len: USize val = 0) : List[A] ref^ ``` #### Parameters * len: [USize](builtin-usize) val = 0 #### Returns * [List](index)[A] ref^ ### unit [[Source]](https://stdlib.ponylang.io/src/collections/list/#L129) Builds a new list from an element. ``` new ref unit( a: A) : List[A] ref^ ``` #### Parameters * a: A #### Returns * [List](index)[A] ref^ ### from [[Source]](https://stdlib.ponylang.io/src/collections/list/#L135) Builds a new list from the sequence passed in. ``` new ref from( seq: Array[A^] ref) : List[A] ref^ ``` #### Parameters * seq: [Array](builtin-array)[A^] ref #### Returns * [List](index)[A] ref^ Public Functions ---------------- ### reserve [[Source]](https://stdlib.ponylang.io/src/collections/list/#L143) Do nothing, but be compatible with Seq. ``` fun ref reserve( len: USize val) : None val ``` #### Parameters * len: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### size [[Source]](https://stdlib.ponylang.io/src/collections/list/#L149) Returns the number of items in the list. ``` fun box size() : USize val ``` #### Returns * [USize](builtin-usize) val ### apply [[Source]](https://stdlib.ponylang.io/src/collections/list/#L155) Get the i-th element, raising an error if the index is out of bounds. ``` fun box apply( i: USize val = 0) : this->A ? ``` #### Parameters * i: [USize](builtin-usize) val = 0 #### Returns * this->A ? ### update [[Source]](https://stdlib.ponylang.io/src/collections/list/#L161) Change the i-th element, raising an error if the index is out of bounds. Returns the previous value, which may be None if the node has been popped but left on the list. ``` fun ref update( i: USize val, value: A) : A^ ? ``` #### Parameters * i: [USize](builtin-usize) val * value: A #### Returns * A^ ? ### index [[Source]](https://stdlib.ponylang.io/src/collections/list/#L169) Gets the i-th node, raising an error if the index is out of bounds. ``` fun box index( i: USize val) : this->ListNode[A] ref ? ``` #### Parameters * i: [USize](builtin-usize) val #### Returns * this->[ListNode](collections-listnode)[A] ref ? ### remove [[Source]](https://stdlib.ponylang.io/src/collections/list/#L187) Remove the i-th node, raising an error if the index is out of bounds. The removed node is returned. ``` fun ref remove( i: USize val) : ListNode[A] ref ? ``` #### Parameters * i: [USize](builtin-usize) val #### Returns * [ListNode](collections-listnode)[A] ref ? ### clear [[Source]](https://stdlib.ponylang.io/src/collections/list/#L194) Empties the list. ``` fun ref clear() : None val ``` #### Returns * [None](builtin-none) val ### head [[Source]](https://stdlib.ponylang.io/src/collections/list/#L202) Get the head of the list. ``` fun box head() : this->ListNode[A] ref ? ``` #### Returns * this->[ListNode](collections-listnode)[A] ref ? ### tail [[Source]](https://stdlib.ponylang.io/src/collections/list/#L208) Get the tail of the list. ``` fun box tail() : this->ListNode[A] ref ? ``` #### Returns * this->[ListNode](collections-listnode)[A] ref ? ### prepend\_node [[Source]](https://stdlib.ponylang.io/src/collections/list/#L214) Adds a node to the head of the list. ``` fun ref prepend_node( node: ListNode[A] ref) : None val ``` #### Parameters * node: [ListNode](collections-listnode)[A] ref #### Returns * [None](builtin-none) val ### append\_node [[Source]](https://stdlib.ponylang.io/src/collections/list/#L225) Adds a node to the tail of the list. ``` fun ref append_node( node: ListNode[A] ref) : None val ``` #### Parameters * node: [ListNode](collections-listnode)[A] ref #### Returns * [None](builtin-none) val ### append\_list [[Source]](https://stdlib.ponylang.io/src/collections/list/#L236) Remove all nodes from that and append them to this. ``` fun ref append_list( that: List[A] ref) : None val ``` #### Parameters * that: [List](index)[A] ref #### Returns * [None](builtin-none) val ### prepend\_list [[Source]](https://stdlib.ponylang.io/src/collections/list/#L246) Remove all nodes from that and prepend them to this. ``` fun ref prepend_list( that: List[A] ref) : None val ``` #### Parameters * that: [List](index)[A] ref #### Returns * [None](builtin-none) val ### push [[Source]](https://stdlib.ponylang.io/src/collections/list/#L256) Adds a value to the tail of the list. ``` fun ref push( a: A) : None val ``` #### Parameters * a: A #### Returns * [None](builtin-none) val ### pop [[Source]](https://stdlib.ponylang.io/src/collections/list/#L262) Removes a value from the tail of the list. ``` fun ref pop() : A^ ? ``` #### Returns * A^ ? ### unshift [[Source]](https://stdlib.ponylang.io/src/collections/list/#L268) Adds a value to the head of the list. ``` fun ref unshift( a: A) : None val ``` #### Parameters * a: A #### Returns * [None](builtin-none) val ### shift [[Source]](https://stdlib.ponylang.io/src/collections/list/#L274) Removes a value from the head of the list. ``` fun ref shift() : A^ ? ``` #### Returns * A^ ? ### append [[Source]](https://stdlib.ponylang.io/src/collections/list/#L280) Append len elements from a sequence, starting from the given offset. ``` fun ref append( seq: (ReadSeq[A] box & ReadElement[A^] box), offset: USize val = 0, len: USize val = call) : None val ``` #### Parameters * seq: ([ReadSeq](builtin-readseq)[A] box & [ReadElement](builtin-readelement)[A^] box) * offset: [USize](builtin-usize) val = 0 * len: [USize](builtin-usize) val = call #### Returns * [None](builtin-none) val ### concat [[Source]](https://stdlib.ponylang.io/src/collections/list/#L305) Add len iterated elements to the end of the list, starting from the given offset. ``` fun ref concat( iter: Iterator[A^] ref, offset: USize val = 0, len: USize val = call) : None val ``` #### Parameters * iter: [Iterator](builtin-iterator)[A^] ref * offset: [USize](builtin-usize) val = 0 * len: [USize](builtin-usize) val = call #### Returns * [None](builtin-none) val ### truncate [[Source]](https://stdlib.ponylang.io/src/collections/list/#L328) Truncate the list to the given length, discarding excess elements. If the list is already smaller than len, do nothing. ``` fun ref truncate( len: USize val) : None val ``` #### Parameters * len: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### clone [[Source]](https://stdlib.ponylang.io/src/collections/list/#L339) Clone the list. ``` fun box clone() : List[this->A!] ref^ ``` #### Returns * [List](index)[this->A!] ref^ ### map[B: B] [[Source]](https://stdlib.ponylang.io/src/collections/list/#L350) Builds a new list by applying a function to every member of the list. ``` fun box map[B: B]( f: {(this->A!): B^}[A, B] box) : List[B] ref^ ``` #### Parameters * f: {(this->A!): B^}[A, B] box #### Returns * [List](index)[B] ref^ ### flat\_map[B: B] [[Source]](https://stdlib.ponylang.io/src/collections/list/#L377) Builds a new list by applying a function to every member of the list and using the elements of the resulting lists. ``` fun box flat_map[B: B]( f: {(this->A!): List[B]}[A, B] box) : List[B] ref^ ``` #### Parameters * f: {(this->A!): List[B]}[A, B] box #### Returns * [List](index)[B] ref^ ### filter [[Source]](https://stdlib.ponylang.io/src/collections/list/#L404) Builds a new list with those elements that satisfy a provided predicate. ``` fun box filter( f: {(this->A!): Bool}[A] box) : List[this->A!] ref^ ``` #### Parameters * f: {(this->A!): Bool}[A] box #### Returns * [List](index)[this->A!] ref^ ### fold[B: B] [[Source]](https://stdlib.ponylang.io/src/collections/list/#L433) Folds the elements of the list using the supplied function. ``` fun box fold[B: B]( f: {(B!, this->A!): B^}[A, B] box, acc: B) : B ``` #### Parameters * f: {(B!, this->A!): B^}[A, B] box * acc: B #### Returns * B ### every [[Source]](https://stdlib.ponylang.io/src/collections/list/#L463) Returns true if every element satisfies the provided predicate, false otherwise. ``` fun box every( f: {(this->A!): Bool}[A] box) : Bool val ``` #### Parameters * f: {(this->A!): Bool}[A] box #### Returns * [Bool](builtin-bool) val ### exists [[Source]](https://stdlib.ponylang.io/src/collections/list/#L488) Returns true if at least one element satisfies the provided predicate, false otherwise. ``` fun box exists( f: {(this->A!): Bool}[A] box) : Bool val ``` #### Parameters * f: {(this->A!): Bool}[A] box #### Returns * [Bool](builtin-bool) val ### partition [[Source]](https://stdlib.ponylang.io/src/collections/list/#L513) Builds a pair of lists, the first of which is made up of the elements satisfying the supplied predicate and the second of which is made up of those that do not. ``` fun box partition( f: {(this->A!): Bool}[A] box) : (List[this->A!] ref^ , List[this->A!] ref^) ``` #### Parameters * f: {(this->A!): Bool}[A] box #### Returns * ([List](index)[this->A!] ref^ , [List](index)[this->A!] ref^) ### drop [[Source]](https://stdlib.ponylang.io/src/collections/list/#L529) Builds a list by dropping the first n elements. ``` fun box drop( n: USize val) : List[this->A!] ref^ ``` #### Parameters * n: [USize](builtin-usize) val #### Returns * [List](index)[this->A!] ref^ ### take [[Source]](https://stdlib.ponylang.io/src/collections/list/#L547) Builds a list of the first n elements. ``` fun box take( n: USize val) : List[this->A!] ref ``` #### Parameters * n: [USize](builtin-usize) val #### Returns * [List](index)[this->A!] ref ### take\_while [[Source]](https://stdlib.ponylang.io/src/collections/list/#L565) Builds a list of elements satisfying the provided predicate until one does not. ``` fun box take_while( f: {(this->A!): Bool}[A] box) : List[this->A!] ref^ ``` #### Parameters * f: {(this->A!): Bool}[A] box #### Returns * [List](index)[this->A!] ref^ ### reverse [[Source]](https://stdlib.ponylang.io/src/collections/list/#L585) Builds a new list by reversing the elements in the list. ``` fun box reverse() : List[this->A!] ref^ ``` #### Returns * [List](index)[this->A!] ref^ ### contains[optional B: (A & [HasEq](builtin-haseq)[A!] #read)] [[Source]](https://stdlib.ponylang.io/src/collections/list/#L607) Returns true if the list contains the provided element, false otherwise. ``` fun box contains[optional B: (A & HasEq[A!] #read)]( a: box->B) : Bool val ``` #### Parameters * a: box->B #### Returns * [Bool](builtin-bool) val ### nodes [[Source]](https://stdlib.ponylang.io/src/collections/list/#L635) Return an iterator on the nodes in the list. ``` fun box nodes() : ListNodes[A, this->ListNode[A] ref] ref^ ``` #### Returns * [ListNodes](collections-listnodes)[A, this->[ListNode](collections-listnode)[A] ref] ref^ ### rnodes [[Source]](https://stdlib.ponylang.io/src/collections/list/#L641) Return an iterator on the nodes in the list. ``` fun box rnodes() : ListNodes[A, this->ListNode[A] ref] ref^ ``` #### Returns * [ListNodes](collections-listnodes)[A, this->[ListNode](collections-listnode)[A] ref] ref^ ### values [[Source]](https://stdlib.ponylang.io/src/collections/list/#L647) Return an iterator on the values in the list. ``` fun box values() : ListValues[A, this->ListNode[A] ref] ref^ ``` #### Returns * [ListValues](collections-listvalues)[A, this->[ListNode](collections-listnode)[A] ref] ref^ ### rvalues [[Source]](https://stdlib.ponylang.io/src/collections/list/#L653) Return an iterator on the values in the list. ``` fun box rvalues() : ListValues[A, this->ListNode[A] ref] ref^ ``` #### Returns * [ListValues](collections-listvalues)[A, this->[ListNode](collections-listnode)[A] ref] ref^ pony FileSeek FileSeek ======== [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L30) ``` primitive val FileSeek ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L30) ``` new val create() : FileSeek val^ ``` #### Returns * [FileSeek](index) val^ Public Functions ---------------- ### value [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L31) ``` fun box value() : U32 val ``` #### Returns * [U32](builtin-u32) val ### eq [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L31) ``` fun box eq( that: FileSeek val) : Bool val ``` #### Parameters * that: [FileSeek](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L31) ``` fun box ne( that: FileSeek val) : Bool val ``` #### Parameters * that: [FileSeek](index) val #### Returns * [Bool](builtin-bool) val
programming_docs
pony HasEq[A: A] HasEq[A: A] =========== [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L15) ``` interface ref HasEq[A: A] ``` Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L16) ``` fun box eq( that: box->A) : Bool val ``` #### Parameters * that: box->A #### Returns * [Bool](builtin-bool) val pony FileOK FileOK ====== [[Source]](https://stdlib.ponylang.io/src/files/file/#L24) ``` primitive val FileOK ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file/#L24) ``` new val create() : FileOK val^ ``` #### Returns * [FileOK](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/files/file/#L25) ``` fun box eq( that: FileOK val) : Bool val ``` #### Parameters * that: [FileOK](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/file/#L25) ``` fun box ne( that: FileOK val) : Bool val ``` #### Parameters * that: [FileOK](index) val #### Returns * [Bool](builtin-bool) val pony WriteError WriteError ========== [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L50) ``` primitive val WriteError ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L50) ``` new val create() : WriteError val^ ``` #### Returns * [WriteError](index) val^ Public Functions ---------------- ### string [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L51) ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### eq [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L51) ``` fun box eq( that: WriteError val) : Bool val ``` #### Parameters * that: [WriteError](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L51) ``` fun box ne( that: WriteError val) : Bool val ``` #### Parameters * that: [WriteError](index) val #### Returns * [Bool](builtin-bool) val pony TCPListener TCPListener =========== [[Source]](https://stdlib.ponylang.io/src/net/tcp_listener/#L3) Listens for new network connections. The following program creates an echo server that listens for connections on port 8989 and echoes back any data it receives. ``` use "net" class MyTCPConnectionNotify is TCPConnectionNotify fun ref received( conn: TCPConnection ref, data: Array[U8] iso, times: USize) : Bool => conn.write(String.from_array(consume data)) true fun ref connect_failed(conn: TCPConnection ref) => None class MyTCPListenNotify is TCPListenNotify fun ref connected(listen: TCPListener ref): TCPConnectionNotify iso^ => MyTCPConnectionNotify fun ref not_listening(listen: TCPListener ref) => None actor Main new create(env: Env) => try TCPListener(env.root as AmbientAuth, recover MyTCPListenNotify end, "", "8989") end ``` ``` actor tag TCPListener ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/net/tcp_listener/#L52) Listens for both IPv4 and IPv6 connections. ``` new tag create( auth: (AmbientAuth val | NetAuth val | TCPAuth val | TCPListenAuth val), notify: TCPListenNotify iso, host: String val = "", service: String val = "0", limit: USize val = 0, read_buffer_size: USize val = 16384, yield_after_reading: USize val = 16384, yield_after_writing: USize val = 16384) : TCPListener tag^ ``` #### Parameters * auth: ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [TCPAuth](net-tcpauth) val | [TCPListenAuth](net-tcplistenauth) val) * notify: [TCPListenNotify](net-tcplistennotify) iso * host: [String](builtin-string) val = "" * service: [String](builtin-string) val = "0" * limit: [USize](builtin-usize) val = 0 * read\_buffer\_size: [USize](builtin-usize) val = 16384 * yield\_after\_reading: [USize](builtin-usize) val = 16384 * yield\_after\_writing: [USize](builtin-usize) val = 16384 #### Returns * [TCPListener](index) tag^ ### ip4 [[Source]](https://stdlib.ponylang.io/src/net/tcp_listener/#L76) Listens for IPv4 connections. ``` new tag ip4( auth: (AmbientAuth val | NetAuth val | TCPAuth val | TCPListenAuth val), notify: TCPListenNotify iso, host: String val = "", service: String val = "0", limit: USize val = 0, read_buffer_size: USize val = 16384, yield_after_reading: USize val = 16384, yield_after_writing: USize val = 16384) : TCPListener tag^ ``` #### Parameters * auth: ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [TCPAuth](net-tcpauth) val | [TCPListenAuth](net-tcplistenauth) val) * notify: [TCPListenNotify](net-tcplistennotify) iso * host: [String](builtin-string) val = "" * service: [String](builtin-string) val = "0" * limit: [USize](builtin-usize) val = 0 * read\_buffer\_size: [USize](builtin-usize) val = 16384 * yield\_after\_reading: [USize](builtin-usize) val = 16384 * yield\_after\_writing: [USize](builtin-usize) val = 16384 #### Returns * [TCPListener](index) tag^ ### ip6 [[Source]](https://stdlib.ponylang.io/src/net/tcp_listener/#L100) Listens for IPv6 connections. ``` new tag ip6( auth: (AmbientAuth val | NetAuth val | TCPAuth val | TCPListenAuth val), notify: TCPListenNotify iso, host: String val = "", service: String val = "0", limit: USize val = 0, read_buffer_size: USize val = 16384, yield_after_reading: USize val = 16384, yield_after_writing: USize val = 16384) : TCPListener tag^ ``` #### Parameters * auth: ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [TCPAuth](net-tcpauth) val | [TCPListenAuth](net-tcplistenauth) val) * notify: [TCPListenNotify](net-tcplistennotify) iso * host: [String](builtin-string) val = "" * service: [String](builtin-string) val = "0" * limit: [USize](builtin-usize) val = 0 * read\_buffer\_size: [USize](builtin-usize) val = 16384 * yield\_after\_reading: [USize](builtin-usize) val = 16384 * yield\_after\_writing: [USize](builtin-usize) val = 16384 #### Returns * [TCPListener](index) tag^ Public Behaviours ----------------- ### set\_notify [[Source]](https://stdlib.ponylang.io/src/net/tcp_listener/#L124) Change the notifier. ``` be set_notify( notify: TCPListenNotify iso) ``` #### Parameters * notify: [TCPListenNotify](net-tcplistennotify) iso ### dispose [[Source]](https://stdlib.ponylang.io/src/net/tcp_listener/#L130) Stop listening. ``` be dispose() ``` Public Functions ---------------- ### local\_address [[Source]](https://stdlib.ponylang.io/src/net/tcp_listener/#L136) Return the bound IP address. ``` fun box local_address() : NetAddress val ``` #### Returns * [NetAddress](net-netaddress) val ### close [[Source]](https://stdlib.ponylang.io/src/net/tcp_listener/#L245) Dispose of resources. ``` fun ref close() : None val ``` #### Returns * [None](builtin-none) val pony Required Required ======== [[Source]](https://stdlib.ponylang.io/src/options/options/#L73) ``` primitive val Required ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/options/options/#L73) ``` new val create() : Required val^ ``` #### Returns * [Required](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/options/options/#L74) ``` fun box eq( that: Required val) : Bool val ``` #### Parameters * that: [Required](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/options/options/#L74) ``` fun box ne( that: Required val) : Bool val ``` #### Parameters * that: [Required](index) val #### Returns * [Bool](builtin-bool) val pony DNS DNS === [[Source]](https://stdlib.ponylang.io/src/net/dns/#L3) Helper functions for resolving DNS queries. ``` primitive val DNS ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/net/dns/#L3) ``` new val create() : DNS val^ ``` #### Returns * [DNS](index) val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/net/dns/#L7) Gets all IPv4 and IPv6 addresses for a host and service. ``` fun box apply( auth: (AmbientAuth val | NetAuth val | DNSAuth val), host: String val, service: String val) : Array[NetAddress val] iso^ ``` #### Parameters * auth: ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [DNSAuth](net-dnsauth) val) * host: [String](builtin-string) val * service: [String](builtin-string) val #### Returns * [Array](builtin-array)[[NetAddress](net-netaddress) val] iso^ ### ip4 [[Source]](https://stdlib.ponylang.io/src/net/dns/#L15) Gets all IPv4 addresses for a host and service. ``` fun box ip4( auth: (AmbientAuth val | NetAuth val | DNSAuth val), host: String val, service: String val) : Array[NetAddress val] iso^ ``` #### Parameters * auth: ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [DNSAuth](net-dnsauth) val) * host: [String](builtin-string) val * service: [String](builtin-string) val #### Returns * [Array](builtin-array)[[NetAddress](net-netaddress) val] iso^ ### ip6 [[Source]](https://stdlib.ponylang.io/src/net/dns/#L23) Gets all IPv6 addresses for a host and service. ``` fun box ip6( auth: (AmbientAuth val | NetAuth val | DNSAuth val), host: String val, service: String val) : Array[NetAddress val] iso^ ``` #### Parameters * auth: ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [DNSAuth](net-dnsauth) val) * host: [String](builtin-string) val * service: [String](builtin-string) val #### Returns * [Array](builtin-array)[[NetAddress](net-netaddress) val] iso^ ### broadcast\_ip4 [[Source]](https://stdlib.ponylang.io/src/net/dns/#L31) Link-local IP4 broadcast address. ``` fun box broadcast_ip4( auth: (AmbientAuth val | NetAuth val | DNSAuth val), service: String val) : Array[NetAddress val] iso^ ``` #### Parameters * auth: ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [DNSAuth](net-dnsauth) val) * service: [String](builtin-string) val #### Returns * [Array](builtin-array)[[NetAddress](net-netaddress) val] iso^ ### broadcast\_ip6 [[Source]](https://stdlib.ponylang.io/src/net/dns/#L39) Link-local IP6 broadcast address. ``` fun box broadcast_ip6( auth: (AmbientAuth val | NetAuth val | DNSAuth val), service: String val) : Array[NetAddress val] iso^ ``` #### Parameters * auth: ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [DNSAuth](net-dnsauth) val) * service: [String](builtin-string) val #### Returns * [Array](builtin-array)[[NetAddress](net-netaddress) val] iso^ ### is\_ip4 [[Source]](https://stdlib.ponylang.io/src/net/dns/#L47) Returns true if the host is a literal IPv4 address. ``` fun box is_ip4( host: String val) : Bool val ``` #### Parameters * host: [String](builtin-string) val #### Returns * [Bool](builtin-bool) val ### is\_ip6 [[Source]](https://stdlib.ponylang.io/src/net/dns/#L53) Returns true if the host is a literal IPv6 address. ``` fun box is_ip6( host: String val) : Bool val ``` #### Parameters * host: [String](builtin-string) val #### Returns * [Bool](builtin-bool) val ### eq [[Source]](https://stdlib.ponylang.io/src/net/dns/#L7) ``` fun box eq( that: DNS val) : Bool val ``` #### Parameters * that: [DNS](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/net/dns/#L7) ``` fun box ne( that: DNS val) : Bool val ``` #### Parameters * that: [DNS](index) val #### Returns * [Bool](builtin-bool) val pony FilePermissionDenied FilePermissionDenied ==================== [[Source]](https://stdlib.ponylang.io/src/files/file/#L29) ``` primitive val FilePermissionDenied ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file/#L29) ``` new val create() : FilePermissionDenied val^ ``` #### Returns * [FilePermissionDenied](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/files/file/#L31) ``` fun box eq( that: FilePermissionDenied val) : Bool val ``` #### Parameters * that: [FilePermissionDenied](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/file/#L31) ``` fun box ne( that: FilePermissionDenied val) : Bool val ``` #### Parameters * that: [FilePermissionDenied](index) val #### Returns * [Bool](builtin-bool) val pony Vec[A: Any #share] Vec[A: [Any](builtin-any) #share] ================================= [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L3) A persistent vector based on the Hash Array Mapped Trie from 'Ideal Hash Trees' by Phil Bagwell. ``` class val Vec[A: Any #share] ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L14) ``` new val create() : Vec[A] val^ ``` #### Returns * [Vec](index)[A] val^ Public Functions ---------------- ### size [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L31) Return the amount of values in the vector. ``` fun box size() : USize val ``` #### Returns * [USize](builtin-usize) val ### apply [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L43) Get the i-th element, raising an error if the index is out of bounds. ``` fun box apply( i: USize val) : val->A ? ``` #### Parameters * i: [USize](builtin-usize) val #### Returns * val->A ? ### update [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L53) Return a vector with the i-th element changed, raising an error if the index is out of bounds. ``` fun val update( i: USize val, value: val->A) : Vec[A] val ? ``` #### Parameters * i: [USize](builtin-usize) val * value: val->A #### Returns * [Vec](index)[A] val ? ### insert [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L67) Return a vector with an element inserted. Elements after this are moved up by one index, extending the vector. An out of bounds index raises an error. ``` fun val insert( i: USize val, value: val->A) : Vec[A] val ? ``` #### Parameters * i: [USize](builtin-usize) val * value: val->A #### Returns * [Vec](index)[A] val ? ### delete [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L81) Return a vector with an element deleted. Elements after this are moved down by one index, compacting the vector. An out of bounds index raises an error. ``` fun val delete( i: USize val) : Vec[A] val ? ``` #### Parameters * i: [USize](builtin-usize) val #### Returns * [Vec](index)[A] val ? ### remove [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L94) Return a vector with n elements removed, beginning at index i. ``` fun val remove( i: USize val, n: USize val) : Vec[A] val ? ``` #### Parameters * i: [USize](builtin-usize) val * n: [USize](builtin-usize) val #### Returns * [Vec](index)[A] val ? ### push [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L106) Return a vector with the value added to the end. ``` fun val push( value: val->A) : Vec[A] val ``` #### Parameters * value: val->A #### Returns * [Vec](index)[A] val ### pop [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L138) Return a vector with the value at the end removed. ``` fun val pop() : Vec[A] val ? ``` #### Returns * [Vec](index)[A] val ? ### concat [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L156) Return a vector with the values of the given iterator added to the end. ``` fun val concat( iter: Iterator[val->A] ref) : Vec[A] val ``` #### Parameters * iter: [Iterator](builtin-iterator)[val->A] ref #### Returns * [Vec](index)[A] val ### find [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L166) Find the `nth` appearance of `value` from the beginning of the vector, starting at `offset` and examining higher indices, and using the supplied `predicate` for comparisons. Returns the index of the value, or raise an error if the value isn't present. By default, the search starts at the first element of the vector, returns the first instance of `value` found, and uses object identity for comparison. ``` fun val find( value: val->A, offset: USize val = 0, nth: USize val = 0, predicate: {(A, A): Bool}[A] val = lambda) : USize val ? ``` #### Parameters * value: val->A * offset: [USize](builtin-usize) val = 0 * nth: [USize](builtin-usize) val = 0 * predicate: {(A, A): Bool}[A] val = lambda #### Returns * [USize](builtin-usize) val ? ### contains [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L192) Returns true if the vector contains `value`, false otherwise. ``` fun val contains( value: val->A, predicate: {(A, A): Bool}[A] val = lambda) : Bool val ``` #### Parameters * value: val->A * predicate: {(A, A): Bool}[A] val = lambda #### Returns * [Bool](builtin-bool) val ### slice [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L205) Return a vector that is a clone of a portion of this vector. The range is exclusive and saturated. ``` fun val slice( from: USize val = 0, to: USize val = call, step: USize val = 1) : Vec[A] val ``` #### Parameters * from: [USize](builtin-usize) val = 0 * to: [USize](builtin-usize) val = call * step: [USize](builtin-usize) val = 1 #### Returns * [Vec](index)[A] val ### reverse [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L216) Return a vector with the elements in reverse order. ``` fun val reverse() : Vec[A] val ``` #### Returns * [Vec](index)[A] val ### keys [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L226) Return an iterator over the indices in the vector. ``` fun val keys() : VecKeys[A] ref^ ``` #### Returns * [VecKeys](collections-persistent-veckeys)[A] ref^ ### values [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L232) Return an iterator over the values in the vector. ``` fun val values() : VecValues[A] ref^ ``` #### Returns * [VecValues](collections-persistent-vecvalues)[A] ref^ ### pairs [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L238) Return an iterator over the (index, value) pairs in the vector. ``` fun val pairs() : VecPairs[A] ref^ ``` #### Returns * [VecPairs](collections-persistent-vecpairs)[A] ref^ pony Promise[A: Any #share] Promise[A: [Any](builtin-any) #share] ===================================== [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L94) A promise to eventually produce a result of type A. This promise can either be fulfilled or rejected. Any number of promises can be chained after this one. ``` actor tag Promise[A: Any #share] ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L94) ``` new tag create() : Promise[A] tag^ ``` #### Returns * [Promise](index)[A] tag^ Public Behaviours ----------------- ### apply [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L104) Fulfill the promise. ``` be apply( value: A) ``` #### Parameters * value: A ### reject [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L120) Reject the promise. ``` be reject() ``` Public Functions ---------------- ### next[B: [Any](builtin-any) #share] [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L136) Chain a promise after this one. When this promise is fulfilled, the result of type A is passed to the fulfill function, generating in an intermediate result of type B. This is then used to fulfill the next promise in the chain. If there is no fulfill function, or if the fulfill function raises an error, then the next promise in the chain will be rejected. If this promise is rejected, this step's reject function is called with no input, generating an intermediate result of type B which is used to fulfill the next promise in the chain. If there is no reject function, of if the reject function raises an error, then the next promise in the chain will be rejected. ``` fun tag next[B: Any #share]( fulfill: Fulfill[A, B] iso, rejected: Reject[B] iso = qualify) : Promise[B] tag ``` #### Parameters * fulfill: [Fulfill](promises-fulfill)[A, B] iso * rejected: [Reject](promises-reject)[B] iso = qualify #### Returns * [Promise](index)[B] tag ### add[optional B: [Any](builtin-any) #share] [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L163) Add two promises into one promise that returns the result of both when they are fulfilled. If either of the promises is rejected then the new promise is also rejected. ``` fun tag add[optional B: Any #share]( p: Promise[B] tag) : Promise[(A , B)] tag ``` #### Parameters * p: [Promise](index)[B] tag #### Returns * [Promise](index)[(A , B)] tag ### join [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L199) Create a promise that is fulfilled when the receiver and all promises in the given iterator are fulfilled. If the receiver or any promise in the sequence is rejected then the new promise is also rejected. Join `p1` and `p2` with an existing promise, `p3`. ``` use "promises" actor Main new create(env: Env) => let p1 = Promise[String val] let p2 = Promise[String val] let p3 = Promise[String val] p3.join([p1; p2].values()) .next[None]({(a: Array[String val] val) => for s in a.values() do env.out.print(s) end }) p2("second") p3("third") p1("first") ``` ``` fun tag join( ps: Iterator[Promise[A] tag] ref) : Promise[Array[A] val] tag ``` #### Parameters * ps: [Iterator](builtin-iterator)[[Promise](index)[A] tag] ref #### Returns * [Promise](index)[[Array](builtin-array)[A] val] tag ### select [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L233) Return a promise that is fulfilled when either promise is fulfilled, resulting in a tuple of its value and the other promise. ``` fun tag select( p: Promise[A] tag) : Promise[(A , Promise[A] tag)] tag ``` #### Parameters * p: [Promise](index)[A] tag #### Returns * [Promise](index)[(A , [Promise](index)[A] tag)] tag ### timeout [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L257) Reject the promise after the given expiration in nanoseconds. ``` fun tag timeout( expiration: U64 val) : None val ``` #### Parameters * expiration: [U64](builtin-u64) val #### Returns * [None](builtin-none) val
programming_docs
pony FileBadFileNumber FileBadFileNumber ================= [[Source]](https://stdlib.ponylang.io/src/files/file/#L27) ``` primitive val FileBadFileNumber ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file/#L27) ``` new val create() : FileBadFileNumber val^ ``` #### Returns * [FileBadFileNumber](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/files/file/#L28) ``` fun box eq( that: FileBadFileNumber val) : Bool val ``` #### Parameters * that: [FileBadFileNumber](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/file/#L28) ``` fun box ne( that: FileBadFileNumber val) : Bool val ``` #### Parameters * that: [FileBadFileNumber](index) val #### Returns * [Bool](builtin-bool) val pony AlignLeft AlignLeft ========= [[Source]](https://stdlib.ponylang.io/src/format/align/#L1) ``` primitive val AlignLeft ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/format/align/#L1) ``` new val create() : AlignLeft val^ ``` #### Returns * [AlignLeft](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/format/align/#L2) ``` fun box eq( that: AlignLeft val) : Bool val ``` #### Parameters * that: [AlignLeft](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/format/align/#L2) ``` fun box ne( that: AlignLeft val) : Bool val ``` #### Parameters * that: [AlignLeft](index) val #### Returns * [Bool](builtin-bool) val pony DebugErr DebugErr ======== [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L20) ``` primitive val DebugErr ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L20) ``` new val create() : DebugErr val^ ``` #### Returns * [DebugErr](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L22) ``` fun box eq( that: DebugErr val) : Bool val ``` #### Parameters * that: [DebugErr](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L22) ``` fun box ne( that: DebugErr val) : Bool val ``` #### Parameters * that: [DebugErr](index) val #### Returns * [Bool](builtin-bool) val pony SignedInteger[A: SignedInteger[A, B] val, B: UnsignedInteger[B] val] SignedInteger[A: [SignedInteger](index)[A, B] val, B: [UnsignedInteger](builtin-unsignedinteger)[B] val] ======================================================================================================== [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L397) ``` trait val SignedInteger[A: SignedInteger[A, B] val, B: UnsignedInteger[B] val] is Integer[A] val ``` #### Implements * [Integer](builtin-integer)[A] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L135) ``` new val create( value: A) : Real[A] val^ ``` #### Parameters * value: A #### Returns * [Real](builtin-real)[A] val^ ### from[B: (([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](builtin-i32) val | [I64](builtin-i64) val | [I128](builtin-i128) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val | [U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val | [F32](builtin-f32) val | [F64](builtin-f64) val) & [Real](builtin-real)[B] val)] [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L137) ``` new val from[B: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[B] val)]( a: B) : Real[A] val^ ``` #### Parameters * a: B #### Returns * [Real](builtin-real)[A] val^ ### min\_value [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L138) ``` new val min_value() : Real[A] val^ ``` #### Returns * [Real](builtin-real)[A] val^ ### max\_value [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L139) ``` new val max_value() : Real[A] val^ ``` #### Returns * [Real](builtin-real)[A] val^ Public Functions ---------------- ### abs [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L399) ``` fun box abs() : B ``` #### Returns * B ### shl [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L401) ``` fun box shl( y: B) : A ``` #### Parameters * y: B #### Returns * A ### shr [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L402) ``` fun box shr( y: B) : A ``` #### Parameters * y: B #### Returns * A ### shl\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L404) Unsafe operation. If bits differing from the final sign bit are shifted-out, the result is undefined. ``` fun box shl_unsafe( y: B) : A ``` #### Parameters * y: B #### Returns * A ### shr\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L412) Unsafe operation. If non-zero bits are shifted-out, the result is undefined. ``` fun box shr_unsafe( y: B) : A ``` #### Parameters * y: B #### Returns * A ### popcount [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L419) ``` fun box popcount() : B ``` #### Returns * B ### clz [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L420) ``` fun box clz() : B ``` #### Returns * B ### ctz [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L421) ``` fun box ctz() : B ``` #### Returns * B ### clz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L423) Unsafe operation. If this is 0, the result is undefined. ``` fun box clz_unsafe() : B ``` #### Returns * B ### ctz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L429) Unsafe operation. If this is 0, the result is undefined. ``` fun box ctz_unsafe() : B ``` #### Returns * B ### bitwidth [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L435) ``` fun box bitwidth() : B ``` #### Returns * B ### bytewidth [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L437) ``` fun box bytewidth() : USize val ``` #### Returns * [USize](builtin-usize) val ### string [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L439) ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### add\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L214) ``` fun box add_unsafe( y: A) : A ``` #### Parameters * y: A #### Returns * A ### sub\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L221) ``` fun box sub_unsafe( y: A) : A ``` #### Parameters * y: A #### Returns * A ### mul\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L228) ``` fun box mul_unsafe( y: A) : A ``` #### Parameters * y: A #### Returns * A ### div\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L235) ``` fun box div_unsafe( y: A) : A ``` #### Parameters * y: A #### Returns * A ### divrem\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L245) ``` fun box divrem_unsafe( y: A) : (A , A) ``` #### Parameters * y: A #### Returns * (A , A) ### rem\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L255) ``` fun box rem_unsafe( y: A) : A ``` #### Parameters * y: A #### Returns * A ### fld\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L265) ``` fun box fld_unsafe( y: A) : A ``` #### Parameters * y: A #### Returns * A ### mod\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L276) ``` fun box mod_unsafe( y: A) : A ``` #### Parameters * y: A #### Returns * A ### add\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L286) ``` fun box add_partial( y: A) : A ? ``` #### Parameters * y: A #### Returns * A ? ### sub\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L293) ``` fun box sub_partial( y: A) : A ? ``` #### Parameters * y: A #### Returns * A ? ### mul\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L300) ``` fun box mul_partial( y: A) : A ? ``` #### Parameters * y: A #### Returns * A ? ### div\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L307) ``` fun box div_partial( y: A) : A ? ``` #### Parameters * y: A #### Returns * A ? ### rem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L314) ``` fun box rem_partial( y: A) : A ? ``` #### Parameters * y: A #### Returns * A ? ### divrem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L322) ``` fun box divrem_partial( y: A) : (A , A) ? ``` #### Parameters * y: A #### Returns * (A , A) ? ### fld\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L329) ``` fun box fld_partial( y: A) : A ? ``` #### Parameters * y: A #### Returns * A ? ### mod\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L336) ``` fun box mod_partial( y: A) : A ? ``` #### Parameters * y: A #### Returns * A ? ### neg\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L344) ``` fun box neg_unsafe() : A ``` #### Returns * A ### addc [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L351) ``` fun box addc( y: A) : (A , Bool val) ``` #### Parameters * y: A #### Returns * (A , [Bool](builtin-bool) val) ### subc [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L355) ``` fun box subc( y: A) : (A , Bool val) ``` #### Parameters * y: A #### Returns * (A , [Bool](builtin-bool) val) ### mulc [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L359) ``` fun box mulc( y: A) : (A , Bool val) ``` #### Parameters * y: A #### Returns * (A , [Bool](builtin-bool) val) ### divc [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L363) ``` fun box divc( y: A) : (A , Bool val) ``` #### Parameters * y: A #### Returns * (A , [Bool](builtin-bool) val) ### remc [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L367) ``` fun box remc( y: A) : (A , Bool val) ``` #### Parameters * y: A #### Returns * (A , [Bool](builtin-bool) val) ### fldc [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L373) ``` fun box fldc( y: A) : (A , Bool val) ``` #### Parameters * y: A #### Returns * (A , [Bool](builtin-bool) val) ### modc [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L377) ``` fun box modc( y: A) : (A , Bool val) ``` #### Parameters * y: A #### Returns * (A , [Bool](builtin-bool) val) ### op\_and [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L384) ``` fun box op_and( y: A) : A ``` #### Parameters * y: A #### Returns * A ### op\_or [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L385) ``` fun box op_or( y: A) : A ``` #### Parameters * y: A #### Returns * A ### op\_xor [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L386) ``` fun box op_xor( y: A) : A ``` #### Parameters * y: A #### Returns * A ### op\_not [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L387) ``` fun box op_not() : A ``` #### Returns * A ### bit\_reverse [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L389) ``` fun box bit_reverse() : A ``` #### Returns * A ### bswap [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L395) ``` fun box bswap() : A ``` #### Returns * A ### add [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L141) ``` fun box add( y: A) : A ``` #### Parameters * y: A #### Returns * A ### sub [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L142) ``` fun box sub( y: A) : A ``` #### Parameters * y: A #### Returns * A ### mul [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L143) ``` fun box mul( y: A) : A ``` #### Parameters * y: A #### Returns * A ### div [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L144) ``` fun box div( y: A) : A ``` #### Parameters * y: A #### Returns * A ### divrem [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L150) ``` fun box divrem( y: A) : (A , A) ``` #### Parameters * y: A #### Returns * (A , A) ### rem [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L151) ``` fun box rem( y: A) : A ``` #### Parameters * y: A #### Returns * A ### neg [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L159) ``` fun box neg() : A ``` #### Returns * A ### fld [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L161) ``` fun box fld( y: A) : A ``` #### Parameters * y: A #### Returns * A ### mod [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L165) ``` fun box mod( y: A) : A ``` #### Parameters * y: A #### Returns * A ### eq [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L172) ``` fun box eq( y: box->A) : Bool val ``` #### Parameters * y: box->A #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L173) ``` fun box ne( y: box->A) : Bool val ``` #### Parameters * y: box->A #### Returns * [Bool](builtin-bool) val ### lt [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L174) ``` fun box lt( y: box->A) : Bool val ``` #### Parameters * y: box->A #### Returns * [Bool](builtin-bool) val ### le [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L175) ``` fun box le( y: box->A) : Bool val ``` #### Parameters * y: box->A #### Returns * [Bool](builtin-bool) val ### ge [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L176) ``` fun box ge( y: box->A) : Bool val ``` #### Parameters * y: box->A #### Returns * [Bool](builtin-bool) val ### gt [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L177) ``` fun box gt( y: box->A) : Bool val ``` #### Parameters * y: box->A #### Returns * [Bool](builtin-bool) val ### min [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L179) ``` fun box min( y: A) : A ``` #### Parameters * y: A #### Returns * A ### max [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L180) ``` fun box max( y: A) : A ``` #### Parameters * y: A #### Returns * A ### hash [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L182) ``` fun box hash() : USize val ``` #### Returns * [USize](builtin-usize) val ### hash64 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L198) ``` fun box hash64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### i8 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L2) ``` fun box i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L3) ``` fun box i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L4) ``` fun box i32() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L5) ``` fun box i64() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L6) ``` fun box i128() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L7) ``` fun box ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L8) ``` fun box isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L10) ``` fun box u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L11) ``` fun box u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L12) ``` fun box u32() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L13) ``` fun box u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L14) ``` fun box u128() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L15) ``` fun box ulong() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L16) ``` fun box usize() : USize val ``` #### Returns * [USize](builtin-usize) val ### f32 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L18) ``` fun box f32() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64 [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L19) ``` fun box f64() : F64 val ``` #### Returns * [F64](builtin-f64) val ### i8\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L21) ``` fun box i8_unsafe() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L28) ``` fun box i16_unsafe() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L35) ``` fun box i32_unsafe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L42) ``` fun box i64_unsafe() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L49) ``` fun box i128_unsafe() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L56) ``` fun box ilong_unsafe() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L63) ``` fun box isize_unsafe() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L70) ``` fun box u8_unsafe() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L77) ``` fun box u16_unsafe() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L84) ``` fun box u32_unsafe() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L91) ``` fun box u64_unsafe() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L98) ``` fun box u128_unsafe() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L105) ``` fun box ulong_unsafe() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L112) ``` fun box usize_unsafe() : USize val ``` #### Returns * [USize](builtin-usize) val ### f32\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L119) ``` fun box f32_unsafe() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/real/#L126) ``` fun box f64_unsafe() : F64 val ``` #### Returns * [F64](builtin-f64) val ### compare ``` fun box compare( that: box->A) : (Less val | Equal val | Greater val) ``` #### Parameters * that: box->A #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val)
programming_docs
pony Nanos Nanos ===== [[Source]](https://stdlib.ponylang.io/src/time/nanos/#L2) Collection of utility functions for converting various durations of time to nanoseconds, for passing to other functions in the time package. ``` primitive val Nanos ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/time/nanos/#L2) ``` new val create() : Nanos val^ ``` #### Returns * [Nanos](index) val^ Public Functions ---------------- ### from\_seconds [[Source]](https://stdlib.ponylang.io/src/time/nanos/#L7) ``` fun box from_seconds( t: U64 val) : U64 val ``` #### Parameters * t: [U64](builtin-u64) val #### Returns * [U64](builtin-u64) val ### from\_millis [[Source]](https://stdlib.ponylang.io/src/time/nanos/#L10) ``` fun box from_millis( t: U64 val) : U64 val ``` #### Parameters * t: [U64](builtin-u64) val #### Returns * [U64](builtin-u64) val ### from\_micros [[Source]](https://stdlib.ponylang.io/src/time/nanos/#L13) ``` fun box from_micros( t: U64 val) : U64 val ``` #### Parameters * t: [U64](builtin-u64) val #### Returns * [U64](builtin-u64) val ### from\_seconds\_f [[Source]](https://stdlib.ponylang.io/src/time/nanos/#L16) ``` fun box from_seconds_f( t: F64 val) : U64 val ``` #### Parameters * t: [F64](builtin-f64) val #### Returns * [U64](builtin-u64) val ### from\_millis\_f [[Source]](https://stdlib.ponylang.io/src/time/nanos/#L19) ``` fun box from_millis_f( t: F64 val) : U64 val ``` #### Parameters * t: [F64](builtin-f64) val #### Returns * [U64](builtin-u64) val ### from\_micros\_f [[Source]](https://stdlib.ponylang.io/src/time/nanos/#L22) ``` fun box from_micros_f( t: F64 val) : U64 val ``` #### Parameters * t: [F64](builtin-f64) val #### Returns * [U64](builtin-u64) val ### from\_wall\_clock [[Source]](https://stdlib.ponylang.io/src/time/nanos/#L25) ``` fun box from_wall_clock( wall: (I64 val , I64 val)) : U64 val ``` #### Parameters * wall: ([I64](builtin-i64) val , [I64](builtin-i64) val) #### Returns * [U64](builtin-u64) val ### eq [[Source]](https://stdlib.ponylang.io/src/time/nanos/#L7) ``` fun box eq( that: Nanos val) : Bool val ``` #### Parameters * that: [Nanos](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/time/nanos/#L7) ``` fun box ne( that: Nanos val) : Bool val ``` #### Parameters * that: [Nanos](index) val #### Returns * [Bool](builtin-bool) val pony Fulfill[A: Any #share, B: Any #share] Fulfill[A: [Any](builtin-any) #share, B: [Any](builtin-any) #share] =================================================================== [[Source]](https://stdlib.ponylang.io/src/promises/fulfill/#L4) A function from A to B that is called when a promise is fulfilled. ``` interface iso Fulfill[A: Any #share, B: Any #share] ``` Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/promises/fulfill/#L8) ``` fun ref apply( value: A) : B ? ``` #### Parameters * value: A #### Returns * B ? pony FormatGeneralLarge FormatGeneralLarge ================== [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L32) ``` primitive val FormatGeneralLarge is FormatSpec val ``` #### Implements * [FormatSpec](format-formatspec) val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L32) ``` new val create() : FormatGeneralLarge val^ ``` #### Returns * [FormatGeneralLarge](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L34) ``` fun box eq( that: FormatGeneralLarge val) : Bool val ``` #### Parameters * that: [FormatGeneralLarge](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L34) ``` fun box ne( that: FormatGeneralLarge val) : Bool val ``` #### Parameters * that: [FormatGeneralLarge](index) val #### Returns * [Bool](builtin-bool) val pony SerialiseAuth SerialiseAuth ============= [[Source]](https://stdlib.ponylang.io/src/serialise/serialise/#L40) This is a capability that allows the holder to serialise objects. It does not allow the holder to examine serialised data or to deserialise objects. ``` primitive val SerialiseAuth ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/serialise/serialise/#L45) ``` new val create( auth: AmbientAuth val) : SerialiseAuth val^ ``` #### Parameters * auth: [AmbientAuth](builtin-ambientauth) val #### Returns * [SerialiseAuth](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/serialise/serialise/#L45) ``` fun box eq( that: SerialiseAuth val) : Bool val ``` #### Parameters * that: [SerialiseAuth](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/serialise/serialise/#L45) ``` fun box ne( that: SerialiseAuth val) : Bool val ``` #### Parameters * that: [SerialiseAuth](index) val #### Returns * [Bool](builtin-bool) val pony Signals package Signals package =============== The Signals package provides support for handling Unix style signals. For each signal that you want to handle, you need to create a `SignalHandler` and a corresponding `SignalNotify` object. Each SignalHandler runs as it own actor and upon receiving the signal will call its corresponding `SignalNotify`'s apply method. Example program --------------- The following program will listen for the TERM signal and output a message to standard out if it is received. ``` use "signals" actor Main new create(env: Env) => // Create a TERM handler let signal = SignalHandler(TermHandler(env), Sig.term()) // Raise TERM signal signal.raise() class TermHandler is SignalNotify let _env: Env new iso create(env: Env) => _env = env fun ref apply(count: U32): Bool => _env.out.print("TERM signal received") true ``` Signal portability ------------------ The `Sig` primitive provides support for portable signal handling across Linux, FreeBSD and OSX. Signals are not supported on Windows and attempting to use them will cause a compilation error. Shutting down handlers ---------------------- Unlike a `TCPConnection` and other forms of input receiving, creating a `SignalHandler` will not keep your program running. As such, you are not required to call `dispose` on your signal handlers in order to shutdown your program. Public Types ------------ * [interface SignalNotify](signals-signalnotify) * [primitive SignalRaise](signals-signalraise) * [actor SignalHandler](signals-signalhandler) * [primitive Sig](signals-sig) pony TCPConnectAuth TCPConnectAuth ============== [[Source]](https://stdlib.ponylang.io/src/net/auth/#L21) ``` primitive val TCPConnectAuth ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/net/auth/#L22) ``` new val create( from: (AmbientAuth val | NetAuth val | TCPAuth val)) : TCPConnectAuth val^ ``` #### Parameters * from: ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [TCPAuth](net-tcpauth) val) #### Returns * [TCPConnectAuth](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/net/auth/#L22) ``` fun box eq( that: TCPConnectAuth val) : Bool val ``` #### Parameters * that: [TCPConnectAuth](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/net/auth/#L22) ``` fun box ne( that: TCPConnectAuth val) : Bool val ``` #### Parameters * that: [TCPConnectAuth](index) val #### Returns * [Bool](builtin-bool) val pony Signed Signed ====== [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L905) ``` type Signed is (I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val) ``` #### Type Alias For * ([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](builtin-i32) val | [I64](builtin-i64) val | [I128](builtin-i128) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val) pony SyntaxError SyntaxError =========== [[Source]](https://stdlib.ponylang.io/src/cli/command/#L181) SyntaxError summarizes a syntax error in a given parsed command line. ``` class val SyntaxError ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/cli/command/#L188) ``` new val create( token': String val, msg': String val) : SyntaxError val^ ``` #### Parameters * token': [String](builtin-string) val * msg': [String](builtin-string) val #### Returns * [SyntaxError](index) val^ Public Functions ---------------- ### token [[Source]](https://stdlib.ponylang.io/src/cli/command/#L192) ``` fun box token() : String val ``` #### Returns * [String](builtin-string) val ### string [[Source]](https://stdlib.ponylang.io/src/cli/command/#L194) ``` fun box string() : String val ``` #### Returns * [String](builtin-string) val pony Promises[A: Any #share] Promises[A: [Any](builtin-any) #share] ====================================== [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L284) ``` primitive val Promises[A: Any #share] ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L284) ``` new val create() : Promises[A] val^ ``` #### Returns * [Promises](index)[A] val^ Public Functions ---------------- ### join [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L285) Create a promise that is fulfilled when all promises in the given sequence are fulfilled. If any promise in the sequence is rejected then the new promise is also rejected. The order that values appear in the final array is based on when each promise is fulfilled and not the order that they are given. Join three existing promises to make a fourth. ``` use "promises" actor Main new create(env: Env) => let p1 = Promise[String val] let p2 = Promise[String val] let p3 = Promise[String val] Promises[String val].join([p1; p2; p3].values()) .next[None]({(a: Array[String val] val) => for s in a.values() do env.out.print(s) end }) p2("second") p3("third") p1("first") ``` ``` fun box join( ps: Iterator[Promise[A] tag] ref) : Promise[Array[A] val] tag ``` #### Parameters * ps: [Iterator](builtin-iterator)[[Promise](promises-promise)[A] tag] ref #### Returns * [Promise](promises-promise)[[Array](builtin-array)[A] val] tag ### eq [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L285) ``` fun box eq( that: Promises[A] val) : Bool val ``` #### Parameters * that: [Promises](index)[A] val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/promises/promise/#L285) ``` fun box ne( that: Promises[A] val) : Bool val ``` #### Parameters * that: [Promises](index)[A] val #### Returns * [Bool](builtin-bool) val pony PonyTest package PonyTest package ================ The PonyTest package provides a unit testing framework. It is designed to be as simple as possible to use, both for the unit test writer and the user running the tests. To help simplify test writing and distribution this package depends on as few other packages as possible. Currently the required packages are: * builtin * time * collections Each unit test is a class, with a single test function. By default all tests run concurrently. Each test run is provided with a helper object. This provides logging and assertion functions. By default log messages are only shown for tests that fail. When any assertion function fails the test is counted as a fail. However, tests can also indicate failure by raising an error in the test function. Example program --------------- To use PonyTest simply write a class for each test and a TestList type that tells the PonyTest object about the tests. Typically the TestList will be Main for the package. The following is a complete program with 2 trivial tests. ``` use "ponytest" actor Main is TestList new create(env: Env) => PonyTest(env, this) new make() => None fun tag tests(test: PonyTest) => test(_TestAdd) test(_TestSub) class iso _TestAdd is UnitTest fun name():String => "addition" fun apply(h: TestHelper) => h.assert_eq[U32](4, 2 + 2) class iso _TestSub is UnitTest fun name():String => "subtraction" fun apply(h: TestHelper) => h.assert_eq[U32](2, 4 - 2) ``` The make() constructor is not needed for this example. However, it allows for easy aggregation of tests (see below) so it is recommended that all test Mains provide it. Main.create() is called only for program invocations on the current package. Main.make() is called during aggregation. If so desired extra code can be added to either of these constructors to perform additional tasks. Test names ---------- Tests are identified by names, which are used when printing test results and on the command line to select which tests to run. These names are independent of the names of the test classes in the Pony source code. Arbitrary strings can be used for these names, but for large projects it is strongly recommended to use a hierarchical naming scheme to make it easier to select groups of tests. You can skip any tests whose names start with a given string by using the `--exclude=[prefix]` command line option. You can run only tests whose names start with a given string by using the `--only=[prefix]` command line option. Aggregation ----------- Often it is desirable to run a collection of unit tests from multiple different source files. For example, if several packages within a bundle each have their own unit tests it may be useful to run all tests for the bundle together. This can be achieved by writing an aggregate test list class, which calls the list function for each package. The following is an example that aggregates the tests from packages `foo` and `bar`. ``` use "ponytest" use foo = "foo" use bar = "bar" actor Main is TestList new create(env: Env) => PonyTest(env, this) new make() => None fun tag tests(test: PonyTest) => foo.Main.make().tests(test) bar.Main.make().tests(test) ``` Aggregate test classes may themselves be aggregated. Every test list class may contain any combination of its own tests and aggregated lists. Long tests ---------- Simple tests run within a single function. When that function exits, either returning or raising an error, the test is complete. This is not viable for tests that need to use actors. Long tests allow for delayed completion. Any test can call long\_test() on its TestHelper to indicate that it needs to keep running. When the test is finally complete it calls complete() on its TestHelper. The complete() function takes a Bool parameter to specify whether the test was a success. If any asserts fail then the test will be considered a failure regardless of the value of this parameter. However, complete() must still be called. Since failing tests may hang, a timeout must be specified for each long test. When the test function exits a timer is started with the specified timeout. If this timer fires before complete() is called the test is marked as a failure and the timeout is reported. On a timeout the timed\_out() function is called on the unit test object. This should perform whatever test specific tidy up is required to allow the program to exit. There is no need to call complete() if a timeout occurs, although it is not an error to do so. Note that the timeout is only relevant when a test hangs and would otherwise prevent the test program from completing. Setting a very long timeout on tests that should not be able to hang is perfectly acceptable and will not make the test take any longer if successful. Timeouts should not be used as the standard method of detecting if a test has failed. Exclusion groups ---------------- By default all tests are run concurrently. This may be a problem for some tests, eg if they manipulate an external file or use a system resource. To fix this issue any number of tests may be put into an exclusion group. No tests that are in the same exclusion group will be run concurrently. Exclusion groups are identified by name, arbitrary strings may be used. Multiple exclusion groups may be used and tests in different groups may run concurrently. Tests that do not specify an exclusion group may be run concurrently with any other tests. The command line option "--sequential" prevents any tests from running concurrently, regardless of exclusion groups. This is intended for debugging rather than standard use. Labels ------ Test can have label. Labels are used to filter which tests are run, by setting command line argument `--label=[some custom label]`. It can be used to separate unit tests from integration tests. By default label is empty. You can set it up by overriding `label(): String` method in unit test. ``` use "ponytest" class iso _I8AddTest is UnitTest fun name(): String => "_I8AddTest" fun label(): String => "simple" fun apply(h: TestHelper) => h.assert_eq[I8](1, 1) ``` Setting up and tearing down a test environment ---------------------------------------------- ### Set Up Any kind of fixture or environment necessary for executing a [UnitTest](ponytest-unittest) can be set up either in the tests constructor or in a function called [set\_up()](ponytest-unittest#set_up). [set\_up()](ponytest-unittest#set_up) is called before the test is executed. It is partial, if it errors, the test is not executed but reported as failing during set up. The test's [TestHelper](ponytest-testhelper) is handed to [set\_up()](ponytest-unittest#set_up) in order to log messages or access the tests [Env](builtin-env) via [TestHelper.env](ponytest-testhelper#let-env-env-val). ### Tear Down Each unit test object may define a [tear\_down()](ponytest-unittest#tear_down) function. This is called after the test has finished to allow tearing down of any complex environment that had to be set up for the test. The [tear\_down()](ponytest-unittest#tear_down) function is called for each test regardless of whether it passed or failed. If a test times out [tear\_down()](ponytest-unittest#tear_down) will be called after timed\_out() returns. When a test is in an exclusion group, the [tear\_down()](ponytest-unittest#tear_down) call is considered part of the tests run. The next test in the exclusion group will not start until after [tear\_down()](ponytest-unittest#tear_down) returns on the current test. The test's [TestHelper](ponytest-testhelper) is handed to [tear\_down()](ponytest-unittest#tear_down) and it is permitted to log messages and call assert functions during tear down. ### Example The following example creates a temporary directory in the [set\_up()](ponytest-unittest#set_up) function and removes it in the [tear\_down()](ponytest-unittest#tear_down) function, thus simplifying the test function itself: ``` use "ponytest" use "files" class iso TempDirTest var tmp_dir: (FilePath | None) = None fun name(): String => "temp-dir" fun ref set_up(h: TestHelper)? => tmp_dir = FilePath.mkdtemp(h.env.root as AmbientAuth, "temp-dir")? fun ref tear_down(h: TestHelper) => try (tmp_dir as FilePath).remove() end fun apply(h: TestHelper)? => let dir = tmp_dir as FilePath // do something inside the temporary directory ``` Public Types ------------ * [trait UnitTest](ponytest-unittest) * [trait TestList](ponytest-testlist) * [interface ITest](ponytest-itest) * [class TestHelper](ponytest-testhelper) * [actor PonyTest](ponytest-ponytest)
programming_docs
pony XorShift128Plus XorShift128Plus =============== [[Source]](https://stdlib.ponylang.io/src/random/xorshift/#L1) This is an implementation of xorshift+, as detailed at: http://xoroshiro.di.unimi.it This should only be used for legacy applications that specifically require XorShift128Plus, otherwise use Rand. ``` class ref XorShift128Plus is Random ref ``` #### Implements * [Random](random-random) ref Constructors ------------ ### from\_u64 [[Source]](https://stdlib.ponylang.io/src/random/xorshift/#L13) Use seed x to seed a [SplitMix64](random-splitmix64) and use this to initialize the 128 bits of state. ``` new ref from_u64( x: U64 val = 5489) : XorShift128Plus ref^ ``` #### Parameters * x: [U64](builtin-u64) val = 5489 #### Returns * [XorShift128Plus](index) ref^ ### create [[Source]](https://stdlib.ponylang.io/src/random/xorshift/#L22) Create with the specified seed. Returned values are deterministic for a given seed. ``` new ref create( x: U64 val = 5489, y: U64 val = 0) : XorShift128Plus ref^ ``` #### Parameters * x: [U64](builtin-u64) val = 5489 * y: [U64](builtin-u64) val = 0 #### Returns * [XorShift128Plus](index) ref^ Public Functions ---------------- ### next [[Source]](https://stdlib.ponylang.io/src/random/xorshift/#L31) A random integer in [0, 2^64) ``` fun ref next() : U64 val ``` #### Returns * [U64](builtin-u64) val ### has\_next ``` fun tag has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### u8 ``` fun ref u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 ``` fun ref u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 ``` fun ref u32() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64 ``` fun ref u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 ``` fun ref u128() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong ``` fun ref ulong() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize ``` fun ref usize() : USize val ``` #### Returns * [USize](builtin-usize) val ### i8 ``` fun ref i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 ``` fun ref i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 ``` fun ref i32() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64 ``` fun ref i64() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128 ``` fun ref i128() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong ``` fun ref ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize ``` fun ref isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### int\_fp\_mult[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] ``` fun ref int_fp_mult[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### int[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] ``` fun ref int[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### int\_unbiased[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] ``` fun ref int_unbiased[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### real ``` fun ref real() : F64 val ``` #### Returns * [F64](builtin-f64) val ### shuffle[A: A] ``` fun ref shuffle[A: A]( array: Array[A] ref) : None val ``` #### Parameters * array: [Array](builtin-array)[A] ref #### Returns * [None](builtin-none) val pony FilePath FilePath ======== [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L9) A FilePath represents a capability to access a path. The path will be represented as an absolute path and a set of capabilities for operations on that path. ``` class val FilePath ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L24) Create a new path. The caller must either provide the root capability or an existing FilePath. If the root capability is provided, path' will be relative to the program's working directory. Otherwise, it will be relative to the existing FilePath, and the existing FilePath must be a prefix of the resulting path. The resulting FilePath will have capabilities that are the intersection of the supplied capabilities and the capabilities on the parent. ``` new val create( base: (FilePath val | AmbientAuth val), path': String val, caps': Flags[(FileCreate val | FileChmod val | FileChown val | FileLink val | FileLookup val | FileMkdir val | FileRead val | FileRemove val | FileRename val | FileSeek val | FileStat val | FileSync val | FileTime val | FileTruncate val | FileWrite val | FileExec val), U32 val] val = recover) : FilePath val^ ? ``` #### Parameters * base: ([FilePath](index) val | [AmbientAuth](builtin-ambientauth) val) * path': [String](builtin-string) val * caps': [Flags](collections-flags)[([FileCreate](files-filecreate) val | [FileChmod](files-filechmod) val | [FileChown](files-filechown) val | [FileLink](files-filelink) val | [FileLookup](files-filelookup) val | [FileMkdir](files-filemkdir) val | [FileRead](files-fileread) val | [FileRemove](files-fileremove) val | [FileRename](files-filerename) val | [FileSeek](files-fileseek) val | [FileStat](files-filestat) val | [FileSync](files-filesync) val | [FileTime](files-filetime) val | [FileTruncate](files-filetruncate) val | [FileWrite](files-filewrite) val | [FileExec](files-fileexec) val), [U32](builtin-u32) val] val = recover #### Returns * [FilePath](index) val^ ? ### mkdtemp [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L60) Create a temporary directory and returns a path to it. The directory's name will begin with `prefix`. The caller must either provide the root capability or an existing FilePath. If AmbientAuth is provided, pattern will be relative to the program's working directory. Otherwise, it will be relative to the existing FilePath, and the existing FilePath must be a prefix of the resulting path. The resulting FilePath will have capabilities that are the intersection of the supplied capabilities and the capabilities on the base. ``` new val mkdtemp( base: (FilePath val | AmbientAuth val), prefix: String val = "", caps': Flags[(FileCreate val | FileChmod val | FileChown val | FileLink val | FileLookup val | FileMkdir val | FileRead val | FileRemove val | FileRename val | FileSeek val | FileStat val | FileSync val | FileTime val | FileTruncate val | FileWrite val | FileExec val), U32 val] val = recover) : FilePath val^ ? ``` #### Parameters * base: ([FilePath](index) val | [AmbientAuth](builtin-ambientauth) val) * prefix: [String](builtin-string) val = "" * caps': [Flags](collections-flags)[([FileCreate](files-filecreate) val | [FileChmod](files-filechmod) val | [FileChown](files-filechown) val | [FileLink](files-filelink) val | [FileLookup](files-filelookup) val | [FileMkdir](files-filemkdir) val | [FileRead](files-fileread) val | [FileRemove](files-fileremove) val | [FileRename](files-filerename) val | [FileSeek](files-fileseek) val | [FileStat](files-filestat) val | [FileSync](files-filesync) val | [FileTime](files-filetime) val | [FileTruncate](files-filetruncate) val | [FileWrite](files-filewrite) val | [FileExec](files-fileexec) val), [U32](builtin-u32) val] val = recover #### Returns * [FilePath](index) val^ ? Public fields ------------- ### let path: [String](builtin-string) val [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L15) Absolute filesystem path. ### let caps: [Flags](collections-flags)[([FileCreate](files-filecreate) val | [FileChmod](files-filechmod) val | [FileChown](files-filechown) val | [FileLink](files-filelink) val | [FileLookup](files-filelookup) val | [FileMkdir](files-filemkdir) val | [FileRead](files-fileread) val | [FileRemove](files-fileremove) val | [FileRename](files-filerename) val | [FileSeek](files-fileseek) val | [FileStat](files-filestat) val | [FileSync](files-filesync) val | [FileTime](files-filetime) val | [FileTruncate](files-filetruncate) val | [FileWrite](files-filewrite) val | [FileExec](files-fileexec) val), [U32](builtin-u32) val] ref [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L19) Set of capabilities for operations on `path`. Public Functions ---------------- ### join [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L102) Return a new path relative to this one. ``` fun val join( path': String val, caps': Flags[(FileCreate val | FileChmod val | FileChown val | FileLink val | FileLookup val | FileMkdir val | FileRead val | FileRemove val | FileRename val | FileSeek val | FileStat val | FileSync val | FileTime val | FileTruncate val | FileWrite val | FileExec val), U32 val] val = recover) : FilePath val ? ``` #### Parameters * path': [String](builtin-string) val * caps': [Flags](collections-flags)[([FileCreate](files-filecreate) val | [FileChmod](files-filechmod) val | [FileChown](files-filechown) val | [FileLink](files-filelink) val | [FileLookup](files-filelookup) val | [FileMkdir](files-filemkdir) val | [FileRead](files-fileread) val | [FileRemove](files-fileremove) val | [FileRename](files-filerename) val | [FileSeek](files-fileseek) val | [FileStat](files-filestat) val | [FileSync](files-filesync) val | [FileTime](files-filetime) val | [FileTruncate](files-filetruncate) val | [FileWrite](files-filewrite) val | [FileExec](files-fileexec) val), [U32](builtin-u32) val] val = recover #### Returns * [FilePath](index) val ? ### walk [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L112) Walks a directory structure starting at this. `handler(dir_path, dir_entries)` will be called for each directory starting with this one. The handler can control which subdirectories are expanded by removing them from the `dir_entries` list. ``` fun val walk( handler: WalkHandler ref, follow_links: Bool val = false) : None val ``` #### Parameters * handler: [WalkHandler](files-walkhandler) ref * follow\_links: [Bool](builtin-bool) val = false #### Returns * [None](builtin-none) val ### canonical [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L136) Return the equivalent canonical absolute path. Raise an error if there isn't one. ``` fun val canonical() : FilePath val ? ``` #### Returns * [FilePath](index) val ? ### exists [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L143) Returns true if the path exists. Returns false for a broken symlink. ``` fun val exists() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### mkdir [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L153) Creates the directory. Will recursively create each element. Returns true if the directory exists when we're done, false if it does not. If we do not have the FileStat permission, this will return false even if the directory does exist. ``` fun val mkdir( must_create: Bool val = false) : Bool val ``` #### Parameters * must\_create: [Bool](builtin-bool) val = false #### Returns * [Bool](builtin-bool) val ### remove [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L200) Remove the file or directory. The directory contents will be removed as well, recursively. Symlinks will be removed but not traversed. ``` fun val remove() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### rename [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L242) Rename a file or directory. ``` fun box rename( new_path: FilePath val) : Bool val ``` #### Parameters * new\_path: [FilePath](index) val #### Returns * [Bool](builtin-bool) val ### symlink [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L252) Create a symlink to a file or directory. Note that on Windows a program must be running with elevated priviledges to be able to create symlinks. ``` fun val symlink( link_name: FilePath val) : Bool val ``` #### Parameters * link\_name: [FilePath](index) val #### Returns * [Bool](builtin-bool) val ### chmod [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L325) Set the FileMode for a path. ``` fun box chmod( mode: FileMode box) : Bool val ``` #### Parameters * mode: [FileMode](files-filemode) box #### Returns * [Bool](builtin-bool) val ### chown [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L341) Set the owner and group for a path. Does nothing on Windows. ``` fun box chown( uid: U32 val, gid: U32 val) : Bool val ``` #### Parameters * uid: [U32](builtin-u32) val * gid: [U32](builtin-u32) val #### Returns * [Bool](builtin-bool) val ### touch [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L355) Set the last access and modification times of a path to now. ``` fun box touch() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### set\_time [[Source]](https://stdlib.ponylang.io/src/files/file_path/#L361) Set the last access and modification times of a path to the given values. ``` fun box set_time( atime: (I64 val , I64 val), mtime: (I64 val , I64 val)) : Bool val ``` #### Parameters * atime: ([I64](builtin-i64) val , [I64](builtin-i64) val) * mtime: ([I64](builtin-i64) val , [I64](builtin-i64) val) #### Returns * [Bool](builtin-bool) val pony ByteSeq ByteSeq ======= [[Source]](https://stdlib.ponylang.io/src/builtin/std_stream/#L1) ``` type ByteSeq is (String val | Array[U8 val] val) ``` #### Type Alias For * ([String](builtin-string) val | [Array](builtin-array)[[U8](builtin-u8) val] val) pony JsonDoc JsonDoc ======= [[Source]](https://stdlib.ponylang.io/src/json/json_doc/#L4) Top level JSON type containing an entire document. A JSON document consists of exactly 1 value. ``` class ref JsonDoc ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/json/json_doc/#L24) Default constructor building a document containing a single null. ``` new ref create() : JsonDoc ref^ ``` #### Returns * [JsonDoc](index) ref^ Public fields ------------- ### var data: ([F64](builtin-f64) val | [I64](builtin-i64) val | [Bool](builtin-bool) val | ``` [None](builtin-None.md) val | [String](builtin-String.md) val | [JsonArray](json-JsonArray.md) ref | [JsonObject](json-JsonObject.md) ref) ``` [[Source]](https://stdlib.ponylang.io/src/json/json_doc/#L9) The parsed JSON structure. Will be a `None` if `parse(source: String)` has not been called yet. Public Functions ---------------- ### string [[Source]](https://stdlib.ponylang.io/src/json/json_doc/#L30) Generate string representation of this document. ``` fun box string( indent: String val = "", pretty_print: Bool val = false) : String val ``` #### Parameters * indent: [String](builtin-string) val = "" * pretty\_print: [Bool](builtin-bool) val = false #### Returns * [String](builtin-string) val ### parse [[Source]](https://stdlib.ponylang.io/src/json/json_doc/#L40) Parse the given string as a JSON file, building a document. Raise error on invalid JSON in given source. ``` fun ref parse( source: String val) : None val ? ``` #### Parameters * source: [String](builtin-string) val #### Returns * [None](builtin-none) val ? ### parse\_report [[Source]](https://stdlib.ponylang.io/src/json/json_doc/#L62) Give details of the error that occurred last time we attempted to parse. If parse was successful returns (0, ""). ``` fun box parse_report() : (USize val , String val) ``` #### Returns * ([USize](builtin-usize) val , [String](builtin-string) val) pony FileEOF FileEOF ======= [[Source]](https://stdlib.ponylang.io/src/files/file/#L26) ``` primitive val FileEOF ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file/#L26) ``` new val create() : FileEOF val^ ``` #### Returns * [FileEOF](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/files/file/#L27) ``` fun box eq( that: FileEOF val) : Bool val ``` #### Parameters * that: [FileEOF](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/file/#L27) ``` fun box ne( that: FileEOF val) : Bool val ``` #### Parameters * that: [FileEOF](index) val #### Returns * [Bool](builtin-bool) val pony Ini package Ini package =========== The Ini package provides support for parsing [INI file](https://en.wikipedia.org/wiki/INI_file) formatted text. * Currently *does not* support multi-line entries. * Any keys not in a section will be placed in the section "" Example code ============ ``` // Parses the file 'example.ini' in the current working directory // Output all the content use "ini" use "files" actor Main new create(env:Env) => try let ini_file = File(FilePath(env.root as AmbientAuth, "example.ini")?) let sections = IniParse(ini_file.lines())? for section in sections.keys() do env.out.print("Section name is: " + section) for key in sections(section)?.keys() do env.out.print(key + " = " + sections(section)?(key)?) end end end ``` Public Types ------------ * [type IniMap](ini-inimap) * [primitive IniParse](ini-iniparse) * [primitive IniIncompleteSection](ini-iniincompletesection) * [primitive IniNoDelimiter](ini-ininodelimiter) * [type IniError](ini-inierror) * [interface IniNotify](ini-ininotify) * [primitive Ini](ini-ini) pony Hashable64 Hashable64 ========== [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L7) A version of Hashable that returns 64-bit hashes on every platform. ``` interface ref Hashable64 ``` Public Functions ---------------- ### hash64 [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L11) ``` fun box hash64() : U64 val ``` #### Returns * [U64](builtin-u64) val pony Command Command ======= [[Source]](https://stdlib.ponylang.io/src/cli/command/#L3) Command contains all of the information describing a command with its spec and effective options and arguments, ready to use. ``` class box Command ``` Public Functions ---------------- ### string [[Source]](https://stdlib.ponylang.io/src/cli/command/#L24) Returns a representational string for this command. ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### spec [[Source]](https://stdlib.ponylang.io/src/cli/command/#L39) Returns the spec for this command. ``` fun box spec() : CommandSpec box ``` #### Returns * [CommandSpec](cli-commandspec) box ### fullname [[Source]](https://stdlib.ponylang.io/src/cli/command/#L45) Returns the full name of this command, with its parents prefixed. ``` fun box fullname() : String val ``` #### Returns * [String](builtin-string) val ### option [[Source]](https://stdlib.ponylang.io/src/cli/command/#L51) Returns the Option by name, defaulting to a fake Option if unknown. ``` fun box option( name: String val) : Option val ``` #### Parameters * name: [String](builtin-string) val #### Returns * [Option](cli-option) val ### arg [[Source]](https://stdlib.ponylang.io/src/cli/command/#L57) Returns the Arg by name, defaulting to a fake Arg if unknown. ``` fun box arg( name: String val) : Arg val ``` #### Parameters * name: [String](builtin-string) val #### Returns * [Arg](cli-arg) val
programming_docs
pony RuntimeOptions RuntimeOptions ============== [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L1) Pony struct for the Pony runtime options C struct that can be used to override the Pony runtime defaults via code compiled into the program. The way this is done is by adding the following function to your `Main` actor: ``` fun @runtime_override_defaults(rto: RuntimeOptions) => ``` and then overriding the fields of `rto` (the `RuntimeOptions` instance) as needed. NOTE: Command line arguments still any values set via `@runtime_override_defaults`. The following example overrides the `--ponyhelp` argument to default it to `true` instead of `false` causing the compiled program to always display the Pony runtime help: ``` actor Main new create(env: Env) => env.out.print("Hello, world.") fun @runtime_override_defaults(rto: RuntimeOptions) => rto.ponyhelp = true ``` ``` struct ref RuntimeOptions ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L1) ``` new iso create() : RuntimeOptions iso^ ``` #### Returns * [RuntimeOptions](index) iso^ Public fields ------------- ### var ponymaxthreads: [U32](builtin-u32) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L37) Use N scheduler threads. Defaults to the number of cores (not hyperthreads) available. This can't be larger than the number of cores available. ### var ponyminthreads: [U32](builtin-u32) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L44) Minimum number of active scheduler threads allowed. Defaults to 0, meaning that all scheduler threads are allowed to be suspended when no work is available. This can't be larger than --ponymaxthreads if provided, or the physical cores available. ### var ponynoscale: [Bool](builtin-bool) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L53) Don't scale down the scheduler threads. See --ponymaxthreads on how to specify the number of threads explicitly. Can't be used with --ponyminthreads. ### var ponysuspendthreshold: [U32](builtin-u32) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L60) Amount of idle time before a scheduler thread suspends itself to minimize resource consumption (max 1000 ms, min 1 ms). Defaults to 1 ms. ### var ponycdinterval: [U32](builtin-u32) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L67) Run cycle detection every N ms (max 1000 ms, min 10 ms). Defaults to 100 ms. ### var ponygcinitial: [USize](builtin-usize) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L73) Defer garbage collection until an actor is using at least 2^N bytes. Defaults to 2^14. ### var ponygcfactor: [F64](builtin-f64) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L79) After GC, an actor will next be GC'd at a heap memory usage N times its current value. This is a floating point value. Defaults to 2.0. ### var ponynoyield: [Bool](builtin-bool) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L85) Do not yield the CPU when no work is available. ### var ponynoblock: [Bool](builtin-bool) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L90) Do not send block messages to the cycle detector. ### var ponypin: [Bool](builtin-bool) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L95) Pin scheduler threads to CPU cores. The ASIO thread can also be pinned if `--ponypinasio` is set. ### var ponypinasio: [Bool](builtin-bool) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L101) Pin the ASIO thread to a CPU the way scheduler threads are pinned to CPUs. Requires `--ponypin` to be set to have any effect. ### var ponyversion: [Bool](builtin-bool) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L107) Print the version of the compiler and exit. ### var ponyhelp: [Bool](builtin-bool) val [[Source]](https://stdlib.ponylang.io/src/builtin/runtime_options/#L112) Print the runtime usage options and exit. pony Readline Readline ======== [[Source]](https://stdlib.ponylang.io/src/term/readline/#L6) Line editing, history, and tab completion. ``` class ref Readline is ANSINotify ref ``` #### Implements * [ANSINotify](term-ansinotify) ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/term/readline/#L23) Create a readline handler to be passed to stdin. It begins blocked. Set an initial prompt on the ANSITerm to begin processing. ``` new iso create( notify: ReadlineNotify iso, out: OutStream tag, path: (FilePath val | None val) = reference, maxlen: USize val = 0) : Readline iso^ ``` #### Parameters * notify: [ReadlineNotify](term-readlinenotify) iso * out: [OutStream](builtin-outstream) tag * path: ([FilePath](files-filepath) val | [None](builtin-none) val) = reference * maxlen: [USize](builtin-usize) val = 0 #### Returns * [Readline](index) iso^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/term/readline/#L41) Receives input. ``` fun ref apply( term: ANSITerm ref, input: U8 val) : None val ``` #### Parameters * term: [ANSITerm](term-ansiterm) ref * input: [U8](builtin-u8) val #### Returns * [None](builtin-none) val ### prompt [[Source]](https://stdlib.ponylang.io/src/term/readline/#L83) Set a new prompt, unblock, and handle the pending queue. ``` fun ref prompt( term: ANSITerm ref, value: String val) : None val ``` #### Parameters * term: [ANSITerm](term-ansiterm) ref * value: [String](builtin-string) val #### Returns * [None](builtin-none) val ### closed [[Source]](https://stdlib.ponylang.io/src/term/readline/#L99) No more input is available. ``` fun ref closed() : None val ``` #### Returns * [None](builtin-none) val ### up [[Source]](https://stdlib.ponylang.io/src/term/readline/#L105) Previous line. ``` fun ref up( ctrl: Bool val = false, alt: Bool val = false, shift: Bool val = false) : None val ``` #### Parameters * ctrl: [Bool](builtin-bool) val = false * alt: [Bool](builtin-bool) val = false * shift: [Bool](builtin-bool) val = false #### Returns * [None](builtin-none) val ### down [[Source]](https://stdlib.ponylang.io/src/term/readline/#L117) Next line. ``` fun ref down( ctrl: Bool val = false, alt: Bool val = false, shift: Bool val = false) : None val ``` #### Parameters * ctrl: [Bool](builtin-bool) val = false * alt: [Bool](builtin-bool) val = false * shift: [Bool](builtin-bool) val = false #### Returns * [None](builtin-none) val ### left [[Source]](https://stdlib.ponylang.io/src/term/readline/#L133) Move left. ``` fun ref left( ctrl: Bool val = false, alt: Bool val = false, shift: Bool val = false) : None val ``` #### Parameters * ctrl: [Bool](builtin-bool) val = false * alt: [Bool](builtin-bool) val = false * shift: [Bool](builtin-bool) val = false #### Returns * [None](builtin-none) val ### right [[Source]](https://stdlib.ponylang.io/src/term/readline/#L152) Move right. ``` fun ref right( ctrl: Bool val = false, alt: Bool val = false, shift: Bool val = false) : None val ``` #### Parameters * ctrl: [Bool](builtin-bool) val = false * alt: [Bool](builtin-bool) val = false * shift: [Bool](builtin-bool) val = false #### Returns * [None](builtin-none) val ### home [[Source]](https://stdlib.ponylang.io/src/term/readline/#L171) Beginning of the line. ``` fun ref home( ctrl: Bool val = false, alt: Bool val = false, shift: Bool val = false) : None val ``` #### Parameters * ctrl: [Bool](builtin-bool) val = false * alt: [Bool](builtin-bool) val = false * shift: [Bool](builtin-bool) val = false #### Returns * [None](builtin-none) val ### end\_key [[Source]](https://stdlib.ponylang.io/src/term/readline/#L178) End of the line. ``` fun ref end_key( ctrl: Bool val = false, alt: Bool val = false, shift: Bool val = false) : None val ``` #### Parameters * ctrl: [Bool](builtin-bool) val = false * alt: [Bool](builtin-bool) val = false * shift: [Bool](builtin-bool) val = false #### Returns * [None](builtin-none) val ### delete [[Source]](https://stdlib.ponylang.io/src/term/readline/#L211) Forward delete. ``` fun ref delete( ctrl: Bool val = false, alt: Bool val = false, shift: Bool val = false) : None val ``` #### Parameters * ctrl: [Bool](builtin-bool) val = false * alt: [Bool](builtin-bool) val = false * shift: [Bool](builtin-bool) val = false #### Returns * [None](builtin-none) val ### insert ``` fun ref insert( ctrl: Bool val, alt: Bool val, shift: Bool val) : None val ``` #### Parameters * ctrl: [Bool](builtin-bool) val * alt: [Bool](builtin-bool) val * shift: [Bool](builtin-bool) val #### Returns * [None](builtin-none) val ### page\_up ``` fun ref page_up( ctrl: Bool val, alt: Bool val, shift: Bool val) : None val ``` #### Parameters * ctrl: [Bool](builtin-bool) val * alt: [Bool](builtin-bool) val * shift: [Bool](builtin-bool) val #### Returns * [None](builtin-none) val ### page\_down ``` fun ref page_down( ctrl: Bool val, alt: Bool val, shift: Bool val) : None val ``` #### Parameters * ctrl: [Bool](builtin-bool) val * alt: [Bool](builtin-bool) val * shift: [Bool](builtin-bool) val #### Returns * [None](builtin-none) val ### fn\_key ``` fun ref fn_key( i: U8 val, ctrl: Bool val, alt: Bool val, shift: Bool val) : None val ``` #### Parameters * i: [U8](builtin-u8) val * ctrl: [Bool](builtin-bool) val * alt: [Bool](builtin-bool) val * shift: [Bool](builtin-bool) val #### Returns * [None](builtin-none) val ### size ``` fun ref size( rows: U16 val, cols: U16 val) : None val ``` #### Parameters * rows: [U16](builtin-u16) val * cols: [U16](builtin-u16) val #### Returns * [None](builtin-none) val pony Set[A: (Hashable val & Equatable[A])] Set[A: ([Hashable](collections-hashable) val & [Equatable](builtin-equatable)[A])] ================================================================================== [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L3) ``` type Set[A: (Hashable val & Equatable[A])] is HashSet[A, HashEq[A] val] val ``` #### Type Alias For * [HashSet](collections-persistent-hashset)[A, [HashEq](collections-hasheq)[A] val] val pony SignalNotify SignalNotify ============ [[Source]](https://stdlib.ponylang.io/src/signals/signal_notify/#L1) Notifications for a signal. ``` interface ref SignalNotify ``` Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/signals/signal_notify/#L5) Called with the the number of times the signal has fired since this was last called. Return false to stop listening for the signal. ``` fun ref apply( count: U32 val) : Bool val ``` #### Parameters * count: [U32](builtin-u32) val #### Returns * [Bool](builtin-bool) val ### dispose [[Source]](https://stdlib.ponylang.io/src/signals/signal_notify/#L12) Called if the signal is disposed. This is also called if the notifier returns false. ``` fun ref dispose() : None val ``` #### Returns * [None](builtin-none) val pony Path Path ==== [[Source]](https://stdlib.ponylang.io/src/files/path/#L10) Operations on paths that do not require a capability. The operations can be used to manipulate path names, but give no access to the resulting paths. ``` primitive val Path ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/path/#L10) ``` new val create() : Path val^ ``` #### Returns * [Path](index) val^ Public Functions ---------------- ### is\_sep [[Source]](https://stdlib.ponylang.io/src/files/path/#L15) Determine if a byte is a path separator. ``` fun box is_sep( c: U8 val) : Bool val ``` #### Parameters * c: [U8](builtin-u8) val #### Returns * [Bool](builtin-bool) val ### sep [[Source]](https://stdlib.ponylang.io/src/files/path/#L25) Return the path separator as a string. ``` fun tag sep() : String val ``` #### Returns * [String](builtin-string) val ### is\_abs [[Source]](https://stdlib.ponylang.io/src/files/path/#L31) Return true if the path is an absolute path. ``` fun box is_abs( path: String val) : Bool val ``` #### Parameters * path: [String](builtin-string) val #### Returns * [Bool](builtin-bool) val ### join [[Source]](https://stdlib.ponylang.io/src/files/path/#L45) Join two paths together. If the next\_path is absolute, simply return it. The returned path will be cleaned. ``` fun box join( path: String val, next_path: String val) : String val ``` #### Parameters * path: [String](builtin-string) val * next\_path: [String](builtin-string) val #### Returns * [String](builtin-string) val ### clean [[Source]](https://stdlib.ponylang.io/src/files/path/#L69) Replace multiple separators with a single separator. Convert / to the OS separator. Remove instances of . from the path. Remove instances of .. and the preceding path element from the path. The result will have no trailing slash unless it is a root directory. If the result would be empty, "." will be returned instead. ``` fun box clean( path: String val) : String val ``` #### Parameters * path: [String](builtin-string) val #### Returns * [String](builtin-string) val ### normcase [[Source]](https://stdlib.ponylang.io/src/files/path/#L188) Normalizes the case of path for the runtime platform. ``` fun box normcase( path: String val) : String val ``` #### Parameters * path: [String](builtin-string) val #### Returns * [String](builtin-string) val ### cwd [[Source]](https://stdlib.ponylang.io/src/files/path/#L200) Returns the program's working directory. Setting the working directory is not supported, as it is not concurrency-safe. ``` fun box cwd() : String val ``` #### Returns * [String](builtin-string) val ### abs [[Source]](https://stdlib.ponylang.io/src/files/path/#L207) Returns a cleaned, absolute path. ``` fun box abs( path: String val) : String val ``` #### Parameters * path: [String](builtin-string) val #### Returns * [String](builtin-string) val ### rel [[Source]](https://stdlib.ponylang.io/src/files/path/#L217) Returns a path such that Path.join(to, Path.rel(to, target)) == target. Raises an error if this isn't possible. ``` fun box rel( to: String val, target: String val) : String val ? ``` #### Parameters * to: [String](builtin-string) val * target: [String](builtin-string) val #### Returns * [String](builtin-string) val ? ### split [[Source]](https://stdlib.ponylang.io/src/files/path/#L307) Splits the path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. The path in head will be cleaned before it is returned. In all cases, join(head, tail) returns a path to the same location as path (but the strings may differ). Also see the functions dir() and base(). ``` fun box split( path: String val, separator: String val = call) : (String val , String val) ``` #### Parameters * path: [String](builtin-string) val * separator: [String](builtin-string) val = call #### Returns * ([String](builtin-string) val , [String](builtin-string) val) ### base [[Source]](https://stdlib.ponylang.io/src/files/path/#L324) Return the path after the last separator, or the whole path if there is no separator. If `with_ext` is `false`, the extension as defined by the `ext()` method will be omitted from the result. ``` fun box base( path: String val, with_ext: Bool val = true) : String val ``` #### Parameters * path: [String](builtin-string) val * with\_ext: [Bool](builtin-bool) val = true #### Returns * [String](builtin-string) val ### dir [[Source]](https://stdlib.ponylang.io/src/files/path/#L349) Return a cleaned path before the last separator, or the whole path if there is no separator. ``` fun box dir( path: String val) : String val ``` #### Parameters * path: [String](builtin-string) val #### Returns * [String](builtin-string) val ### ext [[Source]](https://stdlib.ponylang.io/src/files/path/#L360) Return the file extension, i.e. the part after the last dot as long as that dot is after all separators. Return an empty string for no extension. ``` fun box ext( path: String val) : String val ``` #### Parameters * path: [String](builtin-string) val #### Returns * [String](builtin-string) val ### volume [[Source]](https://stdlib.ponylang.io/src/files/path/#L380) On Windows, this returns the drive letter or UNC base at the beginning of the path, if there is one. Otherwise, this returns an empty string. ``` fun box volume( path: String val) : String val ``` #### Parameters * path: [String](builtin-string) val #### Returns * [String](builtin-string) val ### from\_slash [[Source]](https://stdlib.ponylang.io/src/files/path/#L441) Changes each / in the path to the OS specific separator. ``` fun box from_slash( path: String val) : String val ``` #### Parameters * path: [String](builtin-string) val #### Returns * [String](builtin-string) val ### to\_slash [[Source]](https://stdlib.ponylang.io/src/files/path/#L465) Changes each OS specific separator in the path to /. ``` fun box to_slash( path: String val) : String val ``` #### Parameters * path: [String](builtin-string) val #### Returns * [String](builtin-string) val ### canonical [[Source]](https://stdlib.ponylang.io/src/files/path/#L489) Return the equivalent canonical absolute path. Raise an error if there isn't one. ``` fun box canonical( path: String val) : String val ? ``` #### Parameters * path: [String](builtin-string) val #### Returns * [String](builtin-string) val ? ### is\_list\_sep [[Source]](https://stdlib.ponylang.io/src/files/path/#L503) Determine if a byte is a path list separator. ``` fun box is_list_sep( c: U8 val) : Bool val ``` #### Parameters * c: [U8](builtin-u8) val #### Returns * [Bool](builtin-bool) val ### list\_sep [[Source]](https://stdlib.ponylang.io/src/files/path/#L509) Return the path list separator as a string. ``` fun box list_sep() : String val ``` #### Returns * [String](builtin-string) val ### split\_list [[Source]](https://stdlib.ponylang.io/src/files/path/#L515) Separate a list of paths into an array of cleaned paths. ``` fun box split_list( path: String val) : Array[String val] iso^ ``` #### Parameters * path: [String](builtin-string) val #### Returns * [Array](builtin-array)[[String](builtin-string) val] iso^ ### random [[Source]](https://stdlib.ponylang.io/src/files/path/#L534) Returns a pseudo-random base, suitable as a temporary file name or directory name, but not guaranteed to not already exist. ``` fun box random( len: USize val = 6) : String val ``` #### Parameters * len: [USize](builtin-usize) val = 6 #### Returns * [String](builtin-string) val ### eq [[Source]](https://stdlib.ponylang.io/src/files/path/#L15) ``` fun box eq( that: Path val) : Bool val ``` #### Parameters * that: [Path](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/path/#L15) ``` fun box ne( that: Path val) : Bool val ``` #### Parameters * that: [Path](index) val #### Returns * [Bool](builtin-bool) val pony FileError FileError ========= [[Source]](https://stdlib.ponylang.io/src/files/file/#L25) ``` primitive val FileError ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file/#L25) ``` new val create() : FileError val^ ``` #### Returns * [FileError](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/files/file/#L26) ``` fun box eq( that: FileError val) : Bool val ``` #### Parameters * that: [FileError](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/file/#L26) ``` fun box ne( that: FileError val) : Bool val ``` #### Parameters * that: [FileError](index) val #### Returns * [Bool](builtin-bool) val
programming_docs
pony Greater Greater ======= [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L9) ``` primitive val Greater is Equatable[(Less val | Equal val | Greater val)] ref ``` #### Implements * [Equatable](builtin-equatable)[([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](index) val)] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L9) ``` new val create() : Greater val^ ``` #### Returns * [Greater](index) val^ Public Functions ---------------- ### string [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L10) ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### eq [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L19) ``` fun box eq( that: (Less val | Equal val | Greater val)) : Bool val ``` #### Parameters * that: ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](index) val) #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L20) ``` fun box ne( that: (Less val | Equal val | Greater val)) : Bool val ``` #### Parameters * that: ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](index) val) #### Returns * [Bool](builtin-bool) val pony AlignCenter AlignCenter =========== [[Source]](https://stdlib.ponylang.io/src/format/align/#L3) ``` primitive val AlignCenter ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/format/align/#L3) ``` new val create() : AlignCenter val^ ``` #### Returns * [AlignCenter](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/format/align/#L5) ``` fun box eq( that: AlignCenter val) : Bool val ``` #### Parameters * that: [AlignCenter](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/format/align/#L5) ``` fun box ne( that: AlignCenter val) : Bool val ``` #### Parameters * that: [AlignCenter](index) val #### Returns * [Bool](builtin-bool) val pony I64Argument I64Argument =========== [[Source]](https://stdlib.ponylang.io/src/options/options/#L70) ``` primitive val I64Argument ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/options/options/#L70) ``` new val create() : I64Argument val^ ``` #### Returns * [I64Argument](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/options/options/#L71) ``` fun box eq( that: I64Argument val) : Bool val ``` #### Parameters * that: [I64Argument](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/options/options/#L71) ``` fun box ne( that: I64Argument val) : Bool val ``` #### Parameters * that: [I64Argument](index) val #### Returns * [Bool](builtin-bool) val pony Equatable[A: Equatable[A] #read] Equatable[A: [Equatable](index)[A] #read] ========================================= [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L18) ``` interface ref Equatable[A: Equatable[A] #read] ``` Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L19) ``` fun box eq( that: box->A) : Bool val ``` #### Parameters * that: box->A #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L20) ``` fun box ne( that: box->A) : Bool val ``` #### Parameters * that: box->A #### Returns * [Bool](builtin-bool) val pony FileExec FileExec ======== [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L48) ``` primitive val FileExec ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L48) ``` new val create() : FileExec val^ ``` #### Returns * [FileExec](index) val^ Public Functions ---------------- ### value [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L49) ``` fun box value() : U32 val ``` #### Returns * [U32](builtin-u32) val ### eq [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L49) ``` fun box eq( that: FileExec val) : Bool val ``` #### Parameters * that: [FileExec](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L49) ``` fun box ne( that: FileExec val) : Bool val ``` #### Parameters * that: [FileExec](index) val #### Returns * [Bool](builtin-bool) val pony String String ====== [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L9) A String is an ordered collection of bytes. Strings don't specify an encoding. Example usage of some common String methods: ``` actor Main new create(env: Env) => try // construct a new string let str = "Hello" // make an uppercased version let str_upper = str.upper() // make a reversed version let str_reversed = str.reverse() // add " world" to the end of our original string let str_new = str.add(" world") // count occurrences of letter "l" let count = str_new.count("l") // find first occurrence of letter "w" let first_w = str_new.find("w") // find first occurrence of letter "d" let first_d = str_new.find("d") // get substring capturing "world" let substr = str_new.substring(first_w, first_d+1) // clone substring let substr_clone = substr.clone() // print our substr env.out.print(consume substr) end ``` ``` class val String is Seq[U8 val] ref, Comparable[String box] ref, Stringable box ``` #### Implements * [Seq](builtin-seq)[[U8](builtin-u8) val] ref * [Comparable](builtin-comparable)[[String](index) box] ref * [Stringable](builtin-stringable) box Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L54) An empty string. Enough space for len bytes is reserved. ``` new ref create( len: USize val = 0) : String ref^ ``` #### Parameters * len: [USize](builtin-usize) val = 0 #### Returns * [String](index) ref^ ### from\_array [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L63) Create a string from an array, reusing the underlying data pointer. ``` new val from_array( data: Array[U8 val] val) : String val^ ``` #### Parameters * data: [Array](builtin-array)[[U8](builtin-u8) val] val #### Returns * [String](index) val^ ### from\_iso\_array [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L71) Create a string from an array, reusing the underlying data pointer ``` new iso from_iso_array( data: Array[U8 val] iso) : String iso^ ``` #### Parameters * data: [Array](builtin-array)[[U8](builtin-u8) val] iso #### Returns * [String](index) iso^ ### from\_cpointer [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L82) Return a string from binary pointer data without making a copy. This must be done only with C-FFI functions that return pony\_alloc'd character arrays. If a null pointer is given then an empty string is returned. ``` new ref from_cpointer( str: Pointer[U8 val] ref, len: USize val, alloc: USize val = 0) : String ref^ ``` #### Parameters * str: [Pointer](builtin-pointer)[[U8](builtin-u8) val] ref * len: [USize](builtin-usize) val * alloc: [USize](builtin-usize) val = 0 #### Returns * [String](index) ref^ ### from\_cstring [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L100) Return a string from a pointer to a null-terminated cstring without making a copy. The data is not copied. This must be done only with C-FFI functions that return pony\_alloc'd character arrays. The pointer is scanned for the first null byte, which will be interpreted as the null terminator. Note that the scan is unbounded; the pointed to data must be null-terminated within the allocated array to preserve memory safety. If a null pointer is given then an empty string is returned. ``` new ref from_cstring( str: Pointer[U8 val] ref) : String ref^ ``` #### Parameters * str: [Pointer](builtin-pointer)[[U8](builtin-u8) val] ref #### Returns * [String](index) ref^ ### copy\_cpointer [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L128) Create a string by copying a fixed number of bytes from a pointer. ``` new ref copy_cpointer( str: Pointer[U8 val] box, len: USize val) : String ref^ ``` #### Parameters * str: [Pointer](builtin-pointer)[[U8](builtin-u8) val] box * len: [USize](builtin-usize) val #### Returns * [String](index) ref^ ### copy\_cstring [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L144) Create a string by copying a null-terminated C string. Note that the scan is unbounded; the pointed to data must be null-terminated within the allocated array to preserve memory safety. If a null pointer is given then an empty string is returned. ``` new ref copy_cstring( str: Pointer[U8 val] box) : String ref^ ``` #### Parameters * str: [Pointer](builtin-pointer)[[U8](builtin-u8) val] box #### Returns * [String](index) ref^ ### from\_utf32 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L169) Create a UTF-8 string from a single UTF-32 code point. ``` new ref from_utf32( value: U32 val) : String ref^ ``` #### Parameters * value: [U32](builtin-u32) val #### Returns * [String](index) ref^ Public Functions ---------------- ### push\_utf32 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L189) Push a UTF-32 code point. ``` fun ref push_utf32( value: U32 val) : None val ``` #### Parameters * value: [U32](builtin-u32) val #### Returns * [None](builtin-none) val ### cpointer [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L216) Returns a C compatible pointer to the underlying string allocation. ``` fun box cpointer( offset: USize val = 0) : Pointer[U8 val] tag ``` #### Parameters * offset: [USize](builtin-usize) val = 0 #### Returns * [Pointer](builtin-pointer)[[U8](builtin-u8) val] tag ### cstring [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L222) Returns a C compatible pointer to a null-terminated version of the string, safe to pass to an FFI function that doesn't accept a size argument, expecting a null-terminator. If the underlying string is already null terminated, this is returned; otherwise the string is copied into a new, null-terminated allocation. ``` fun box cstring() : Pointer[U8 val] tag ``` #### Returns * [Pointer](builtin-pointer)[[U8](builtin-u8) val] tag ### array [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L239) Returns an Array[U8] that reuses the underlying data pointer. ``` fun val array() : Array[U8 val] val ``` #### Returns * [Array](builtin-array)[[U8](builtin-u8) val] val ### iso\_array [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L247) Returns an Array[U8] iso that reuses the underlying data pointer. ``` fun iso iso_array() : Array[U8 val] iso^ ``` #### Returns * [Array](builtin-array)[[U8](builtin-u8) val] iso^ ### size [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L255) Returns the length of the string data in bytes. ``` fun box size() : USize val ``` #### Returns * [USize](builtin-usize) val ### codepoints [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L261) Returns the number of unicode code points in the string between the two offsets. Index range [`from` .. `to`) is half-open. ``` fun box codepoints( from: ISize val = 0, to: ISize val = call) : USize val ``` #### Parameters * from: [ISize](builtin-isize) val = 0 * to: [ISize](builtin-isize) val = call #### Returns * [USize](builtin-usize) val ### space [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L284) Returns the space available for data, not including the null terminator. ``` fun box space() : USize val ``` #### Returns * [USize](builtin-usize) val ### reserve [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L290) Reserve space for len bytes. An additional byte will be reserved for the null terminator. ``` fun ref reserve( len: USize val) : None val ``` #### Parameters * len: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### compact [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L306) Try to remove unused space, making it available for garbage collection. The request may be ignored. The string is returned to allow call chaining. ``` fun ref compact() : None val ``` #### Returns * [None](builtin-none) val ### recalc [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L325) Recalculates the string length. This is only needed if the string is changed via an FFI call. If a null terminator byte is not found within the allocated length, the size will not be changed. ``` fun ref recalc() : None val ``` #### Returns * [None](builtin-none) val ### truncate [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L341) Truncates the string at the minimum of len and space. Ensures there is a null terminator. Does not check for null terminators inside the string. Note that memory is not freed by this operation. ``` fun ref truncate( len: USize val) : None val ``` #### Parameters * len: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### trim\_in\_place [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L357) Trim the string to a portion of itself, covering `from` until `to`. Unlike slice, the operation does not allocate a new string nor copy elements. ``` fun ref trim_in_place( from: USize val = 0, to: USize val = call) : None val ``` #### Parameters * from: [USize](builtin-usize) val = 0 * to: [USize](builtin-usize) val = call #### Returns * [None](builtin-none) val ### trim [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L385) Return a shared portion of this string, covering `from` until `to`. Both the original and the new string are immutable, as they share memory. The operation does not allocate a new string pointer nor copy elements. ``` fun val trim( from: USize val = 0, to: USize val = call) : String val ``` #### Parameters * from: [USize](builtin-usize) val = 0 * to: [USize](builtin-usize) val = call #### Returns * [String](index) val ### chop [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L409) Chops the string in half at the split point requested and returns both the left and right portions. The original string is trimmed in place and returned as the left portion. If the split point is larger than the string, the left portion is the original string and the right portion is a new empty string. Both strings are isolated and mutable, as they do not share memory. The operation does not allocate a new string pointer nor copy elements. ``` fun iso chop( split_point: USize val) : (String iso^ , String iso^) ``` #### Parameters * split\_point: [USize](builtin-usize) val #### Returns * ([String](index) iso^ , [String](index) iso^) ### unchop [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L435) Unchops two iso strings to return the original string they were chopped from. Both input strings are isolated and mutable and were originally chopped from a single string. This function checks that they are indeed two strings chopped from the same original string and can be unchopped before doing the unchopping and returning the unchopped string. If the two strings cannot be unchopped it returns both strings without modifying them. The operation does not allocate a new string pointer nor copy elements. ``` fun iso unchop( b: String iso) : ((String iso^ , String iso^) | String iso^) ``` #### Parameters * b: [String](index) iso #### Returns * (([String](index) iso^ , [String](index) iso^) | [String](index) iso^) ### is\_null\_terminated [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L477) Return true if the string is null-terminated and safe to pass to an FFI function that doesn't accept a size argument, expecting a null-terminator. This method checks that there is a null byte just after the final position of populated bytes in the string, but does not check for other null bytes which may be present earlier in the content of the string. If you need a null-terminated copy of this string, use the clone method. ``` fun box is_null_terminated() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### utf32 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L488) Return a UTF32 representation of the character at the given offset and the number of bytes needed to encode that character. If the offset does not point to the beginning of a valid UTF8 encoding, return 0xFFFD (the unicode replacement character) and a length of one. Raise an error if the offset is out of bounds. ``` fun box utf32( offset: ISize val) : (U32 val , U8 val) ? ``` #### Parameters * offset: [ISize](builtin-isize) val #### Returns * ([U32](builtin-u32) val , [U8](builtin-u8) val) ? ### apply [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L574) Returns the i-th byte. Raise an error if the index is out of bounds. ``` fun box apply( i: USize val) : U8 val ? ``` #### Parameters * i: [USize](builtin-usize) val #### Returns * [U8](builtin-u8) val ? ### update [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L580) Change the i-th byte. Raise an error if the index is out of bounds. ``` fun ref update( i: USize val, value: U8 val) : U8 val ? ``` #### Parameters * i: [USize](builtin-usize) val * value: [U8](builtin-u8) val #### Returns * [U8](builtin-u8) val ? ### at\_offset [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L590) Returns the byte at the given offset. Raise an error if the offset is out of bounds. ``` fun box at_offset( offset: ISize val) : U8 val ? ``` #### Parameters * offset: [ISize](builtin-isize) val #### Returns * [U8](builtin-u8) val ? ### update\_offset [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L597) Changes a byte in the string, returning the previous byte at that offset. Raise an error if the offset is out of bounds. ``` fun ref update_offset( offset: ISize val, value: U8 val) : U8 val ? ``` #### Parameters * offset: [ISize](builtin-isize) val * value: [U8](builtin-u8) val #### Returns * [U8](builtin-u8) val ? ### clone [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L604) Returns a copy of the string. The resulting string is null-terminated even if the original is not. ``` fun box clone() : String iso^ ``` #### Returns * [String](index) iso^ ### repeat\_str [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L616) Returns a copy of the string repeated `num` times with an optional separator added inbetween repeats. ``` fun box repeat_str( num: USize val = 1, sep: String val = "") : String iso^ ``` #### Parameters * num: [USize](builtin-usize) val = 1 * sep: [String](index) val = "" #### Returns * [String](index) iso^ ### mul [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L634) Returns a copy of the string repeated `num` times. ``` fun box mul( num: USize val) : String iso^ ``` #### Parameters * num: [USize](builtin-usize) val #### Returns * [String](index) iso^ ### find [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L640) Return the index of the n-th instance of s in the string starting from the beginning. Raise an error if there is no n-th occurrence of s or s is empty. ``` fun box find( s: String box, offset: ISize val = 0, nth: USize val = 0) : ISize val ? ``` #### Parameters * s: [String](index) box * offset: [ISize](builtin-isize) val = 0 * nth: [USize](builtin-usize) val = 0 #### Returns * [ISize](builtin-isize) val ? ### rfind [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L669) Return the index of n-th instance of `s` in the string starting from the end. The `offset` represents the highest index to included in the search. Raise an error if there is no n-th occurrence of `s` or `s` is empty. ``` fun box rfind( s: String box, offset: ISize val = call, nth: USize val = 0) : ISize val ? ``` #### Parameters * s: [String](index) box * offset: [ISize](builtin-isize) val = call * nth: [USize](builtin-usize) val = 0 #### Returns * [ISize](builtin-isize) val ? ### contains [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L700) Returns true if contains s as a substring, false otherwise. ``` fun box contains( s: String box, offset: ISize val = 0, nth: USize val = 0) : Bool val ``` #### Parameters * s: [String](index) box * offset: [ISize](builtin-isize) val = 0 * nth: [USize](builtin-usize) val = 0 #### Returns * [Bool](builtin-bool) val ### count [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L728) Counts the non-overlapping occurrences of s in the string. ``` fun box count( s: String box, offset: ISize val = 0) : USize val ``` #### Parameters * s: [String](index) box * offset: [ISize](builtin-isize) val = 0 #### Returns * [USize](builtin-usize) val ### at [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L751) Returns true if the substring s is present at the given offset. ``` fun box at( s: String box, offset: ISize val = 0) : Bool val ``` #### Parameters * s: [String](index) box * offset: [ISize](builtin-isize) val = 0 #### Returns * [Bool](builtin-bool) val ### delete [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L763) Delete len bytes at the supplied offset, compacting the string in place. ``` fun ref delete( offset: ISize val, len: USize val = 1) : None val ``` #### Parameters * offset: [ISize](builtin-isize) val * len: [USize](builtin-usize) val = 1 #### Returns * [None](builtin-none) val ### substring [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L776) Returns a substring. Index range [`from` .. `to`) is half-open. Returns an empty string if nothing is in the range. Note that this operation allocates a new string to be returned. For similar operations that don't allocate a new string, see `trim` and `trim_in_place`. ``` fun box substring( from: ISize val, to: ISize val = call) : String iso^ ``` #### Parameters * from: [ISize](builtin-isize) val * to: [ISize](builtin-isize) val = call #### Returns * [String](index) iso^ ### lower [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L799) Returns a lower case version of the string. ``` fun box lower() : String iso^ ``` #### Returns * [String](index) iso^ ### lower\_in\_place [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L807) Transforms the string to lower case. Currently only knows ASCII case. ``` fun ref lower_in_place() : None val ``` #### Returns * [None](builtin-none) val ### upper [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L823) Returns an upper case version of the string. Currently only knows ASCII case. ``` fun box upper() : String iso^ ``` #### Returns * [String](index) iso^ ### upper\_in\_place [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L832) Transforms the string to upper case. ``` fun ref upper_in_place() : None val ``` #### Returns * [None](builtin-none) val ### reverse [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L848) Returns a reversed version of the string. ``` fun box reverse() : String iso^ ``` #### Returns * [String](index) iso^ ### reverse\_in\_place [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L856) Reverses the byte order in the string. This needs to be changed to handle UTF-8 correctly. ``` fun ref reverse_in_place() : None val ``` #### Returns * [None](builtin-none) val ### push [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L874) Add a byte to the end of the string. ``` fun ref push( value: U8 val) : None val ``` #### Parameters * value: [U8](builtin-u8) val #### Returns * [None](builtin-none) val ### pop [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L883) Remove a byte from the end of the string. ``` fun ref pop() : U8 val ? ``` #### Returns * [U8](builtin-u8) val ? ### unshift [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L894) Adds a byte to the beginning of the string. ``` fun ref unshift( value: U8 val) : None val ``` #### Parameters * value: [U8](builtin-u8) val #### Returns * [None](builtin-none) val ### shift [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L908) Removes a byte from the beginning of the string. ``` fun ref shift() : U8 val ? ``` #### Returns * [U8](builtin-u8) val ? ### append [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L921) Append the elements from a sequence, starting from the given offset. ``` fun ref append( seq: ReadSeq[U8 val] box, offset: USize val = 0, len: USize val = call) : None val ``` #### Parameters * seq: [ReadSeq](builtin-readseq)[[U8](builtin-u8) val] box * offset: [USize](builtin-usize) val = 0 * len: [USize](builtin-usize) val = call #### Returns * [None](builtin-none) val ### concat [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L949) Add len iterated bytes to the end of the string, starting from the given offset. ``` fun ref concat( iter: Iterator[U8 val] ref, offset: USize val = 0, len: USize val = call) : None val ``` #### Parameters * iter: [Iterator](builtin-iterator)[[U8](builtin-u8) val] ref * offset: [USize](builtin-usize) val = 0 * len: [USize](builtin-usize) val = call #### Returns * [None](builtin-none) val ### clear [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L980) Truncate the string to zero length. ``` fun ref clear() : None val ``` #### Returns * [None](builtin-none) val ### insert [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L987) Returns a version of the string with the given string inserted at the given offset. ``` fun box insert( offset: ISize val, that: String val) : String iso^ ``` #### Parameters * offset: [ISize](builtin-isize) val * that: [String](index) val #### Returns * [String](index) iso^ ### insert\_in\_place [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L996) Inserts the given string at the given offset. Appends the string if the offset is out of bounds. ``` fun ref insert_in_place( offset: ISize val, that: String box) : None val ``` #### Parameters * offset: [ISize](builtin-isize) val * that: [String](index) box #### Returns * [None](builtin-none) val ### insert\_byte [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1009) Inserts a byte at the given offset. Appends if the offset is out of bounds. ``` fun ref insert_byte( offset: ISize val, value: U8 val) : None val ``` #### Parameters * offset: [ISize](builtin-isize) val * value: [U8](builtin-u8) val #### Returns * [None](builtin-none) val ### cut [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1021) Returns a version of the string with the given range deleted. Index range [`from` .. `to`) is half-open. ``` fun box cut( from: ISize val, to: ISize val = call) : String iso^ ``` #### Parameters * from: [ISize](builtin-isize) val * to: [ISize](builtin-isize) val = call #### Returns * [String](index) iso^ ### cut\_in\_place [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1030) Cuts the given range out of the string. Index range [`from` .. `to`) is half-open. ``` fun ref cut_in_place( from: ISize val, to: ISize val = call) : None val ``` #### Parameters * from: [ISize](builtin-isize) val * to: [ISize](builtin-isize) val = call #### Returns * [None](builtin-none) val ### remove [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1052) Remove all instances of s from the string. Returns the count of removed instances. ``` fun ref remove( s: String box) : USize val ``` #### Parameters * s: [String](index) box #### Returns * [USize](builtin-usize) val ### replace [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1069) Replace up to n occurrences of `from` in `this` with `to`. If n is 0, all occurrences will be replaced. Returns the count of replaced occurrences. ``` fun ref replace( from: String box, to: String box, n: USize val = 0) : USize val ``` #### Parameters * from: [String](index) box * to: [String](index) box * n: [USize](builtin-usize) val = 0 #### Returns * [USize](builtin-usize) val ### split\_by [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1094) Split the string into an array of strings that are delimited by `delim` in the original string. If `n > 0`, then the split count is limited to n. Example: ``` let original: String = "<b><span>Hello!</span></b>" let delimiter: String = "><" let split_array: Array[String] = original.split_by(delimiter) env.out.print("OUTPUT:") for value in split_array.values() do env.out.print(value) end // OUTPUT: // <b // span>Hello!</span // b> ``` Adjacent delimiters result in a zero length entry in the array. For example, `"1CutCut2".split_by("Cut") => ["1", "", "2"]`. An empty delimiter results in an array that contains a single element equal to the whole string. If you want to split the string with each individual character of `delim`, use [`split`](#split). ``` fun box split_by( delim: String val, n: USize val = call) : Array[String val] iso^ ``` #### Parameters * delim: [String](index) val * n: [USize](builtin-usize) val = call #### Returns * [Array](builtin-array)[[String](index) val] iso^ ### split [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1145) Split the string into an array of strings with any character in the delimiter string. By default, the string is split with whitespace characters. If `n > 0`, then the split count is limited to n. Example: ``` let original: String = "name,job;department" let delimiter: String = ".,;" let split_array: Array[String] = original.split(delimiter) env.out.print("OUTPUT:") for value in split_array.values() do env.out.print(value) end // OUTPUT: // name // job // department ``` Adjacent delimiters result in a zero length entry in the array. For example, `"1,,2".split(",") => ["1", "", "2"]`. If you want to split the string with the entire delimiter string `delim`, use [`split_by`](#split_by). ``` fun box split( delim: String val = " ", n: USize val = 0) : Array[String val] iso^ ``` #### Parameters * delim: [String](index) val = " " * n: [USize](builtin-usize) val = 0 #### Returns * [Array](builtin-array)[[String](index) val] iso^ ### strip [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1225) Remove all leading and trailing characters from the string that are in s. ``` fun ref strip( s: String box = " ") : None val ``` #### Parameters * s: [String](index) box = " " #### Returns * [None](builtin-none) val ### rstrip [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1231) Remove all trailing characters within the string that are in s. By default, trailing whitespace is removed. ``` fun ref rstrip( s: String box = " ") : None val ``` #### Parameters * s: [String](index) box = " " #### Returns * [None](builtin-none) val ### lstrip [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1263) Remove all leading characters within the string that are in s. By default, leading whitespace is removed. ``` fun ref lstrip( s: String box = " ") : None val ``` #### Parameters * s: [String](index) box = " " #### Returns * [None](builtin-none) val ### add [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1304) Return a string that is a concatenation of this and that. ``` fun box add( that: String box) : String val ``` #### Parameters * that: [String](index) box #### Returns * [String](index) val ### join [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1312) Return a string that is a concatenation of the strings in data, using this as a separator. ``` fun box join( data: Iterator[Stringable box] ref) : String iso^ ``` #### Parameters * data: [Iterator](builtin-iterator)[[Stringable](builtin-stringable) box] ref #### Returns * [String](index) iso^ ### compare [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1329) Lexically compare two strings. ``` fun box compare( that: String box) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [String](index) box #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val) ### compare\_sub [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1335) Lexically compare at most `n` bytes of the substring of `this` starting at `offset` with the substring of `that` starting at `that_offset`. The comparison is case sensitive unless `ignore_case` is `true`. If the substring of `this` is a proper prefix of the substring of `that`, then `this` is `Less` than `that`. Likewise, if `that` is a proper prefix of `this`, then `this` is `Greater` than `that`. Both `offset` and `that_offset` can be negative, in which case the offsets are computed from the end of the string. If `n + offset` is greater than the length of `this`, or `n + that_offset` is greater than the length of `that`, then the number of positions compared will be reduced to the length of the longest substring. Needs to be made UTF-8 safe. ``` fun box compare_sub( that: String box, n: USize val, offset: ISize val = 0, that_offset: ISize val = 0, ignore_case: Bool val = false) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [String](index) box * n: [USize](builtin-usize) val * offset: [ISize](builtin-isize) val = 0 * that\_offset: [ISize](builtin-isize) val = 0 * ignore\_case: [Bool](builtin-bool) val = false #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val) ### eq [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1392) Returns true if the two strings have the same contents. ``` fun box eq( that: String box) : Bool val ``` #### Parameters * that: [String](index) box #### Returns * [Bool](builtin-bool) val ### lt [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1402) Returns true if this is lexically less than that. Needs to be made UTF-8 safe. ``` fun box lt( that: String box) : Bool val ``` #### Parameters * that: [String](index) box #### Returns * [Bool](builtin-bool) val ### le [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1420) Returns true if this is lexically less than or equal to that. Needs to be made UTF-8 safe. ``` fun box le( that: String box) : Bool val ``` #### Parameters * that: [String](index) box #### Returns * [Bool](builtin-bool) val ### offset\_to\_index [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1438) ``` fun box offset_to_index( i: ISize val) : USize val ``` #### Parameters * i: [ISize](builtin-isize) val #### Returns * [USize](builtin-usize) val ### bool [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1441) ``` fun box bool() : Bool val ? ``` #### Returns * [Bool](builtin-bool) val ? ### i8 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1449) ``` fun box i8( base: U8 val = 0) : I8 val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [I8](builtin-i8) val ? ### i16 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1450) ``` fun box i16( base: U8 val = 0) : I16 val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [I16](builtin-i16) val ? ### i32 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1451) ``` fun box i32( base: U8 val = 0) : I32 val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [I32](builtin-i32) val ? ### i64 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1452) ``` fun box i64( base: U8 val = 0) : I64 val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [I64](builtin-i64) val ? ### i128 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1453) ``` fun box i128( base: U8 val = 0) : I128 val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [I128](builtin-i128) val ? ### ilong [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1454) ``` fun box ilong( base: U8 val = 0) : ILong val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [ILong](builtin-ilong) val ? ### isize [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1455) ``` fun box isize( base: U8 val = 0) : ISize val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [ISize](builtin-isize) val ? ### u8 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1456) ``` fun box u8( base: U8 val = 0) : U8 val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [U8](builtin-u8) val ? ### u16 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1457) ``` fun box u16( base: U8 val = 0) : U16 val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [U16](builtin-u16) val ? ### u32 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1458) ``` fun box u32( base: U8 val = 0) : U32 val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [U32](builtin-u32) val ? ### u64 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1459) ``` fun box u64( base: U8 val = 0) : U64 val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [U64](builtin-u64) val ? ### u128 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1460) ``` fun box u128( base: U8 val = 0) : U128 val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [U128](builtin-u128) val ? ### ulong [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1461) ``` fun box ulong( base: U8 val = 0) : ULong val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [ULong](builtin-ulong) val ? ### usize [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1462) ``` fun box usize( base: U8 val = 0) : USize val ? ``` #### Parameters * base: [U8](builtin-u8) val = 0 #### Returns * [USize](builtin-usize) val ? ### read\_int[A: (([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](builtin-i32) val | [I64](builtin-i64) val | [I128](builtin-i128) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val | [U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Integer](builtin-integer)[A] val)] [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1475) Read an integer from the specified location in this string. The integer value read and the number of bytes consumed are reported. The base parameter specifies the base to use, 0 indicates using the prefix, if any, to detect base 2, 10 or 16. If no integer is found at the specified location, then (0, 0) is returned, since no characters have been used. An integer out of range for the target type throws an error. A leading minus is allowed for signed integer types. Underscore characters are allowed throughout the integer and are ignored. ``` fun box read_int[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Integer[A] val)]( offset: ISize val = 0, base: U8 val = 0) : (A , USize val) ? ``` #### Parameters * offset: [ISize](builtin-isize) val = 0 * base: [U8](builtin-u8) val = 0 #### Returns * (A , [USize](builtin-usize) val) ? ### f32 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1590) Convert this string starting at the given offset to a 32-bit floating point number ([F32](builtin-f32)). This method errors if this string cannot be parsed to a float, if the result would over- or underflow, the offset exceeds the size of this string or there are leftover characters in the string after conversion. Examples: ``` "1.5".f32()? == F32(1.5) "1.19208e-07".f32()? == F32(1.19208e-07) "NaN".f32()?.nan() == true ``` ``` fun box f32( offset: ISize val = 0) : F32 val ? ``` #### Parameters * offset: [ISize](builtin-isize) val = 0 #### Returns * [F32](builtin-f32) val ? ### f64 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1623) Convert this string starting at the given offset to a 64-bit floating point number ([F64](builtin-f64)). This method errors if this string cannot be parsed to a float, if the result would over- or underflow, the offset exceeds the size of this string or there are leftover characters in the string after conversion. Examples: ``` "1.5".f64()? == F64(1.5) "1.19208e-07".f64()? == F64(1.19208e-07) "Inf".f64()?.infinite() == true ``` ``` fun box f64( offset: ISize val = 0) : F64 val ? ``` #### Parameters * offset: [ISize](builtin-isize) val = 0 #### Returns * [F64](builtin-f64) val ? ### hash [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1656) ``` fun box hash() : USize val ``` #### Returns * [USize](builtin-usize) val ### hash64 [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1659) ``` fun box hash64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### string [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1662) ``` fun box string() : String iso^ ``` #### Returns * [String](index) iso^ ### values [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1665) Return an iterator over the bytes in the string. ``` fun box values() : StringBytes ref^ ``` #### Returns * [StringBytes](builtin-stringbytes) ref^ ### runes [[Source]](https://stdlib.ponylang.io/src/builtin/string/#L1671) Return an iterator over the codepoints in the string. ``` fun box runes() : StringRunes ref^ ``` #### Returns * [StringRunes](builtin-stringrunes) ref^ ### ge ``` fun box ge( that: String box) : Bool val ``` #### Parameters * that: [String](index) box #### Returns * [Bool](builtin-bool) val ### gt ``` fun box gt( that: String box) : Bool val ``` #### Parameters * that: [String](index) box #### Returns * [Bool](builtin-bool) val ### ne ``` fun box ne( that: String box) : Bool val ``` #### Parameters * that: [String](index) box #### Returns * [Bool](builtin-bool) val
programming_docs
pony Proxy Proxy ===== [[Source]](https://stdlib.ponylang.io/src/net/proxy/#L2) ``` interface ref Proxy ``` Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/net/proxy/#L3) ``` fun box apply( wrap: TCPConnectionNotify iso) : TCPConnectionNotify iso^ ``` #### Parameters * wrap: [TCPConnectionNotify](net-tcpconnectionnotify) iso #### Returns * [TCPConnectionNotify](net-tcpconnectionnotify) iso^ pony ProcessNotify ProcessNotify ============= [[Source]](https://stdlib.ponylang.io/src/process/process_notify/#L1) Notifications for Process connections. ``` interface ref ProcessNotify ``` Public Functions ---------------- ### created [[Source]](https://stdlib.ponylang.io/src/process/process_notify/#L6) ProcessMonitor calls this when it is created. ``` fun ref created( process: ProcessMonitor ref) : None val ``` #### Parameters * process: [ProcessMonitor](process-processmonitor) ref #### Returns * [None](builtin-none) val ### stdout [[Source]](https://stdlib.ponylang.io/src/process/process_notify/#L11) ProcessMonitor calls this when new data is received on STDOUT of the forked process ``` fun ref stdout( process: ProcessMonitor ref, data: Array[U8 val] iso) : None val ``` #### Parameters * process: [ProcessMonitor](process-processmonitor) ref * data: [Array](builtin-array)[[U8](builtin-u8) val] iso #### Returns * [None](builtin-none) val ### stderr [[Source]](https://stdlib.ponylang.io/src/process/process_notify/#L17) ProcessMonitor calls this when new data is received on STDERR of the forked process ``` fun ref stderr( process: ProcessMonitor ref, data: Array[U8 val] iso) : None val ``` #### Parameters * process: [ProcessMonitor](process-processmonitor) ref * data: [Array](builtin-array)[[U8](builtin-u8) val] iso #### Returns * [None](builtin-none) val ### failed [[Source]](https://stdlib.ponylang.io/src/process/process_notify/#L23) ProcessMonitor calls this if we run into errors communicating with the forked process. ``` fun ref failed( process: ProcessMonitor ref, err: ProcessError val) : None val ``` #### Parameters * process: [ProcessMonitor](process-processmonitor) ref * err: [ProcessError](process-processerror) val #### Returns * [None](builtin-none) val ### expect [[Source]](https://stdlib.ponylang.io/src/process/process_notify/#L29) Called when the process monitor has been told to expect a certain quantity of bytes. This allows nested notifiers to change the expected quantity, which allows a lower level protocol to handle any framing. ``` fun ref expect( process: ProcessMonitor ref, qty: USize val) : USize val ``` #### Parameters * process: [ProcessMonitor](process-processmonitor) ref * qty: [USize](builtin-usize) val #### Returns * [USize](builtin-usize) val ### dispose [[Source]](https://stdlib.ponylang.io/src/process/process_notify/#L37) Call when ProcessMonitor terminates to cleanup ProcessNotify. We return the exit status of the child process, it can be either an instance of [Exited](process-exited) if the process finished. The childs exit code can be retrieved using [Exited.exit\_code()](process-exited#exit_code). On Posix systems, if the process has been killed by a signal (e.g. through the `kill` command), `child_exit_status` will be an instance of [Signaled](process-signaled) with the signal number that terminated the process available via [Signaled.signal()](process-signaled#signal). ``` fun ref dispose( process: ProcessMonitor ref, child_exit_status: (Exited val | Signaled val)) : None val ``` #### Parameters * process: [ProcessMonitor](process-processmonitor) ref * child\_exit\_status: ([Exited](process-exited) val | [Signaled](process-signaled) val) #### Returns * [None](builtin-none) val pony MT MT == [[Source]](https://stdlib.ponylang.io/src/random/mt/#L1) A Mersenne Twister. This is a non-cryptographic random number generator. This should only be used for legacy applications that require a Mersenne Twister, otherwise use Rand. ``` class ref MT is Random ref ``` #### Implements * [Random](random-random) ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/random/mt/#L10) Create with the specified seed. Returned values are deterministic for a given seed. ``` new ref create( x: U64 val = 5489, y: U64 val = 0) : MT ref^ ``` #### Parameters * x: [U64](builtin-u64) val = 5489 * y: [U64](builtin-u64) val = 0 #### Returns * [MT](index) ref^ Public Functions ---------------- ### next [[Source]](https://stdlib.ponylang.io/src/random/mt/#L29) A random integer in [0, 2^64) ``` fun ref next() : U64 val ``` #### Returns * [U64](builtin-u64) val ### has\_next [[Source]](https://stdlib.ponylang.io/src/random/random/#L34) ``` fun tag has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### u8 [[Source]](https://stdlib.ponylang.io/src/random/random/#L45) ``` fun ref u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 [[Source]](https://stdlib.ponylang.io/src/random/random/#L51) ``` fun ref u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 [[Source]](https://stdlib.ponylang.io/src/random/random/#L57) ``` fun ref u32() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64 [[Source]](https://stdlib.ponylang.io/src/random/random/#L63) ``` fun ref u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 [[Source]](https://stdlib.ponylang.io/src/random/random/#L69) ``` fun ref u128() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong [[Source]](https://stdlib.ponylang.io/src/random/random/#L75) ``` fun ref ulong() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize [[Source]](https://stdlib.ponylang.io/src/random/random/#L85) ``` fun ref usize() : USize val ``` #### Returns * [USize](builtin-usize) val ### i8 [[Source]](https://stdlib.ponylang.io/src/random/random/#L95) ``` fun ref i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 [[Source]](https://stdlib.ponylang.io/src/random/random/#L101) ``` fun ref i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 [[Source]](https://stdlib.ponylang.io/src/random/random/#L107) ``` fun ref i32() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64 [[Source]](https://stdlib.ponylang.io/src/random/random/#L113) ``` fun ref i64() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128 [[Source]](https://stdlib.ponylang.io/src/random/random/#L119) ``` fun ref i128() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong [[Source]](https://stdlib.ponylang.io/src/random/random/#L125) ``` fun ref ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize [[Source]](https://stdlib.ponylang.io/src/random/random/#L131) ``` fun ref isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### int\_fp\_mult[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] [[Source]](https://stdlib.ponylang.io/src/random/random/#L137) ``` fun ref int_fp_mult[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### int[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] [[Source]](https://stdlib.ponylang.io/src/random/random/#L143) ``` fun ref int[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### int\_unbiased[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] [[Source]](https://stdlib.ponylang.io/src/random/random/#L159) ``` fun ref int_unbiased[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### real [[Source]](https://stdlib.ponylang.io/src/random/random/#L195) ``` fun ref real() : F64 val ``` #### Returns * [F64](builtin-f64) val ### shuffle[A: A] [[Source]](https://stdlib.ponylang.io/src/random/random/#L201) ``` fun ref shuffle[A: A]( array: Array[A] ref) : None val ``` #### Parameters * array: [Array](builtin-array)[A] ref #### Returns * [None](builtin-none) val pony USize USize ===== [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L431) ``` primitive val USize is UnsignedInteger[USize val] val ``` #### Implements * [UnsignedInteger](builtin-unsignedinteger)[[USize](index) val] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L432) ``` new val create( value: USize val) : USize val^ ``` #### Parameters * value: [USize](index) val #### Returns * [USize](index) val^ ### from[A: (([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](builtin-i32) val | [I64](builtin-i64) val | [I128](builtin-i128) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val | [U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](index) val | [F32](builtin-f32) val | [F64](builtin-f64) val) & [Real](builtin-real)[A] val)] [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L433) ``` new val from[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[A] val)]( a: A) : USize val^ ``` #### Parameters * a: A #### Returns * [USize](index) val^ ### min\_value [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L435) ``` new val min_value() : USize val^ ``` #### Returns * [USize](index) val^ ### max\_value [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L437) ``` new val max_value() : USize val^ ``` #### Returns * [USize](index) val^ Public Functions ---------------- ### next\_pow2 [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L444) ``` fun box next_pow2() : USize val ``` #### Returns * [USize](index) val ### abs [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L448) ``` fun box abs() : USize val ``` #### Returns * [USize](index) val ### bit\_reverse [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L450) ``` fun box bit_reverse() : USize val ``` #### Returns * [USize](index) val ### bswap [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L457) ``` fun box bswap() : USize val ``` #### Returns * [USize](index) val ### popcount [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L464) ``` fun box popcount() : USize val ``` #### Returns * [USize](index) val ### clz [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L471) ``` fun box clz() : USize val ``` #### Returns * [USize](index) val ### ctz [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L478) ``` fun box ctz() : USize val ``` #### Returns * [USize](index) val ### clz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L485) Unsafe operation. If this is 0, the result is undefined. ``` fun box clz_unsafe() : USize val ``` #### Returns * [USize](index) val ### ctz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L496) Unsafe operation. If this is 0, the result is undefined. ``` fun box ctz_unsafe() : USize val ``` #### Returns * [USize](index) val ### bitwidth [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L507) ``` fun box bitwidth() : USize val ``` #### Returns * [USize](index) val ### bytewidth [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L509) ``` fun box bytewidth() : USize val ``` #### Returns * [USize](index) val ### min [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L511) ``` fun box min( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### max [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L512) ``` fun box max( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### addc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L514) ``` fun box addc( y: USize val) : (USize val , Bool val) ``` #### Parameters * y: [USize](index) val #### Returns * ([USize](index) val , [Bool](builtin-bool) val) ### subc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L521) ``` fun box subc( y: USize val) : (USize val , Bool val) ``` #### Parameters * y: [USize](index) val #### Returns * ([USize](index) val , [Bool](builtin-bool) val) ### mulc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L528) ``` fun box mulc( y: USize val) : (USize val , Bool val) ``` #### Parameters * y: [USize](index) val #### Returns * ([USize](index) val , [Bool](builtin-bool) val) ### divc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L535) ``` fun box divc( y: USize val) : (USize val , Bool val) ``` #### Parameters * y: [USize](index) val #### Returns * ([USize](index) val , [Bool](builtin-bool) val) ### remc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L538) ``` fun box remc( y: USize val) : (USize val , Bool val) ``` #### Parameters * y: [USize](index) val #### Returns * ([USize](index) val , [Bool](builtin-bool) val) ### add\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L541) ``` fun box add_partial( y: USize val) : USize val ? ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ? ### sub\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L544) ``` fun box sub_partial( y: USize val) : USize val ? ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ? ### mul\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L547) ``` fun box mul_partial( y: USize val) : USize val ? ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ? ### div\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L550) ``` fun box div_partial( y: USize val) : USize val ? ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ? ### rem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L553) ``` fun box rem_partial( y: USize val) : USize val ? ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ? ### divrem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L556) ``` fun box divrem_partial( y: USize val) : (USize val , USize val) ? ``` #### Parameters * y: [USize](index) val #### Returns * ([USize](index) val , [USize](index) val) ? ### shl ``` fun box shl( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### shr ``` fun box shr( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### fld ``` fun box fld( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### fldc ``` fun box fldc( y: USize val) : (USize val , Bool val) ``` #### Parameters * y: [USize](index) val #### Returns * ([USize](index) val , [Bool](builtin-bool) val) ### fld\_partial ``` fun box fld_partial( y: USize val) : USize val ? ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ? ### fld\_unsafe ``` fun box fld_unsafe( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### mod ``` fun box mod( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### modc ``` fun box modc( y: USize val) : (USize val , Bool val) ``` #### Parameters * y: [USize](index) val #### Returns * ([USize](index) val , [Bool](builtin-bool) val) ### mod\_partial ``` fun box mod_partial( y: USize val) : USize val ? ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ? ### mod\_unsafe ``` fun box mod_unsafe( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### shl\_unsafe ``` fun box shl_unsafe( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### shr\_unsafe ``` fun box shr_unsafe( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### rotl ``` fun box rotl( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### rotr ``` fun box rotr( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### string ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### add\_unsafe ``` fun box add_unsafe( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### sub\_unsafe ``` fun box sub_unsafe( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### mul\_unsafe ``` fun box mul_unsafe( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### div\_unsafe ``` fun box div_unsafe( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### divrem\_unsafe ``` fun box divrem_unsafe( y: USize val) : (USize val , USize val) ``` #### Parameters * y: [USize](index) val #### Returns * ([USize](index) val , [USize](index) val) ### rem\_unsafe ``` fun box rem_unsafe( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### neg\_unsafe ``` fun box neg_unsafe() : USize val ``` #### Returns * [USize](index) val ### op\_and ``` fun box op_and( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### op\_or ``` fun box op_or( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### op\_xor ``` fun box op_xor( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### op\_not ``` fun box op_not() : USize val ``` #### Returns * [USize](index) val ### add ``` fun box add( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### sub ``` fun box sub( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### mul ``` fun box mul( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### div ``` fun box div( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### divrem ``` fun box divrem( y: USize val) : (USize val , USize val) ``` #### Parameters * y: [USize](index) val #### Returns * ([USize](index) val , [USize](index) val) ### rem ``` fun box rem( y: USize val) : USize val ``` #### Parameters * y: [USize](index) val #### Returns * [USize](index) val ### neg ``` fun box neg() : USize val ``` #### Returns * [USize](index) val ### eq ``` fun box eq( y: USize val) : Bool val ``` #### Parameters * y: [USize](index) val #### Returns * [Bool](builtin-bool) val ### ne ``` fun box ne( y: USize val) : Bool val ``` #### Parameters * y: [USize](index) val #### Returns * [Bool](builtin-bool) val ### lt ``` fun box lt( y: USize val) : Bool val ``` #### Parameters * y: [USize](index) val #### Returns * [Bool](builtin-bool) val ### le ``` fun box le( y: USize val) : Bool val ``` #### Parameters * y: [USize](index) val #### Returns * [Bool](builtin-bool) val ### ge ``` fun box ge( y: USize val) : Bool val ``` #### Parameters * y: [USize](index) val #### Returns * [Bool](builtin-bool) val ### gt ``` fun box gt( y: USize val) : Bool val ``` #### Parameters * y: [USize](index) val #### Returns * [Bool](builtin-bool) val ### hash ``` fun box hash() : USize val ``` #### Returns * [USize](index) val ### hash64 ``` fun box hash64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### i8 ``` fun box i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 ``` fun box i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 ``` fun box i32() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64 ``` fun box i64() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128 ``` fun box i128() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong ``` fun box ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize ``` fun box isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8 ``` fun box u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 ``` fun box u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 ``` fun box u32() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64 ``` fun box u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 ``` fun box u128() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong ``` fun box ulong() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize ``` fun box usize() : USize val ``` #### Returns * [USize](index) val ### f32 ``` fun box f32() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64 ``` fun box f64() : F64 val ``` #### Returns * [F64](builtin-f64) val ### i8\_unsafe ``` fun box i8_unsafe() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16\_unsafe ``` fun box i16_unsafe() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32\_unsafe ``` fun box i32_unsafe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64\_unsafe ``` fun box i64_unsafe() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128\_unsafe ``` fun box i128_unsafe() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong\_unsafe ``` fun box ilong_unsafe() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize\_unsafe ``` fun box isize_unsafe() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8\_unsafe ``` fun box u8_unsafe() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16\_unsafe ``` fun box u16_unsafe() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32\_unsafe ``` fun box u32_unsafe() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64\_unsafe ``` fun box u64_unsafe() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128\_unsafe ``` fun box u128_unsafe() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong\_unsafe ``` fun box ulong_unsafe() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize\_unsafe ``` fun box usize_unsafe() : USize val ``` #### Returns * [USize](index) val ### f32\_unsafe ``` fun box f32_unsafe() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64\_unsafe ``` fun box f64_unsafe() : F64 val ``` #### Returns * [F64](builtin-f64) val ### compare ``` fun box compare( that: USize val) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [USize](index) val #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val)
programming_docs
pony BenchConfig BenchConfig =========== [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L53) Configuration of a benchmark. ``` class val BenchConfig ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L70) ``` new val create( samples': USize val = 20, max_iterations': U64 val = 1000000000, max_sample_time': U64 val = 100000000) : BenchConfig val^ ``` #### Parameters * samples': [USize](builtin-usize) val = 20 * max\_iterations': [U64](builtin-u64) val = 1000000000 * max\_sample\_time': [U64](builtin-u64) val = 100000000 #### Returns * [BenchConfig](index) val^ Public fields ------------- ### let samples: [USize](builtin-usize) val [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L57) Total number of samples to be measured. (Default: 20) ### let max\_iterations: [U64](builtin-u64) val [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L61) Maximum number of iterations to execute per sample. (Default: 1\_000\_000\_000) ### let max\_sample\_time: [U64](builtin-u64) val [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L65) Maximum time to execute a sample in Nanoseconds. (Default: 100\_000\_000) pony Benchmark Benchmark ========= [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L2) ``` type Benchmark is (MicroBenchmark iso | AsyncMicroBenchmark iso) ``` #### Type Alias For * ([MicroBenchmark](ponybench-microbenchmark) iso | [AsyncMicroBenchmark](ponybench-asyncmicrobenchmark) iso) pony OSSockOpt OSSockOpt ========= [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L4) Convenience functions to fetch the option level and option name constants (arguments #2 and #3) for the `getsockopt(2)` and `setsockopt(2)` operating system calls. The values of the option level and option name constants are typically C preprocessor macros, e.g., `#define SOMETHING 42`. These macro names are upper case and may contain multiple consecutive underscore characters (though this is rare, for example, `IP_NAT__XXX`). The function names in this primitive are derived by the C macro name and then: * converted to lower case * any double underscore (`__`) is converted to a single underscore (`_`). These constants are *not* stable between Pony releases. Values returned by this function may be held by long-lived variables by the calling process: values cannot change while the process runs. Programmers must not cache any of these values for purposes of sharing them for use by any other Pony program (for example, sharing via serialization & deserialization or via direct shared memory). Many functions may return `-1`, which means that the constant's value could not be determined at the Pony runtime library compile time. One cause may be that the option truly isn't available, for example, the option level constant `IPPROTO_3PC` is available on MacOS 10.x but not on Linux 4.4. Another cause may be the Pony runtime library's compilation did not include the correct header file(s) for the target OS platform. A third cause of error is due to the regular expression-based approach used to harvest desirable constants. It is not fool-proof. The regexp used is too broad and finds some macros that are not supposed to be used with `getsockopt(2)` and `setsockopt(2)`. Please consult your platform's documentation to verify the names of the option level and option name macros. The following code fragments are equivalent: set the socket receive buffer size for the file descriptor `fd` to `4455`. ``` /* In C */ int option_value = 4455; setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &option_value, 4); /* In Pony */ var option: I32 = 4455; @pony_os_setsockopt[I32](fd, OSSockOpt.sol_socket(), OSSockOpt.so_rcvbuf(), addressof option, I32(4)) ``` ``` primitive val OSSockOpt ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L4) ``` new val create() : OSSockOpt val^ ``` #### Returns * [OSSockOpt](index) val^ Public Functions ---------------- ### ipproto\_3pc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L76) ``` fun box ipproto_3pc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_adfs [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L77) ``` fun box ipproto_adfs() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ah [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L78) ``` fun box ipproto_ah() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ahip [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L79) ``` fun box ipproto_ahip() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_apes [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L80) ``` fun box ipproto_apes() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_argus [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L81) ``` fun box ipproto_argus() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ax25 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L82) ``` fun box ipproto_ax25() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_beetph [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L83) ``` fun box ipproto_beetph() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_bha [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L84) ``` fun box ipproto_bha() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_blt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L85) ``` fun box ipproto_blt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_brsatmon [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L86) ``` fun box ipproto_brsatmon() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_carp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L87) ``` fun box ipproto_carp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_cftp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L88) ``` fun box ipproto_cftp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_chaos [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L89) ``` fun box ipproto_chaos() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_cmtp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L90) ``` fun box ipproto_cmtp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_comp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L91) ``` fun box ipproto_comp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_cphb [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L92) ``` fun box ipproto_cphb() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_cpnx [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L93) ``` fun box ipproto_cpnx() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_dccp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L94) ``` fun box ipproto_dccp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ddp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L95) ``` fun box ipproto_ddp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_dgp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L96) ``` fun box ipproto_dgp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_divert [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L97) ``` fun box ipproto_divert() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_done [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L98) ``` fun box ipproto_done() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_dstopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L99) ``` fun box ipproto_dstopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_egp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L100) ``` fun box ipproto_egp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_emcon [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L101) ``` fun box ipproto_emcon() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_encap [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L102) ``` fun box ipproto_encap() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_eon [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L103) ``` fun box ipproto_eon() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_esp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L104) ``` fun box ipproto_esp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_etherip [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L105) ``` fun box ipproto_etherip() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_fragment [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L106) ``` fun box ipproto_fragment() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ggp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L107) ``` fun box ipproto_ggp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_gmtp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L108) ``` fun box ipproto_gmtp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_gre [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L109) ``` fun box ipproto_gre() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_hello [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L110) ``` fun box ipproto_hello() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_hip [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L111) ``` fun box ipproto_hip() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_hmp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L112) ``` fun box ipproto_hmp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_hopopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L113) ``` fun box ipproto_hopopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_icmp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L114) ``` fun box ipproto_icmp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_icmpv6 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L115) ``` fun box ipproto_icmpv6() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_idp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L116) ``` fun box ipproto_idp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_idpr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L117) ``` fun box ipproto_idpr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_idrp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L118) ``` fun box ipproto_idrp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_igmp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L119) ``` fun box ipproto_igmp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_igp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L120) ``` fun box ipproto_igp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_igrp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L121) ``` fun box ipproto_igrp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_il [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L122) ``` fun box ipproto_il() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_inlsp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L123) ``` fun box ipproto_inlsp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_inp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L124) ``` fun box ipproto_inp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ip [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L125) ``` fun box ipproto_ip() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ipcomp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L126) ``` fun box ipproto_ipcomp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ipcv [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L127) ``` fun box ipproto_ipcv() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ipeip [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L128) ``` fun box ipproto_ipeip() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ipip [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L129) ``` fun box ipproto_ipip() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ippc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L130) ``` fun box ipproto_ippc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ipv4 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L131) ``` fun box ipproto_ipv4() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ipv6 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L132) ``` fun box ipproto_ipv6() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_irtp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L133) ``` fun box ipproto_irtp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_kryptolan [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L134) ``` fun box ipproto_kryptolan() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_larp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L135) ``` fun box ipproto_larp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_leaf1 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L136) ``` fun box ipproto_leaf1() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_leaf2 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L137) ``` fun box ipproto_leaf2() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_max [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L138) ``` fun box ipproto_max() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_maxid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L139) ``` fun box ipproto_maxid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_meas [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L140) ``` fun box ipproto_meas() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_mh [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L141) ``` fun box ipproto_mh() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_mhrp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L142) ``` fun box ipproto_mhrp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_micp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L143) ``` fun box ipproto_micp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_mobile [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L144) ``` fun box ipproto_mobile() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_mpls [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L145) ``` fun box ipproto_mpls() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_mtp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L146) ``` fun box ipproto_mtp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_mux [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L147) ``` fun box ipproto_mux() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_nd [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L148) ``` fun box ipproto_nd() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_nhrp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L149) ``` fun box ipproto_nhrp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_none [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L150) ``` fun box ipproto_none() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_nsp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L151) ``` fun box ipproto_nsp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_nvpii [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L152) ``` fun box ipproto_nvpii() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_old\_divert [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L153) ``` fun box ipproto_old_divert() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ospfigp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L154) ``` fun box ipproto_ospfigp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_pfsync [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L155) ``` fun box ipproto_pfsync() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_pgm [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L156) ``` fun box ipproto_pgm() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_pigp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L157) ``` fun box ipproto_pigp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_pim [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L158) ``` fun box ipproto_pim() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_prm [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L159) ``` fun box ipproto_prm() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_pup [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L160) ``` fun box ipproto_pup() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_pvp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L161) ``` fun box ipproto_pvp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_raw [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L162) ``` fun box ipproto_raw() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_rccmon [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L163) ``` fun box ipproto_rccmon() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_rdp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L164) ``` fun box ipproto_rdp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_reserved\_253 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L165) ``` fun box ipproto_reserved_253() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_reserved\_254 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L166) ``` fun box ipproto_reserved_254() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_routing [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L167) ``` fun box ipproto_routing() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_rsvp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L168) ``` fun box ipproto_rsvp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_rvd [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L169) ``` fun box ipproto_rvd() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_satexpak [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L170) ``` fun box ipproto_satexpak() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_satmon [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L171) ``` fun box ipproto_satmon() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_sccsp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L172) ``` fun box ipproto_sccsp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_sctp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L173) ``` fun box ipproto_sctp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_sdrp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L174) ``` fun box ipproto_sdrp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_send [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L175) ``` fun box ipproto_send() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_sep [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L176) ``` fun box ipproto_sep() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_shim6 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L177) ``` fun box ipproto_shim6() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_skip [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L178) ``` fun box ipproto_skip() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_spacer [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L179) ``` fun box ipproto_spacer() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_srpc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L180) ``` fun box ipproto_srpc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_st [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L181) ``` fun box ipproto_st() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_svmtp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L182) ``` fun box ipproto_svmtp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_swipe [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L183) ``` fun box ipproto_swipe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_tcf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L184) ``` fun box ipproto_tcf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_tcp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L185) ``` fun box ipproto_tcp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_tlsp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L186) ``` fun box ipproto_tlsp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_tp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L187) ``` fun box ipproto_tp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_tpxx [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L188) ``` fun box ipproto_tpxx() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_trunk1 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L189) ``` fun box ipproto_trunk1() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_trunk2 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L190) ``` fun box ipproto_trunk2() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_ttp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L191) ``` fun box ipproto_ttp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_udp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L192) ``` fun box ipproto_udp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_udplite [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L193) ``` fun box ipproto_udplite() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_vines [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L194) ``` fun box ipproto_vines() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_visa [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L195) ``` fun box ipproto_visa() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_vmtp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L196) ``` fun box ipproto_vmtp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_wbexpak [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L197) ``` fun box ipproto_wbexpak() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_wbmon [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L198) ``` fun box ipproto_wbmon() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_wsn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L199) ``` fun box ipproto_wsn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_xnet [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L200) ``` fun box ipproto_xnet() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipproto\_xtp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L201) ``` fun box ipproto_xtp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_atalk [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L202) ``` fun box sol_atalk() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_ax25 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L203) ``` fun box sol_ax25() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_hci\_raw [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L204) ``` fun box sol_hci_raw() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_ipx [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L205) ``` fun box sol_ipx() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_l2cap [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L206) ``` fun box sol_l2cap() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_local [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L207) ``` fun box sol_local() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_ndrvproto [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L208) ``` fun box sol_ndrvproto() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_netrom [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L209) ``` fun box sol_netrom() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_rds [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L210) ``` fun box sol_rds() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_rfcomm [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L211) ``` fun box sol_rfcomm() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_rose [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L212) ``` fun box sol_rose() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_sco [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L213) ``` fun box sol_sco() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_socket [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L214) ``` fun box sol_socket() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_tipc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L215) ``` fun box sol_tipc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sol\_udp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L216) ``` fun box sol_udp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### af\_coip [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L225) ``` fun box af_coip() : I32 val ``` #### Returns * [I32](builtin-i32) val ### af\_inet [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L226) ``` fun box af_inet() : I32 val ``` #### Returns * [I32](builtin-i32) val ### af\_inet6 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L227) ``` fun box af_inet6() : I32 val ``` #### Returns * [I32](builtin-i32) val ### bluetooth\_proto\_sco [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L228) ``` fun box bluetooth_proto_sco() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_nr\_pkt\_types [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L229) ``` fun box dccp_nr_pkt_types() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_service\_list\_max\_len [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L230) ``` fun box dccp_service_list_max_len() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_single\_opt\_maxlen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L231) ``` fun box dccp_single_opt_maxlen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_available\_ccids [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L232) ``` fun box dccp_sockopt_available_ccids() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_ccid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L233) ``` fun box dccp_sockopt_ccid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_ccid\_rx\_info [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L234) ``` fun box dccp_sockopt_ccid_rx_info() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_ccid\_tx\_info [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L235) ``` fun box dccp_sockopt_ccid_tx_info() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_change\_l [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L236) ``` fun box dccp_sockopt_change_l() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_change\_r [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L237) ``` fun box dccp_sockopt_change_r() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_get\_cur\_mps [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L238) ``` fun box dccp_sockopt_get_cur_mps() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_packet\_size [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L239) ``` fun box dccp_sockopt_packet_size() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_qpolicy\_id [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L240) ``` fun box dccp_sockopt_qpolicy_id() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_qpolicy\_txqlen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L241) ``` fun box dccp_sockopt_qpolicy_txqlen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_recv\_cscov [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L242) ``` fun box dccp_sockopt_recv_cscov() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_rx\_ccid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L243) ``` fun box dccp_sockopt_rx_ccid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_send\_cscov [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L244) ``` fun box dccp_sockopt_send_cscov() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_server\_timewait [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L245) ``` fun box dccp_sockopt_server_timewait() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_service [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L246) ``` fun box dccp_sockopt_service() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dccp\_sockopt\_tx\_ccid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L247) ``` fun box dccp_sockopt_tx_ccid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_acceptmode [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L248) ``` fun box dso_acceptmode() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_conaccept [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L249) ``` fun box dso_conaccept() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_conaccess [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L250) ``` fun box dso_conaccess() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_condata [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L251) ``` fun box dso_condata() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_conreject [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L252) ``` fun box dso_conreject() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_cork [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L253) ``` fun box dso_cork() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_disdata [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L254) ``` fun box dso_disdata() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_info [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L255) ``` fun box dso_info() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_linkinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L256) ``` fun box dso_linkinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_max [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L257) ``` fun box dso_max() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_maxwindow [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L258) ``` fun box dso_maxwindow() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_nodelay [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L259) ``` fun box dso_nodelay() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_seqpacket [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L260) ``` fun box dso_seqpacket() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_services [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L261) ``` fun box dso_services() : I32 val ``` #### Returns * [I32](builtin-i32) val ### dso\_stream [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L262) ``` fun box dso_stream() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_address [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L263) ``` fun box icmp_address() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_addressreply [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L264) ``` fun box icmp_addressreply() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_dest\_unreach [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L265) ``` fun box icmp_dest_unreach() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_echo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L266) ``` fun box icmp_echo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_echoreply [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L267) ``` fun box icmp_echoreply() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_exc\_fragtime [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L268) ``` fun box icmp_exc_fragtime() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_exc\_ttl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L269) ``` fun box icmp_exc_ttl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_filter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L270) ``` fun box icmp_filter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_frag\_needed [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L271) ``` fun box icmp_frag_needed() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_host\_ano [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L272) ``` fun box icmp_host_ano() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_host\_isolated [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L273) ``` fun box icmp_host_isolated() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_host\_unknown [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L274) ``` fun box icmp_host_unknown() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_host\_unreach [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L275) ``` fun box icmp_host_unreach() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_host\_unr\_tos [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L276) ``` fun box icmp_host_unr_tos() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_info\_reply [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L277) ``` fun box icmp_info_reply() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_info\_request [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L278) ``` fun box icmp_info_request() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_net\_ano [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L279) ``` fun box icmp_net_ano() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_net\_unknown [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L280) ``` fun box icmp_net_unknown() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_net\_unreach [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L281) ``` fun box icmp_net_unreach() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_net\_unr\_tos [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L282) ``` fun box icmp_net_unr_tos() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_parameterprob [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L283) ``` fun box icmp_parameterprob() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_pkt\_filtered [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L284) ``` fun box icmp_pkt_filtered() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_port\_unreach [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L285) ``` fun box icmp_port_unreach() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_prec\_cutoff [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L286) ``` fun box icmp_prec_cutoff() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_prec\_violation [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L287) ``` fun box icmp_prec_violation() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_prot\_unreach [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L288) ``` fun box icmp_prot_unreach() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_redirect [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L289) ``` fun box icmp_redirect() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_redir\_host [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L290) ``` fun box icmp_redir_host() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_redir\_hosttos [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L291) ``` fun box icmp_redir_hosttos() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_redir\_net [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L292) ``` fun box icmp_redir_net() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_redir\_nettos [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L293) ``` fun box icmp_redir_nettos() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_source\_quench [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L294) ``` fun box icmp_source_quench() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_sr\_failed [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L295) ``` fun box icmp_sr_failed() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_timestamp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L296) ``` fun box icmp_timestamp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_timestampreply [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L297) ``` fun box icmp_timestampreply() : I32 val ``` #### Returns * [I32](builtin-i32) val ### icmp\_time\_exceeded [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L298) ``` fun box icmp_time_exceeded() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_acceptsourceroute [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L299) ``` fun box ipctl_acceptsourceroute() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_defmtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L300) ``` fun box ipctl_defmtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_defttl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L301) ``` fun box ipctl_defttl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_directedbroadcast [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L302) ``` fun box ipctl_directedbroadcast() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_fastforwarding [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L303) ``` fun box ipctl_fastforwarding() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_forwarding [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L304) ``` fun box ipctl_forwarding() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_gif\_ttl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L305) ``` fun box ipctl_gif_ttl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_intrdqdrops [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L306) ``` fun box ipctl_intrdqdrops() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_intrdqmaxlen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L307) ``` fun box ipctl_intrdqmaxlen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_intrqdrops [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L308) ``` fun box ipctl_intrqdrops() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_intrqmaxlen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L309) ``` fun box ipctl_intrqmaxlen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_keepfaith [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L310) ``` fun box ipctl_keepfaith() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_maxid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L311) ``` fun box ipctl_maxid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_rtexpire [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L312) ``` fun box ipctl_rtexpire() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_rtmaxcache [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L313) ``` fun box ipctl_rtmaxcache() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_rtminexpire [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L314) ``` fun box ipctl_rtminexpire() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_sendredirects [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L315) ``` fun box ipctl_sendredirects() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_sourceroute [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L316) ``` fun box ipctl_sourceroute() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipctl\_stats [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L317) ``` fun box ipctl_stats() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipport\_ephemeralfirst [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L318) ``` fun box ipport_ephemeralfirst() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipport\_ephemerallast [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L319) ``` fun box ipport_ephemerallast() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipport\_hifirstauto [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L320) ``` fun box ipport_hifirstauto() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipport\_hilastauto [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L321) ``` fun box ipport_hilastauto() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipport\_max [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L322) ``` fun box ipport_max() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipport\_reserved [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L323) ``` fun box ipport_reserved() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipport\_reservedstart [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L324) ``` fun box ipport_reservedstart() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipport\_userreserved [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L325) ``` fun box ipport_userreserved() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_2292dstopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L326) ``` fun box ipv6_2292dstopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_2292hoplimit [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L327) ``` fun box ipv6_2292hoplimit() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_2292hopopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L328) ``` fun box ipv6_2292hopopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_2292pktinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L329) ``` fun box ipv6_2292pktinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_2292pktoptions [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L330) ``` fun box ipv6_2292pktoptions() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_2292rthdr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L331) ``` fun box ipv6_2292rthdr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_addrform [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L332) ``` fun box ipv6_addrform() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_addr\_preferences [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L333) ``` fun box ipv6_addr_preferences() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_add\_membership [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L334) ``` fun box ipv6_add_membership() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_authhdr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L335) ``` fun box ipv6_authhdr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_autoflowlabel [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L336) ``` fun box ipv6_autoflowlabel() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_checksum [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L337) ``` fun box ipv6_checksum() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_dontfrag [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L338) ``` fun box ipv6_dontfrag() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_drop\_membership [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L339) ``` fun box ipv6_drop_membership() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_dstopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L340) ``` fun box ipv6_dstopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_flowinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L341) ``` fun box ipv6_flowinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_flowinfo\_flowlabel [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L342) ``` fun box ipv6_flowinfo_flowlabel() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_flowinfo\_priority [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L343) ``` fun box ipv6_flowinfo_priority() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_flowinfo\_send [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L344) ``` fun box ipv6_flowinfo_send() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_flowlabel\_mgr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L345) ``` fun box ipv6_flowlabel_mgr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_a\_get [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L346) ``` fun box ipv6_fl_a_get() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_a\_put [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L347) ``` fun box ipv6_fl_a_put() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_a\_renew [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L348) ``` fun box ipv6_fl_a_renew() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_f\_create [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L349) ``` fun box ipv6_fl_f_create() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_f\_excl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L350) ``` fun box ipv6_fl_f_excl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_f\_reflect [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L351) ``` fun box ipv6_fl_f_reflect() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_f\_remote [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L352) ``` fun box ipv6_fl_f_remote() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_s\_any [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L353) ``` fun box ipv6_fl_s_any() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_s\_excl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L354) ``` fun box ipv6_fl_s_excl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_s\_none [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L355) ``` fun box ipv6_fl_s_none() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_s\_process [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L356) ``` fun box ipv6_fl_s_process() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_fl\_s\_user [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L357) ``` fun box ipv6_fl_s_user() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_hoplimit [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L358) ``` fun box ipv6_hoplimit() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_hopopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L359) ``` fun box ipv6_hopopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_ipsec\_policy [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L360) ``` fun box ipv6_ipsec_policy() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_join\_anycast [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L361) ``` fun box ipv6_join_anycast() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_leave\_anycast [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L362) ``` fun box ipv6_leave_anycast() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_minhopcount [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L363) ``` fun box ipv6_minhopcount() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_mtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L364) ``` fun box ipv6_mtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_mtu\_discover [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L365) ``` fun box ipv6_mtu_discover() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_multicast\_hops [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L366) ``` fun box ipv6_multicast_hops() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_multicast\_if [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L367) ``` fun box ipv6_multicast_if() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_multicast\_loop [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L368) ``` fun box ipv6_multicast_loop() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_nexthop [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L369) ``` fun box ipv6_nexthop() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_origdstaddr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L370) ``` fun box ipv6_origdstaddr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_pathmtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L371) ``` fun box ipv6_pathmtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_pktinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L372) ``` fun box ipv6_pktinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_pmtudisc\_do [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L373) ``` fun box ipv6_pmtudisc_do() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_pmtudisc\_dont [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L374) ``` fun box ipv6_pmtudisc_dont() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_pmtudisc\_interface [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L375) ``` fun box ipv6_pmtudisc_interface() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_pmtudisc\_omit [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L376) ``` fun box ipv6_pmtudisc_omit() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_pmtudisc\_probe [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L377) ``` fun box ipv6_pmtudisc_probe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_pmtudisc\_want [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L378) ``` fun box ipv6_pmtudisc_want() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_prefer\_src\_cga [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L379) ``` fun box ipv6_prefer_src_cga() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_prefer\_src\_coa [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L380) ``` fun box ipv6_prefer_src_coa() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_prefer\_src\_home [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L381) ``` fun box ipv6_prefer_src_home() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_prefer\_src\_noncga [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L382) ``` fun box ipv6_prefer_src_noncga() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_prefer\_src\_public [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L383) ``` fun box ipv6_prefer_src_public() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_prefer\_src\_pubtmp\_default [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L384) ``` fun box ipv6_prefer_src_pubtmp_default() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_prefer\_src\_tmp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L385) ``` fun box ipv6_prefer_src_tmp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_10 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L386) ``` fun box ipv6_priority_10() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_11 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L387) ``` fun box ipv6_priority_11() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_12 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L388) ``` fun box ipv6_priority_12() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_13 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L389) ``` fun box ipv6_priority_13() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_14 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L390) ``` fun box ipv6_priority_14() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_15 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L391) ``` fun box ipv6_priority_15() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_8 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L392) ``` fun box ipv6_priority_8() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_9 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L393) ``` fun box ipv6_priority_9() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_bulk [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L394) ``` fun box ipv6_priority_bulk() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_control [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L395) ``` fun box ipv6_priority_control() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_filler [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L396) ``` fun box ipv6_priority_filler() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_interactive [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L397) ``` fun box ipv6_priority_interactive() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_reserved1 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L398) ``` fun box ipv6_priority_reserved1() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_reserved2 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L399) ``` fun box ipv6_priority_reserved2() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_unattended [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L400) ``` fun box ipv6_priority_unattended() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_priority\_uncharacterized [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L401) ``` fun box ipv6_priority_uncharacterized() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_recvdstopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L402) ``` fun box ipv6_recvdstopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_recverr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L403) ``` fun box ipv6_recverr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_recvhoplimit [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L404) ``` fun box ipv6_recvhoplimit() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_recvhopopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L405) ``` fun box ipv6_recvhopopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_recvorigdstaddr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L406) ``` fun box ipv6_recvorigdstaddr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_recvpathmtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L407) ``` fun box ipv6_recvpathmtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_recvpktinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L408) ``` fun box ipv6_recvpktinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_recvrthdr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L409) ``` fun box ipv6_recvrthdr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_recvtclass [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L410) ``` fun box ipv6_recvtclass() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_router\_alert [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L411) ``` fun box ipv6_router_alert() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_rthdr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L412) ``` fun box ipv6_rthdr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_rthdrdstopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L413) ``` fun box ipv6_rthdrdstopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_tclass [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L414) ``` fun box ipv6_tclass() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_tlv\_hao [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L415) ``` fun box ipv6_tlv_hao() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_tlv\_jumbo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L416) ``` fun box ipv6_tlv_jumbo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_tlv\_pad1 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L417) ``` fun box ipv6_tlv_pad1() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_tlv\_padn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L418) ``` fun box ipv6_tlv_padn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_tlv\_routeralert [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L419) ``` fun box ipv6_tlv_routeralert() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_transparent [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L420) ``` fun box ipv6_transparent() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_unicast\_hops [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L421) ``` fun box ipv6_unicast_hops() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_unicast\_if [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L422) ``` fun box ipv6_unicast_if() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_use\_min\_mtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L423) ``` fun box ipv6_use_min_mtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_v6only [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L424) ``` fun box ipv6_v6only() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipv6\_xfrm\_policy [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L425) ``` fun box ipv6_xfrm_policy() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_address [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L426) ``` fun box ipx_address() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_address\_notify [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L427) ``` fun box ipx_address_notify() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_crtitf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L428) ``` fun box ipx_crtitf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_dltitf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L429) ``` fun box ipx_dltitf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_dstype [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L430) ``` fun box ipx_dstype() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_extended\_address [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L431) ``` fun box ipx_extended_address() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_filterptype [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L432) ``` fun box ipx_filterptype() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_frame\_8022 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L433) ``` fun box ipx_frame_8022() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_frame\_8023 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L434) ``` fun box ipx_frame_8023() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_frame\_etherii [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L435) ``` fun box ipx_frame_etherii() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_frame\_none [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L436) ``` fun box ipx_frame_none() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_frame\_snap [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L437) ``` fun box ipx_frame_snap() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_frame\_tr\_8022 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L438) ``` fun box ipx_frame_tr_8022() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_getnetinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L439) ``` fun box ipx_getnetinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_getnetinfo\_norip [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L440) ``` fun box ipx_getnetinfo_norip() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_immediatespxack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L441) ``` fun box ipx_immediatespxack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_internal [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L442) ``` fun box ipx_internal() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_maxsize [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L443) ``` fun box ipx_maxsize() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_max\_adapter\_num [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L444) ``` fun box ipx_max_adapter_num() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_mtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L445) ``` fun box ipx_mtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_node\_len [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L446) ``` fun box ipx_node_len() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_primary [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L447) ``` fun box ipx_primary() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_ptype [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L448) ``` fun box ipx_ptype() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_receive\_broadcast [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L449) ``` fun box ipx_receive_broadcast() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_recvhdr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L450) ``` fun box ipx_recvhdr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_reripnetnumber [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L451) ``` fun box ipx_reripnetnumber() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_route\_no\_router [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L452) ``` fun box ipx_route_no_router() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_rt\_8022 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L453) ``` fun box ipx_rt_8022() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_rt\_bluebook [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L454) ``` fun box ipx_rt_bluebook() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_rt\_routed [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L455) ``` fun box ipx_rt_routed() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_rt\_snap [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L456) ``` fun box ipx_rt_snap() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_special\_none [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L457) ``` fun box ipx_special_none() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_spxgetconnectionstatus [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L458) ``` fun box ipx_spxgetconnectionstatus() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_stopfilterptype [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L459) ``` fun box ipx_stopfilterptype() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ipx\_type [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L460) ``` fun box ipx_type() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_add\_membership [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L461) ``` fun box ip_add_membership() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_add\_source\_membership [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L462) ``` fun box ip_add_source_membership() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_bindany [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L463) ``` fun box ip_bindany() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_bindmulti [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L464) ``` fun box ip_bindmulti() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_bind\_address\_no\_port [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L465) ``` fun box ip_bind_address_no_port() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_block\_source [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L466) ``` fun box ip_block_source() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_bound\_if [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L467) ``` fun box ip_bound_if() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_checksum [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L468) ``` fun box ip_checksum() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_default\_multicast\_loop [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L469) ``` fun box ip_default_multicast_loop() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_default\_multicast\_ttl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L470) ``` fun box ip_default_multicast_ttl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_dontfrag [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L471) ``` fun box ip_dontfrag() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_drop\_membership [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L472) ``` fun box ip_drop_membership() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_drop\_source\_membership [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L473) ``` fun box ip_drop_source_membership() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_dummynet3 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L474) ``` fun box ip_dummynet3() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_dummynet\_configure [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L475) ``` fun box ip_dummynet_configure() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_dummynet\_del [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L476) ``` fun box ip_dummynet_del() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_dummynet\_flush [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L477) ``` fun box ip_dummynet_flush() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_dummynet\_get [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L478) ``` fun box ip_dummynet_get() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_faith [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L479) ``` fun box ip_faith() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_flowid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L480) ``` fun box ip_flowid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_flowtype [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L481) ``` fun box ip_flowtype() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_freebind [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L482) ``` fun box ip_freebind() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw3 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L483) ``` fun box ip_fw3() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_add [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L484) ``` fun box ip_fw_add() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_del [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L485) ``` fun box ip_fw_del() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_flush [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L486) ``` fun box ip_fw_flush() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_get [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L487) ``` fun box ip_fw_get() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_nat\_cfg [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L488) ``` fun box ip_fw_nat_cfg() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_nat\_del [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L489) ``` fun box ip_fw_nat_del() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_nat\_get\_config [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L490) ``` fun box ip_fw_nat_get_config() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_nat\_get\_log [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L491) ``` fun box ip_fw_nat_get_log() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_resetlog [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L492) ``` fun box ip_fw_resetlog() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_table\_add [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L493) ``` fun box ip_fw_table_add() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_table\_del [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L494) ``` fun box ip_fw_table_del() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_table\_flush [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L495) ``` fun box ip_fw_table_flush() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_table\_getsize [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L496) ``` fun box ip_fw_table_getsize() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_table\_list [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L497) ``` fun box ip_fw_table_list() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_fw\_zero [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L498) ``` fun box ip_fw_zero() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_hdrincl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L499) ``` fun box ip_hdrincl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_ipsec\_policy [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L500) ``` fun box ip_ipsec_policy() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_max\_group\_src\_filter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L501) ``` fun box ip_max_group_src_filter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_max\_memberships [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L502) ``` fun box ip_max_memberships() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_max\_sock\_mute\_filter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L503) ``` fun box ip_max_sock_mute_filter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_max\_sock\_src\_filter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L504) ``` fun box ip_max_sock_src_filter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_max\_source\_filter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L505) ``` fun box ip_max_source_filter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_minttl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L506) ``` fun box ip_minttl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_min\_memberships [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L507) ``` fun box ip_min_memberships() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_msfilter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L508) ``` fun box ip_msfilter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_mtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L509) ``` fun box ip_mtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_mtu\_discover [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L510) ``` fun box ip_mtu_discover() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_multicast\_all [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L511) ``` fun box ip_multicast_all() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_multicast\_if [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L512) ``` fun box ip_multicast_if() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_multicast\_ifindex [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L513) ``` fun box ip_multicast_ifindex() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_multicast\_loop [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L514) ``` fun box ip_multicast_loop() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_multicast\_ttl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L515) ``` fun box ip_multicast_ttl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_multicast\_vif [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L516) ``` fun box ip_multicast_vif() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_nat\_xxx [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L517) ``` fun box ip_nat_xxx() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_nodefrag [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L518) ``` fun box ip_nodefrag() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_old\_fw\_add [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L519) ``` fun box ip_old_fw_add() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_old\_fw\_del [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L520) ``` fun box ip_old_fw_del() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_old\_fw\_flush [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L521) ``` fun box ip_old_fw_flush() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_old\_fw\_get [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L522) ``` fun box ip_old_fw_get() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_old\_fw\_resetlog [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L523) ``` fun box ip_old_fw_resetlog() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_old\_fw\_zero [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L524) ``` fun box ip_old_fw_zero() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_onesbcast [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L525) ``` fun box ip_onesbcast() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_options [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L526) ``` fun box ip_options() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_origdstaddr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L527) ``` fun box ip_origdstaddr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_passsec [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L528) ``` fun box ip_passsec() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_pktinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L529) ``` fun box ip_pktinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_pktoptions [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L530) ``` fun box ip_pktoptions() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_pmtudisc\_do [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L531) ``` fun box ip_pmtudisc_do() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_pmtudisc\_dont [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L532) ``` fun box ip_pmtudisc_dont() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_pmtudisc\_interface [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L533) ``` fun box ip_pmtudisc_interface() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_pmtudisc\_omit [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L534) ``` fun box ip_pmtudisc_omit() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_pmtudisc\_probe [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L535) ``` fun box ip_pmtudisc_probe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_pmtudisc\_want [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L536) ``` fun box ip_pmtudisc_want() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_portrange [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L537) ``` fun box ip_portrange() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_portrange\_default [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L538) ``` fun box ip_portrange_default() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_portrange\_high [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L539) ``` fun box ip_portrange_high() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_portrange\_low [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L540) ``` fun box ip_portrange_low() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_recvdstaddr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L541) ``` fun box ip_recvdstaddr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_recverr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L542) ``` fun box ip_recverr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_recvflowid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L543) ``` fun box ip_recvflowid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_recvif [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L544) ``` fun box ip_recvif() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_recvopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L545) ``` fun box ip_recvopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_recvorigdstaddr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L546) ``` fun box ip_recvorigdstaddr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_recvpktinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L547) ``` fun box ip_recvpktinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_recvretopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L548) ``` fun box ip_recvretopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_recvrssbucketid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L549) ``` fun box ip_recvrssbucketid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_recvtos [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L550) ``` fun box ip_recvtos() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_recvttl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L551) ``` fun box ip_recvttl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_retopts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L552) ``` fun box ip_retopts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_router\_alert [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L553) ``` fun box ip_router_alert() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_rssbucketid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L554) ``` fun box ip_rssbucketid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_rss\_listen\_bucket [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L555) ``` fun box ip_rss_listen_bucket() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_rsvp\_off [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L556) ``` fun box ip_rsvp_off() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_rsvp\_on [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L557) ``` fun box ip_rsvp_on() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_rsvp\_vif\_off [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L558) ``` fun box ip_rsvp_vif_off() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_rsvp\_vif\_on [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L559) ``` fun box ip_rsvp_vif_on() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_sendsrcaddr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L560) ``` fun box ip_sendsrcaddr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_striphdr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L561) ``` fun box ip_striphdr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_tos [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L562) ``` fun box ip_tos() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_traffic\_mgt\_background [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L563) ``` fun box ip_traffic_mgt_background() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_transparent [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L564) ``` fun box ip_transparent() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_ttl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L565) ``` fun box ip_ttl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_unblock\_source [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L566) ``` fun box ip_unblock_source() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_unicast\_if [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L567) ``` fun box ip_unicast_if() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ip\_xfrm\_policy [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L568) ``` fun box ip_xfrm_policy() : I32 val ``` #### Returns * [I32](builtin-i32) val ### local\_connwait [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L569) ``` fun box local_connwait() : I32 val ``` #### Returns * [I32](builtin-i32) val ### local\_creds [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L570) ``` fun box local_creds() : I32 val ``` #### Returns * [I32](builtin-i32) val ### local\_peercred [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L571) ``` fun box local_peercred() : I32 val ``` #### Returns * [I32](builtin-i32) val ### local\_peerepid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L572) ``` fun box local_peerepid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### local\_peereuuid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L573) ``` fun box local_peereuuid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### local\_peerpid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L574) ``` fun box local_peerpid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### local\_peeruuid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L575) ``` fun box local_peeruuid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### local\_vendor [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L576) ``` fun box local_vendor() : I32 val ``` #### Returns * [I32](builtin-i32) val ### max\_tcpoptlen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L577) ``` fun box max_tcpoptlen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mcast\_block\_source [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L578) ``` fun box mcast_block_source() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mcast\_exclude [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L579) ``` fun box mcast_exclude() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mcast\_include [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L580) ``` fun box mcast_include() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mcast\_join\_group [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L581) ``` fun box mcast_join_group() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mcast\_join\_source\_group [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L582) ``` fun box mcast_join_source_group() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mcast\_leave\_group [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L583) ``` fun box mcast_leave_group() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mcast\_leave\_source\_group [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L584) ``` fun box mcast_leave_source_group() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mcast\_msfilter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L585) ``` fun box mcast_msfilter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mcast\_unblock\_source [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L586) ``` fun box mcast_unblock_source() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mcast\_undefined [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L587) ``` fun box mcast_undefined() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_add\_bw\_upcall [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L588) ``` fun box mrt_add_bw_upcall() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_add\_mfc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L589) ``` fun box mrt_add_mfc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_add\_vif [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L590) ``` fun box mrt_add_vif() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_api\_config [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L591) ``` fun box mrt_api_config() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_api\_flags\_all [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L592) ``` fun box mrt_api_flags_all() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_api\_support [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L593) ``` fun box mrt_api_support() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_assert [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L594) ``` fun box mrt_assert() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_del\_bw\_upcall [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L595) ``` fun box mrt_del_bw_upcall() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_del\_mfc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L596) ``` fun box mrt_del_mfc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_del\_vif [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L597) ``` fun box mrt_del_vif() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_done [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L598) ``` fun box mrt_done() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_init [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L599) ``` fun box mrt_init() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_mfc\_bw\_upcall [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L600) ``` fun box mrt_mfc_bw_upcall() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_mfc\_flags\_all [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L601) ``` fun box mrt_mfc_flags_all() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_mfc\_flags\_border\_vif [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L602) ``` fun box mrt_mfc_flags_border_vif() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_mfc\_flags\_disable\_wrongvif [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L603) ``` fun box mrt_mfc_flags_disable_wrongvif() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_mfc\_rp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L604) ``` fun box mrt_mfc_rp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_pim [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L605) ``` fun box mrt_pim() : I32 val ``` #### Returns * [I32](builtin-i32) val ### mrt\_version [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L606) ``` fun box mrt_version() : I32 val ``` #### Returns * [I32](builtin-i32) val ### msg\_notification [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L607) ``` fun box msg_notification() : I32 val ``` #### Returns * [I32](builtin-i32) val ### msg\_socallbck [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L608) ``` fun box msg_socallbck() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ndrvproto\_ndrv [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L609) ``` fun box ndrvproto_ndrv() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ndrv\_addmulticast [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L610) ``` fun box ndrv_addmulticast() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ndrv\_deldmxspec [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L611) ``` fun box ndrv_deldmxspec() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ndrv\_delmulticast [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L612) ``` fun box ndrv_delmulticast() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ndrv\_demuxtype\_ethertype [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L613) ``` fun box ndrv_demuxtype_ethertype() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ndrv\_demuxtype\_sap [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L614) ``` fun box ndrv_demuxtype_sap() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ndrv\_demuxtype\_snap [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L615) ``` fun box ndrv_demuxtype_snap() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ndrv\_dmux\_max\_descr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L616) ``` fun box ndrv_dmux_max_descr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ndrv\_protocol\_desc\_vers [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L617) ``` fun box ndrv_protocol_desc_vers() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ndrv\_setdmxspec [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L618) ``` fun box ndrv_setdmxspec() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_add\_membership [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L619) ``` fun box netlink_add_membership() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_audit [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L620) ``` fun box netlink_audit() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_broadcast\_error [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L621) ``` fun box netlink_broadcast_error() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_cap\_ack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L622) ``` fun box netlink_cap_ack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_connector [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L623) ``` fun box netlink_connector() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_crypto [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L624) ``` fun box netlink_crypto() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_dnrtmsg [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L625) ``` fun box netlink_dnrtmsg() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_drop\_membership [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L626) ``` fun box netlink_drop_membership() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_ecryptfs [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L627) ``` fun box netlink_ecryptfs() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_fib\_lookup [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L628) ``` fun box netlink_fib_lookup() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_firewall [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L629) ``` fun box netlink_firewall() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_generic [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L630) ``` fun box netlink_generic() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_inet\_diag [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L631) ``` fun box netlink_inet_diag() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_ip6\_fw [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L632) ``` fun box netlink_ip6_fw() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_iscsi [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L633) ``` fun box netlink_iscsi() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_kobject\_uevent [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L634) ``` fun box netlink_kobject_uevent() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_listen\_all\_nsid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L635) ``` fun box netlink_listen_all_nsid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_list\_memberships [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L636) ``` fun box netlink_list_memberships() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_netfilter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L637) ``` fun box netlink_netfilter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_nflog [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L638) ``` fun box netlink_nflog() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_no\_enobufs [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L639) ``` fun box netlink_no_enobufs() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_pktinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L640) ``` fun box netlink_pktinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_rdma [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L641) ``` fun box netlink_rdma() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_route [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L642) ``` fun box netlink_route() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_rx\_ring [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L643) ``` fun box netlink_rx_ring() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_scsitransport [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L644) ``` fun box netlink_scsitransport() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_selinux [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L645) ``` fun box netlink_selinux() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_sock\_diag [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L646) ``` fun box netlink_sock_diag() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_tx\_ring [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L647) ``` fun box netlink_tx_ring() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_unused [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L648) ``` fun box netlink_unused() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_usersock [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L649) ``` fun box netlink_usersock() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netlink\_xfrm [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L650) ``` fun box netlink_xfrm() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netrom\_idle [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L651) ``` fun box netrom_idle() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netrom\_kill [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L652) ``` fun box netrom_kill() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netrom\_n2 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L653) ``` fun box netrom_n2() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netrom\_neigh [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L654) ``` fun box netrom_neigh() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netrom\_node [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L655) ``` fun box netrom_node() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netrom\_paclen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L656) ``` fun box netrom_paclen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netrom\_t1 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L657) ``` fun box netrom_t1() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netrom\_t2 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L658) ``` fun box netrom_t2() : I32 val ``` #### Returns * [I32](builtin-i32) val ### netrom\_t4 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L659) ``` fun box netrom_t4() : I32 val ``` #### Returns * [I32](builtin-i32) val ### nrdv\_multicast\_addrs\_per\_sock [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L660) ``` fun box nrdv_multicast_addrs_per_sock() : I32 val ``` #### Returns * [I32](builtin-i32) val ### pvd\_config [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L661) ``` fun box pvd_config() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cancel\_sent\_to [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L662) ``` fun box rds_cancel_sent_to() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cmsg\_atomic\_cswp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L663) ``` fun box rds_cmsg_atomic_cswp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cmsg\_atomic\_fadd [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L664) ``` fun box rds_cmsg_atomic_fadd() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cmsg\_cong\_update [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L665) ``` fun box rds_cmsg_cong_update() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cmsg\_masked\_atomic\_cswp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L666) ``` fun box rds_cmsg_masked_atomic_cswp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cmsg\_masked\_atomic\_fadd [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L667) ``` fun box rds_cmsg_masked_atomic_fadd() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cmsg\_rdma\_args [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L668) ``` fun box rds_cmsg_rdma_args() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cmsg\_rdma\_dest [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L669) ``` fun box rds_cmsg_rdma_dest() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cmsg\_rdma\_map [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L670) ``` fun box rds_cmsg_rdma_map() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cmsg\_rdma\_status [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L671) ``` fun box rds_cmsg_rdma_status() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cong\_monitor [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L672) ``` fun box rds_cong_monitor() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_cong\_monitor\_size [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L673) ``` fun box rds_cong_monitor_size() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_free\_mr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L674) ``` fun box rds_free_mr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_get\_mr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L675) ``` fun box rds_get_mr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_get\_mr\_for\_dest [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L676) ``` fun box rds_get_mr_for_dest() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_ib\_abi\_version [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L677) ``` fun box rds_ib_abi_version() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_ib\_gid\_len [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L678) ``` fun box rds_ib_gid_len() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_connections [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L679) ``` fun box rds_info_connections() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_connection\_flag\_connected [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L680) ``` fun box rds_info_connection_flag_connected() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_connection\_flag\_connecting [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L681) ``` fun box rds_info_connection_flag_connecting() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_connection\_flag\_sending [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L682) ``` fun box rds_info_connection_flag_sending() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_connection\_stats [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L683) ``` fun box rds_info_connection_stats() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_counters [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L684) ``` fun box rds_info_counters() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_first [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L685) ``` fun box rds_info_first() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_ib\_connections [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L686) ``` fun box rds_info_ib_connections() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_iwarp\_connections [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L687) ``` fun box rds_info_iwarp_connections() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_last [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L688) ``` fun box rds_info_last() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_message\_flag\_ack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L689) ``` fun box rds_info_message_flag_ack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_message\_flag\_fast\_ack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L690) ``` fun box rds_info_message_flag_fast_ack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_recv\_messages [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L691) ``` fun box rds_info_recv_messages() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_retrans\_messages [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L692) ``` fun box rds_info_retrans_messages() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_send\_messages [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L693) ``` fun box rds_info_send_messages() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_sockets [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L694) ``` fun box rds_info_sockets() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_info\_tcp\_sockets [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L695) ``` fun box rds_info_tcp_sockets() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_canceled [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L696) ``` fun box rds_rdma_canceled() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_dontwait [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L697) ``` fun box rds_rdma_dontwait() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_dropped [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L698) ``` fun box rds_rdma_dropped() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_fence [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L699) ``` fun box rds_rdma_fence() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_invalidate [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L700) ``` fun box rds_rdma_invalidate() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_notify\_me [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L701) ``` fun box rds_rdma_notify_me() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_other\_error [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L702) ``` fun box rds_rdma_other_error() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_readwrite [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L703) ``` fun box rds_rdma_readwrite() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_remote\_error [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L704) ``` fun box rds_rdma_remote_error() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_silent [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L705) ``` fun box rds_rdma_silent() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_success [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L706) ``` fun box rds_rdma_success() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_rdma\_use\_once [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L707) ``` fun box rds_rdma_use_once() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_recverr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L708) ``` fun box rds_recverr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_trans\_count [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L709) ``` fun box rds_trans_count() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_trans\_ib [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L710) ``` fun box rds_trans_ib() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_trans\_iwarp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L711) ``` fun box rds_trans_iwarp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_trans\_none [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L712) ``` fun box rds_trans_none() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rds\_trans\_tcp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L713) ``` fun box rds_trans_tcp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_access\_barred [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L714) ``` fun box rose_access_barred() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_defer [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L715) ``` fun box rose_defer() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_dte\_originated [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L716) ``` fun box rose_dte_originated() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_holdback [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L717) ``` fun box rose_holdback() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_idle [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L718) ``` fun box rose_idle() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_invalid\_facility [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L719) ``` fun box rose_invalid_facility() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_local\_procedure [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L720) ``` fun box rose_local_procedure() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_max\_digis [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L721) ``` fun box rose_max_digis() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_mtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L722) ``` fun box rose_mtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_network\_congestion [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L723) ``` fun box rose_network_congestion() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_not\_obtainable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L724) ``` fun box rose_not_obtainable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_number\_busy [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L725) ``` fun box rose_number_busy() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_out\_of\_order [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L726) ``` fun box rose_out_of_order() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_qbitincl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L727) ``` fun box rose_qbitincl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_remote\_procedure [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L728) ``` fun box rose_remote_procedure() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_ship\_absent [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L729) ``` fun box rose_ship_absent() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_t1 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L730) ``` fun box rose_t1() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_t2 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L731) ``` fun box rose_t2() : I32 val ``` #### Returns * [I32](builtin-i32) val ### rose\_t3 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L732) ``` fun box rose_t3() : I32 val ``` #### Returns * [I32](builtin-i32) val ### scm\_hci\_raw\_direction [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L733) ``` fun box scm_hci_raw_direction() : I32 val ``` #### Returns * [I32](builtin-i32) val ### scm\_timestamp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L734) ``` fun box scm_timestamp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### scm\_timestamping [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L735) ``` fun box scm_timestamping() : I32 val ``` #### Returns * [I32](builtin-i32) val ### scm\_timestampns [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L736) ``` fun box scm_timestampns() : I32 val ``` #### Returns * [I32](builtin-i32) val ### scm\_wifi\_status [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L737) ``` fun box scm_wifi_status() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_abort\_association [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L738) ``` fun box sctp_abort_association() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_adaptation\_layer [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L739) ``` fun box sctp_adaptation_layer() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_adaption\_layer [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L740) ``` fun box sctp_adaption_layer() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_add\_streams [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L741) ``` fun box sctp_add_streams() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_add\_vrf\_id [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L742) ``` fun box sctp_add_vrf_id() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_asconf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L743) ``` fun box sctp_asconf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_asconf\_ack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L744) ``` fun box sctp_asconf_ack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_asconf\_supported [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L745) ``` fun box sctp_asconf_supported() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_associnfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L746) ``` fun box sctp_associnfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_authentication [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L747) ``` fun box sctp_authentication() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_auth\_active\_key [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L748) ``` fun box sctp_auth_active_key() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_auth\_chunk [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L749) ``` fun box sctp_auth_chunk() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_auth\_deactivate\_key [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L750) ``` fun box sctp_auth_deactivate_key() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_auth\_delete\_key [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L751) ``` fun box sctp_auth_delete_key() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_auth\_key [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L752) ``` fun box sctp_auth_key() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_auth\_supported [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L753) ``` fun box sctp_auth_supported() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_autoclose [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L754) ``` fun box sctp_autoclose() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_auto\_asconf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L755) ``` fun box sctp_auto_asconf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_badcrc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L756) ``` fun box sctp_badcrc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_bindx\_add\_addr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L757) ``` fun box sctp_bindx_add_addr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_bindx\_rem\_addr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L758) ``` fun box sctp_bindx_rem_addr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_blk\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L759) ``` fun box sctp_blk_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_bound [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L760) ``` fun box sctp_bound() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_cookie\_in\_shutdown [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L761) ``` fun box sctp_cause_cookie_in_shutdown() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_deleting\_last\_addr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L762) ``` fun box sctp_cause_deleting_last_addr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_deleting\_src\_addr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L763) ``` fun box sctp_cause_deleting_src_addr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_illegal\_asconf\_ack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L764) ``` fun box sctp_cause_illegal_asconf_ack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_invalid\_param [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L765) ``` fun box sctp_cause_invalid_param() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_invalid\_stream [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L766) ``` fun box sctp_cause_invalid_stream() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_missing\_param [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L767) ``` fun box sctp_cause_missing_param() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_nat\_colliding\_state [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L768) ``` fun box sctp_cause_nat_colliding_state() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_nat\_missing\_state [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L769) ``` fun box sctp_cause_nat_missing_state() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_no\_error [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L770) ``` fun box sctp_cause_no_error() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_no\_user\_data [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L771) ``` fun box sctp_cause_no_user_data() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_out\_of\_resc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L772) ``` fun box sctp_cause_out_of_resc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_protocol\_violation [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L773) ``` fun box sctp_cause_protocol_violation() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_request\_refused [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L774) ``` fun box sctp_cause_request_refused() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_resource\_shortage [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L775) ``` fun box sctp_cause_resource_shortage() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_restart\_w\_newaddr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L776) ``` fun box sctp_cause_restart_w_newaddr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_stale\_cookie [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L777) ``` fun box sctp_cause_stale_cookie() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_unrecog\_chunk [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L778) ``` fun box sctp_cause_unrecog_chunk() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_unrecog\_param [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L779) ``` fun box sctp_cause_unrecog_param() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_unresolvable\_addr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L780) ``` fun box sctp_cause_unresolvable_addr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_unsupported\_hmacid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L781) ``` fun box sctp_cause_unsupported_hmacid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cause\_user\_initiated\_abt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L782) ``` fun box sctp_cause_user_initiated_abt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cc\_hstcp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L783) ``` fun box sctp_cc_hstcp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cc\_htcp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L784) ``` fun box sctp_cc_htcp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cc\_option [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L785) ``` fun box sctp_cc_option() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cc\_opt\_rtcc\_setmode [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L786) ``` fun box sctp_cc_opt_rtcc_setmode() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cc\_opt\_steady\_step [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L787) ``` fun box sctp_cc_opt_steady_step() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cc\_opt\_use\_dccc\_ecn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L788) ``` fun box sctp_cc_opt_use_dccc_ecn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cc\_rfc2581 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L789) ``` fun box sctp_cc_rfc2581() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cc\_rtcc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L790) ``` fun box sctp_cc_rtcc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_closed [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L791) ``` fun box sctp_closed() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_clr\_stat\_log [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L792) ``` fun box sctp_clr_stat_log() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cmt\_base [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L793) ``` fun box sctp_cmt_base() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cmt\_max [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L794) ``` fun box sctp_cmt_max() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cmt\_mptcp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L795) ``` fun box sctp_cmt_mptcp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cmt\_off [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L796) ``` fun box sctp_cmt_off() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cmt\_on\_off [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L797) ``` fun box sctp_cmt_on_off() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cmt\_rpv1 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L798) ``` fun box sctp_cmt_rpv1() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cmt\_rpv2 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L799) ``` fun box sctp_cmt_rpv2() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cmt\_use\_dac [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L800) ``` fun box sctp_cmt_use_dac() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_connect\_x [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L801) ``` fun box sctp_connect_x() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_connect\_x\_complete [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L802) ``` fun box sctp_connect_x_complete() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_connect\_x\_delayed [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L803) ``` fun box sctp_connect_x_delayed() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_context [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L804) ``` fun box sctp_context() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cookie\_ack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L805) ``` fun box sctp_cookie_ack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cookie\_echo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L806) ``` fun box sctp_cookie_echo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cookie\_echoed [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L807) ``` fun box sctp_cookie_echoed() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cookie\_wait [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L808) ``` fun box sctp_cookie_wait() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cwnd\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L809) ``` fun box sctp_cwnd_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cwnd\_monitor\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L810) ``` fun box sctp_cwnd_monitor_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cwr\_in\_same\_window [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L811) ``` fun box sctp_cwr_in_same_window() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_cwr\_reduce\_override [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L812) ``` fun box sctp_cwr_reduce_override() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_data [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L813) ``` fun box sctp_data() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_data\_first\_frag [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L814) ``` fun box sctp_data_first_frag() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_data\_frag\_mask [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L815) ``` fun box sctp_data_frag_mask() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_data\_last\_frag [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L816) ``` fun box sctp_data_last_frag() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_data\_middle\_frag [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L817) ``` fun box sctp_data_middle_frag() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_data\_not\_frag [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L818) ``` fun box sctp_data_not_frag() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_data\_sack\_immediately [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L819) ``` fun box sctp_data_sack_immediately() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_data\_unordered [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L820) ``` fun box sctp_data_unordered() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_default\_prinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L821) ``` fun box sctp_default_prinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_default\_send\_param [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L822) ``` fun box sctp_default_send_param() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_default\_sndinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L823) ``` fun box sctp_default_sndinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_delayed\_sack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L824) ``` fun box sctp_delayed_sack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_del\_vrf\_id [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L825) ``` fun box sctp_del_vrf_id() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_disable\_fragments [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L826) ``` fun box sctp_disable_fragments() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ecn\_cwr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L827) ``` fun box sctp_ecn_cwr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ecn\_echo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L828) ``` fun box sctp_ecn_echo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ecn\_supported [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L829) ``` fun box sctp_ecn_supported() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_enable\_change\_assoc\_req [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L830) ``` fun box sctp_enable_change_assoc_req() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_enable\_reset\_assoc\_req [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L831) ``` fun box sctp_enable_reset_assoc_req() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_enable\_reset\_stream\_req [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L832) ``` fun box sctp_enable_reset_stream_req() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_enable\_stream\_reset [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L833) ``` fun box sctp_enable_stream_reset() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_enable\_value\_mask [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L834) ``` fun box sctp_enable_value_mask() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_established [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L835) ``` fun box sctp_established() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_event [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L836) ``` fun box sctp_event() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_events [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L837) ``` fun box sctp_events() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_explicit\_eor [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L838) ``` fun box sctp_explicit_eor() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_flight\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L839) ``` fun box sctp_flight_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_forward\_cum\_tsn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L840) ``` fun box sctp_forward_cum_tsn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_fragment\_interleave [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L841) ``` fun box sctp_fragment_interleave() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_frag\_level\_0 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L842) ``` fun box sctp_frag_level_0() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_frag\_level\_1 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L843) ``` fun box sctp_frag_level_1() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_frag\_level\_2 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L844) ``` fun box sctp_frag_level_2() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_from\_middle\_box [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L845) ``` fun box sctp_from_middle_box() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_fr\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L846) ``` fun box sctp_fr_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_addr\_len [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L847) ``` fun box sctp_get_addr_len() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_asoc\_vrf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L848) ``` fun box sctp_get_asoc_vrf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_assoc\_id\_list [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L849) ``` fun box sctp_get_assoc_id_list() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_assoc\_number [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L850) ``` fun box sctp_get_assoc_number() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_local\_addresses [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L851) ``` fun box sctp_get_local_addresses() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_local\_addr\_size [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L852) ``` fun box sctp_get_local_addr_size() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_nonce\_values [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L853) ``` fun box sctp_get_nonce_values() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_packet\_log [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L854) ``` fun box sctp_get_packet_log() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_peer\_addresses [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L855) ``` fun box sctp_get_peer_addresses() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_peer\_addr\_info [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L856) ``` fun box sctp_get_peer_addr_info() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_remote\_addr\_size [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L857) ``` fun box sctp_get_remote_addr_size() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_sndbuf\_use [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L858) ``` fun box sctp_get_sndbuf_use() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_stat\_log [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L859) ``` fun box sctp_get_stat_log() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_get\_vrf\_ids [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L860) ``` fun box sctp_get_vrf_ids() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_had\_no\_tcb [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L861) ``` fun box sctp_had_no_tcb() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_heartbeat\_ack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L862) ``` fun box sctp_heartbeat_ack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_heartbeat\_request [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L863) ``` fun box sctp_heartbeat_request() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_hmac\_ident [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L864) ``` fun box sctp_hmac_ident() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_idata [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L865) ``` fun box sctp_idata() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_iforward\_cum\_tsn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L866) ``` fun box sctp_iforward_cum_tsn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_initiation [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L867) ``` fun box sctp_initiation() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_initiation\_ack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L868) ``` fun box sctp_initiation_ack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_initmsg [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L869) ``` fun box sctp_initmsg() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_interleaving\_supported [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L870) ``` fun box sctp_interleaving_supported() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_i\_want\_mapped\_v4\_addr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L871) ``` fun box sctp_i_want_mapped_v4_addr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_last\_packet\_tracing [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L872) ``` fun box sctp_last_packet_tracing() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_listen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L873) ``` fun box sctp_listen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_local\_auth\_chunks [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L874) ``` fun box sctp_local_auth_chunks() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_lock\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L875) ``` fun box sctp_lock_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_log\_at\_send\_2\_outq [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L876) ``` fun box sctp_log_at_send_2_outq() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_log\_at\_send\_2\_sctp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L877) ``` fun box sctp_log_at_send_2_sctp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_log\_maxburst\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L878) ``` fun box sctp_log_maxburst_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_log\_rwnd\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L879) ``` fun box sctp_log_rwnd_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_log\_sack\_arrivals\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L880) ``` fun box sctp_log_sack_arrivals_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_log\_try\_advance [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L881) ``` fun box sctp_log_try_advance() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ltrace\_chunk\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L882) ``` fun box sctp_ltrace_chunk_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ltrace\_error\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L883) ``` fun box sctp_ltrace_error_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_map\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L884) ``` fun box sctp_map_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_maxburst [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L885) ``` fun box sctp_maxburst() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_maxseg [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L886) ``` fun box sctp_maxseg() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_max\_burst [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L887) ``` fun box sctp_max_burst() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_max\_cookie\_life [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L888) ``` fun box sctp_max_cookie_life() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_max\_cwnd [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L889) ``` fun box sctp_max_cwnd() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_max\_hb\_interval [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L890) ``` fun box sctp_max_hb_interval() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_max\_sack\_delay [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L891) ``` fun box sctp_max_sack_delay() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_mbcnt\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L892) ``` fun box sctp_mbcnt_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_mbuf\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L893) ``` fun box sctp_mbuf_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_mobility\_base [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L894) ``` fun box sctp_mobility_base() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_mobility\_fasthandoff [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L895) ``` fun box sctp_mobility_fasthandoff() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_mobility\_prim\_deleted [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L896) ``` fun box sctp_mobility_prim_deleted() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_nagle\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L897) ``` fun box sctp_nagle_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_nodelay [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L898) ``` fun box sctp_nodelay() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_nrsack\_supported [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L899) ``` fun box sctp_nrsack_supported() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_nr\_selective\_ack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L900) ``` fun box sctp_nr_selective_ack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_operation\_error [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L901) ``` fun box sctp_operation_error() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_packed [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L902) ``` fun box sctp_packed() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_packet\_dropped [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L903) ``` fun box sctp_packet_dropped() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_packet\_log\_size [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L904) ``` fun box sctp_packet_log_size() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_packet\_truncated [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L905) ``` fun box sctp_packet_truncated() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pad\_chunk [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L906) ``` fun box sctp_pad_chunk() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_partial\_delivery\_point [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L907) ``` fun box sctp_partial_delivery_point() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_copy\_flags [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L908) ``` fun box sctp_pcb_copy_flags() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_accepting [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L909) ``` fun box sctp_pcb_flags_accepting() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_adaptationevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L910) ``` fun box sctp_pcb_flags_adaptationevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_assoc\_resetevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L911) ``` fun box sctp_pcb_flags_assoc_resetevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_authevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L912) ``` fun box sctp_pcb_flags_authevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_autoclose [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L913) ``` fun box sctp_pcb_flags_autoclose() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_auto\_asconf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L914) ``` fun box sctp_pcb_flags_auto_asconf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_blocking\_io [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L915) ``` fun box sctp_pcb_flags_blocking_io() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_boundall [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L916) ``` fun box sctp_pcb_flags_boundall() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_bound\_v6 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L917) ``` fun box sctp_pcb_flags_bound_v6() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_close\_ip [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L918) ``` fun box sctp_pcb_flags_close_ip() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_connected [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L919) ``` fun box sctp_pcb_flags_connected() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_donot\_heartbeat [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L920) ``` fun box sctp_pcb_flags_donot_heartbeat() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_dont\_wake [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L921) ``` fun box sctp_pcb_flags_dont_wake() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_do\_asconf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L922) ``` fun box sctp_pcb_flags_do_asconf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_do\_not\_pmtud [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L923) ``` fun box sctp_pcb_flags_do_not_pmtud() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_dryevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L924) ``` fun box sctp_pcb_flags_dryevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_explicit\_eor [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L925) ``` fun box sctp_pcb_flags_explicit_eor() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_ext\_rcvinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L926) ``` fun box sctp_pcb_flags_ext_rcvinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_frag\_interleave [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L927) ``` fun box sctp_pcb_flags_frag_interleave() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_interleave\_strms [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L928) ``` fun box sctp_pcb_flags_interleave_strms() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_in\_tcppool [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L929) ``` fun box sctp_pcb_flags_in_tcppool() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_multiple\_asconfs [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L930) ``` fun box sctp_pcb_flags_multiple_asconfs() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_needs\_mapped\_v4 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L931) ``` fun box sctp_pcb_flags_needs_mapped_v4() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_nodelay [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L932) ``` fun box sctp_pcb_flags_nodelay() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_no\_fragment [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L933) ``` fun box sctp_pcb_flags_no_fragment() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_pdapievnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L934) ``` fun box sctp_pcb_flags_pdapievnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_portreuse [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L935) ``` fun box sctp_pcb_flags_portreuse() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_recvassocevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L936) ``` fun box sctp_pcb_flags_recvassocevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_recvdataioevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L937) ``` fun box sctp_pcb_flags_recvdataioevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_recvnsendfailevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L938) ``` fun box sctp_pcb_flags_recvnsendfailevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_recvnxtinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L939) ``` fun box sctp_pcb_flags_recvnxtinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_recvpaddrevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L940) ``` fun box sctp_pcb_flags_recvpaddrevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_recvpeererr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L941) ``` fun box sctp_pcb_flags_recvpeererr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_recvrcvinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L942) ``` fun box sctp_pcb_flags_recvrcvinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_recvsendfailevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L943) ``` fun box sctp_pcb_flags_recvsendfailevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_recvshutdownevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L944) ``` fun box sctp_pcb_flags_recvshutdownevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_socket\_allgone [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L945) ``` fun box sctp_pcb_flags_socket_allgone() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_socket\_cant\_read [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L946) ``` fun box sctp_pcb_flags_socket_cant_read() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_socket\_gone [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L947) ``` fun box sctp_pcb_flags_socket_gone() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_stream\_changeevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L948) ``` fun box sctp_pcb_flags_stream_changeevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_stream\_resetevnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L949) ``` fun box sctp_pcb_flags_stream_resetevnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_tcptype [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L950) ``` fun box sctp_pcb_flags_tcptype() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_udptype [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L951) ``` fun box sctp_pcb_flags_udptype() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_unbound [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L952) ``` fun box sctp_pcb_flags_unbound() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_wakeinput [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L953) ``` fun box sctp_pcb_flags_wakeinput() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_wakeoutput [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L954) ``` fun box sctp_pcb_flags_wakeoutput() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_was\_aborted [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L955) ``` fun box sctp_pcb_flags_was_aborted() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_was\_connected [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L956) ``` fun box sctp_pcb_flags_was_connected() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_flags\_zero\_copy\_active [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L957) ``` fun box sctp_pcb_flags_zero_copy_active() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pcb\_status [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L958) ``` fun box sctp_pcb_status() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_peeloff [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L959) ``` fun box sctp_peeloff() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_peer\_addr\_params [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L960) ``` fun box sctp_peer_addr_params() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_peer\_addr\_thlds [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L961) ``` fun box sctp_peer_addr_thlds() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_peer\_auth\_chunks [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L962) ``` fun box sctp_peer_auth_chunks() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pktdrop\_supported [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L963) ``` fun box sctp_pktdrop_supported() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pluggable\_cc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L964) ``` fun box sctp_pluggable_cc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pluggable\_ss [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L965) ``` fun box sctp_pluggable_ss() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_primary\_addr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L966) ``` fun box sctp_primary_addr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pr\_assoc\_status [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L967) ``` fun box sctp_pr_assoc_status() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pr\_stream\_status [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L968) ``` fun box sctp_pr_stream_status() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_pr\_supported [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L969) ``` fun box sctp_pr_supported() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_reconfig\_supported [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L970) ``` fun box sctp_reconfig_supported() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_recvnxtinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L971) ``` fun box sctp_recvnxtinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_recvrcvinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L972) ``` fun box sctp_recvrcvinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_recv\_rwnd\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L973) ``` fun box sctp_recv_rwnd_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_remote\_udp\_encaps\_port [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L974) ``` fun box sctp_remote_udp_encaps_port() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_reset\_assoc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L975) ``` fun box sctp_reset_assoc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_reset\_streams [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L976) ``` fun box sctp_reset_streams() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_reuse\_port [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L977) ``` fun box sctp_reuse_port() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_rtoinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L978) ``` fun box sctp_rtoinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_rttvar\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L979) ``` fun box sctp_rttvar_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_sack\_cmt\_dac [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L980) ``` fun box sctp_sack_cmt_dac() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_sack\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L981) ``` fun box sctp_sack_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_sack\_nonce\_sum [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L982) ``` fun box sctp_sack_nonce_sum() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_sack\_rwnd\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L983) ``` fun box sctp_sack_rwnd_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_sat\_network\_burst\_incr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L984) ``` fun box sctp_sat_network_burst_incr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_sat\_network\_min [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L985) ``` fun box sctp_sat_network_min() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_sb\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L986) ``` fun box sctp_sb_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_selective\_ack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L987) ``` fun box sctp_selective_ack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_set\_debug\_level [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L988) ``` fun box sctp_set_debug_level() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_set\_dynamic\_primary [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L989) ``` fun box sctp_set_dynamic_primary() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_set\_initial\_dbg\_seq [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L990) ``` fun box sctp_set_initial_dbg_seq() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_set\_peer\_primary\_addr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L991) ``` fun box sctp_set_peer_primary_addr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_shutdown [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L992) ``` fun box sctp_shutdown() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_shutdown\_ack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L993) ``` fun box sctp_shutdown_ack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_shutdown\_ack\_sent [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L994) ``` fun box sctp_shutdown_ack_sent() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_shutdown\_complete [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L995) ``` fun box sctp_shutdown_complete() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_shutdown\_pending [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L996) ``` fun box sctp_shutdown_pending() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_shutdown\_received [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L997) ``` fun box sctp_shutdown_received() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_shutdown\_sent [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L998) ``` fun box sctp_shutdown_sent() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_smallest\_pmtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L999) ``` fun box sctp_smallest_pmtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ss\_default [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1000) ``` fun box sctp_ss_default() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ss\_fair\_bandwith [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1001) ``` fun box sctp_ss_fair_bandwith() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ss\_first\_come [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1002) ``` fun box sctp_ss_first_come() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ss\_priority [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1003) ``` fun box sctp_ss_priority() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ss\_round\_robin [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1004) ``` fun box sctp_ss_round_robin() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ss\_round\_robin\_packet [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1005) ``` fun box sctp_ss_round_robin_packet() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_ss\_value [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1006) ``` fun box sctp_ss_value() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_status [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1007) ``` fun box sctp_status() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_stream\_reset [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1008) ``` fun box sctp_stream_reset() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_stream\_reset\_incoming [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1009) ``` fun box sctp_stream_reset_incoming() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_stream\_reset\_outgoing [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1010) ``` fun box sctp_stream_reset_outgoing() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_str\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1011) ``` fun box sctp_str_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_threshold\_logging [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1012) ``` fun box sctp_threshold_logging() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_timeouts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1013) ``` fun box sctp_timeouts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_use\_ext\_rcvinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1014) ``` fun box sctp_use_ext_rcvinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_vrf\_id [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1015) ``` fun box sctp_vrf_id() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sctp\_wake\_logging\_enable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1016) ``` fun box sctp_wake_logging_enable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sock\_cloexec [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1017) ``` fun box sock_cloexec() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sock\_dgram [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1018) ``` fun box sock_dgram() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sock\_maxaddrlen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1019) ``` fun box sock_maxaddrlen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sock\_nonblock [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1020) ``` fun box sock_nonblock() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sock\_raw [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1021) ``` fun box sock_raw() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sock\_rdm [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1022) ``` fun box sock_rdm() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sock\_seqpacket [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1023) ``` fun box sock_seqpacket() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sock\_stream [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1024) ``` fun box sock_stream() : I32 val ``` #### Returns * [I32](builtin-i32) val ### somaxconn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1025) ``` fun box somaxconn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### sonpx\_setoptshut [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1026) ``` fun box sonpx_setoptshut() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_acceptconn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1027) ``` fun box so_acceptconn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_acceptfilter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1028) ``` fun box so_acceptfilter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_atmpvc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1029) ``` fun box so_atmpvc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_atmqos [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1030) ``` fun box so_atmqos() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_atmsap [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1031) ``` fun box so_atmsap() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_attach\_bpf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1032) ``` fun box so_attach_bpf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_attach\_filter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1033) ``` fun box so_attach_filter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_bindtodevice [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1034) ``` fun box so_bindtodevice() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_bintime [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1035) ``` fun box so_bintime() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_bpf\_extensions [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1036) ``` fun box so_bpf_extensions() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_broadcast [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1037) ``` fun box so_broadcast() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_bsdcompat [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1038) ``` fun box so_bsdcompat() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_bsp\_state [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1039) ``` fun box so_bsp_state() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_busy\_poll [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1040) ``` fun box so_busy_poll() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_conaccess [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1041) ``` fun box so_conaccess() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_condata [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1042) ``` fun box so_condata() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_conditional\_accept [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1043) ``` fun box so_conditional_accept() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_connect\_time [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1044) ``` fun box so_connect_time() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_debug [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1045) ``` fun box so_debug() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_detach\_bpf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1046) ``` fun box so_detach_bpf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_detach\_filter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1047) ``` fun box so_detach_filter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_domain [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1048) ``` fun box so_domain() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_dontlinger [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1049) ``` fun box so_dontlinger() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_dontroute [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1050) ``` fun box so_dontroute() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_donttrunc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1051) ``` fun box so_donttrunc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_error [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1052) ``` fun box so_error() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_exclusiveaddruse [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1053) ``` fun box so_exclusiveaddruse() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_get\_filter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1054) ``` fun box so_get_filter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_group\_id [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1055) ``` fun box so_group_id() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_group\_priority [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1056) ``` fun box so_group_priority() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_hci\_raw\_direction [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1057) ``` fun box so_hci_raw_direction() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_hci\_raw\_filter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1058) ``` fun box so_hci_raw_filter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_incoming\_cpu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1059) ``` fun box so_incoming_cpu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_keepalive [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1060) ``` fun box so_keepalive() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_l2cap\_encrypted [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1061) ``` fun box so_l2cap_encrypted() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_l2cap\_flush [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1062) ``` fun box so_l2cap_flush() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_l2cap\_iflow [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1063) ``` fun box so_l2cap_iflow() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_l2cap\_imtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1064) ``` fun box so_l2cap_imtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_l2cap\_oflow [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1065) ``` fun box so_l2cap_oflow() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_l2cap\_omtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1066) ``` fun box so_l2cap_omtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_label [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1067) ``` fun box so_label() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_linger [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1068) ``` fun box so_linger() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_linger\_sec [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1069) ``` fun box so_linger_sec() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_linkinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1070) ``` fun box so_linkinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_listenincqlen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1071) ``` fun box so_listenincqlen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_listenqlen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1072) ``` fun box so_listenqlen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_listenqlimit [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1073) ``` fun box so_listenqlimit() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_lock\_filter [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1074) ``` fun box so_lock_filter() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_mark [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1075) ``` fun box so_mark() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_max\_msg\_size [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1076) ``` fun box so_max_msg_size() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_max\_pacing\_rate [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1077) ``` fun box so_max_pacing_rate() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_multipoint [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1078) ``` fun box so_multipoint() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_netsvc\_marking\_level [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1079) ``` fun box so_netsvc_marking_level() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_net\_service\_type [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1080) ``` fun box so_net_service_type() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_nke [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1081) ``` fun box so_nke() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_noaddrerr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1082) ``` fun box so_noaddrerr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_nofcs [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1083) ``` fun box so_nofcs() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_nosigpipe [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1084) ``` fun box so_nosigpipe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_notifyconflict [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1085) ``` fun box so_notifyconflict() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_no\_check [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1086) ``` fun box so_no_check() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_no\_ddp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1087) ``` fun box so_no_ddp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_no\_offload [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1088) ``` fun box so_no_offload() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_np\_extensions [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1089) ``` fun box so_np_extensions() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_nread [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1090) ``` fun box so_nread() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_numrcvpkt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1091) ``` fun box so_numrcvpkt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_nwrite [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1092) ``` fun box so_nwrite() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_oobinline [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1093) ``` fun box so_oobinline() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_original\_dst [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1094) ``` fun box so_original_dst() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_passcred [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1095) ``` fun box so_passcred() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_passsec [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1096) ``` fun box so_passsec() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_peek\_off [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1097) ``` fun box so_peek_off() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_peercred [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1098) ``` fun box so_peercred() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_peerlabel [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1099) ``` fun box so_peerlabel() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_peername [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1100) ``` fun box so_peername() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_peersec [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1101) ``` fun box so_peersec() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_port\_scalability [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1102) ``` fun box so_port_scalability() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_priority [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1103) ``` fun box so_priority() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_protocol [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1104) ``` fun box so_protocol() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_protocol\_info [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1105) ``` fun box so_protocol_info() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_prototype [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1106) ``` fun box so_prototype() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_proxyusr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1107) ``` fun box so_proxyusr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_randomport [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1108) ``` fun box so_randomport() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_rcvbuf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1109) ``` fun box so_rcvbuf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_rcvbufforce [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1110) ``` fun box so_rcvbufforce() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_rcvlowat [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1111) ``` fun box so_rcvlowat() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_rcvtimeo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1112) ``` fun box so_rcvtimeo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_rds\_transport [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1113) ``` fun box so_rds_transport() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_reuseaddr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1114) ``` fun box so_reuseaddr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_reuseport [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1115) ``` fun box so_reuseport() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_reuseshareuid [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1116) ``` fun box so_reuseshareuid() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_rfcomm\_fc\_info [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1117) ``` fun box so_rfcomm_fc_info() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_rfcomm\_mtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1118) ``` fun box so_rfcomm_mtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_rxq\_ovfl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1119) ``` fun box so_rxq_ovfl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_sco\_conninfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1120) ``` fun box so_sco_conninfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_sco\_mtu [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1121) ``` fun box so_sco_mtu() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_security\_authentication [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1122) ``` fun box so_security_authentication() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_security\_encryption\_network [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1123) ``` fun box so_security_encryption_network() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_security\_encryption\_transport [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1124) ``` fun box so_security_encryption_transport() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_select\_err\_queue [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1125) ``` fun box so_select_err_queue() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_setclp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1126) ``` fun box so_setclp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_setfib [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1127) ``` fun box so_setfib() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_sndbuf [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1128) ``` fun box so_sndbuf() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_sndbufforce [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1129) ``` fun box so_sndbufforce() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_sndlowat [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1130) ``` fun box so_sndlowat() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_sndtimeo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1131) ``` fun box so_sndtimeo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_timestamp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1132) ``` fun box so_timestamp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_timestamping [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1133) ``` fun box so_timestamping() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_timestampns [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1134) ``` fun box so_timestampns() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_timestamp\_monotonic [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1135) ``` fun box so_timestamp_monotonic() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_type [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1136) ``` fun box so_type() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_upcallclosewait [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1137) ``` fun box so_upcallclosewait() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_update\_accept\_context [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1138) ``` fun box so_update_accept_context() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_useloopback [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1139) ``` fun box so_useloopback() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_user\_cookie [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1140) ``` fun box so_user_cookie() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_vendor [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1141) ``` fun box so_vendor() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_vm\_sockets\_buffer\_max\_size [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1142) ``` fun box so_vm_sockets_buffer_max_size() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_vm\_sockets\_buffer\_min\_size [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1143) ``` fun box so_vm_sockets_buffer_min_size() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_vm\_sockets\_buffer\_size [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1144) ``` fun box so_vm_sockets_buffer_size() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_vm\_sockets\_connect\_timeout [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1145) ``` fun box so_vm_sockets_connect_timeout() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_vm\_sockets\_nonblock\_txrx [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1146) ``` fun box so_vm_sockets_nonblock_txrx() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_vm\_sockets\_peer\_host\_vm\_id [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1147) ``` fun box so_vm_sockets_peer_host_vm_id() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_vm\_sockets\_trusted [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1148) ``` fun box so_vm_sockets_trusted() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_wantmore [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1149) ``` fun box so_wantmore() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_wantoobflag [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1150) ``` fun box so_wantoobflag() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_wifi\_status [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1151) ``` fun box so_wifi_status() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp6\_mss [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1152) ``` fun box tcp6_mss() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpci\_flag\_lossrecovery [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1153) ``` fun box tcpci_flag_lossrecovery() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpci\_flag\_reordering\_detected [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1154) ``` fun box tcpci_flag_reordering_detected() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpci\_opt\_ecn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1155) ``` fun box tcpci_opt_ecn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpci\_opt\_sack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1156) ``` fun box tcpci_opt_sack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpci\_opt\_timestamps [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1157) ``` fun box tcpci_opt_timestamps() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpci\_opt\_wscale [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1158) ``` fun box tcpci_opt_wscale() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpf\_ca\_cwr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1159) ``` fun box tcpf_ca_cwr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpf\_ca\_disorder [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1160) ``` fun box tcpf_ca_disorder() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpf\_ca\_loss [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1161) ``` fun box tcpf_ca_loss() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpf\_ca\_open [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1162) ``` fun box tcpf_ca_open() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpf\_ca\_recovery [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1163) ``` fun box tcpf_ca_recovery() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpi\_opt\_ecn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1164) ``` fun box tcpi_opt_ecn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpi\_opt\_ecn\_seen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1165) ``` fun box tcpi_opt_ecn_seen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpi\_opt\_sack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1166) ``` fun box tcpi_opt_sack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpi\_opt\_syn\_data [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1167) ``` fun box tcpi_opt_syn_data() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpi\_opt\_timestamps [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1168) ``` fun box tcpi_opt_timestamps() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpi\_opt\_toe [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1169) ``` fun box tcpi_opt_toe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpi\_opt\_wscale [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1170) ``` fun box tcpi_opt_wscale() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_cc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1171) ``` fun box tcpolen_cc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_cc\_appa [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1172) ``` fun box tcpolen_cc_appa() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_eol [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1173) ``` fun box tcpolen_eol() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_fastopen\_req [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1174) ``` fun box tcpolen_fastopen_req() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_fast\_open\_empty [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1175) ``` fun box tcpolen_fast_open_empty() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_fast\_open\_max [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1176) ``` fun box tcpolen_fast_open_max() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_fast\_open\_min [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1177) ``` fun box tcpolen_fast_open_min() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_maxseg [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1178) ``` fun box tcpolen_maxseg() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_nop [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1179) ``` fun box tcpolen_nop() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_pad [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1180) ``` fun box tcpolen_pad() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_sack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1181) ``` fun box tcpolen_sack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_sackhdr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1182) ``` fun box tcpolen_sackhdr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_sack\_permitted [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1183) ``` fun box tcpolen_sack_permitted() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_signature [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1184) ``` fun box tcpolen_signature() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_timestamp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1185) ``` fun box tcpolen_timestamp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_tstamp\_appa [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1186) ``` fun box tcpolen_tstamp_appa() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpolen\_window [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1187) ``` fun box tcpolen_window() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_cc [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1188) ``` fun box tcpopt_cc() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_ccecho [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1189) ``` fun box tcpopt_ccecho() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_ccnew [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1190) ``` fun box tcpopt_ccnew() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_eol [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1191) ``` fun box tcpopt_eol() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_fastopen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1192) ``` fun box tcpopt_fastopen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_fast\_open [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1193) ``` fun box tcpopt_fast_open() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_maxseg [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1194) ``` fun box tcpopt_maxseg() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_multipath [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1195) ``` fun box tcpopt_multipath() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_nop [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1196) ``` fun box tcpopt_nop() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_pad [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1197) ``` fun box tcpopt_pad() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_sack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1198) ``` fun box tcpopt_sack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_sack\_hdr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1199) ``` fun box tcpopt_sack_hdr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_sack\_permitted [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1200) ``` fun box tcpopt_sack_permitted() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_sack\_permit\_hdr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1201) ``` fun box tcpopt_sack_permit_hdr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_signature [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1202) ``` fun box tcpopt_signature() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_timestamp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1203) ``` fun box tcpopt_timestamp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_tstamp\_hdr [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1204) ``` fun box tcpopt_tstamp_hdr() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcpopt\_window [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1205) ``` fun box tcpopt_window() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_ca\_name\_max [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1206) ``` fun box tcp_ca_name_max() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_ccalgoopt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1207) ``` fun box tcp_ccalgoopt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_cc\_info [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1208) ``` fun box tcp_cc_info() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_congestion [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1209) ``` fun box tcp_congestion() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_connectiontimeout [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1210) ``` fun box tcp_connectiontimeout() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_connection\_info [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1211) ``` fun box tcp_connection_info() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_cookie\_in\_always [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1212) ``` fun box tcp_cookie_in_always() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_cookie\_max [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1213) ``` fun box tcp_cookie_max() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_cookie\_min [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1214) ``` fun box tcp_cookie_min() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_cookie\_out\_never [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1215) ``` fun box tcp_cookie_out_never() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_cookie\_pair\_size [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1216) ``` fun box tcp_cookie_pair_size() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_cookie\_transactions [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1217) ``` fun box tcp_cookie_transactions() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_cork [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1218) ``` fun box tcp_cork() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_defer\_accept [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1219) ``` fun box tcp_defer_accept() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_enable\_ecn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1220) ``` fun box tcp_enable_ecn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_fastopen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1221) ``` fun box tcp_fastopen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_function\_blk [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1222) ``` fun box tcp_function_blk() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_function\_name\_len\_max [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1223) ``` fun box tcp_function_name_len_max() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_info [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1224) ``` fun box tcp_info() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_keepalive [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1225) ``` fun box tcp_keepalive() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_keepcnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1226) ``` fun box tcp_keepcnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_keepidle [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1227) ``` fun box tcp_keepidle() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_keepinit [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1228) ``` fun box tcp_keepinit() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_keepintvl [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1229) ``` fun box tcp_keepintvl() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_linger2 [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1230) ``` fun box tcp_linger2() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_maxburst [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1231) ``` fun box tcp_maxburst() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_maxhlen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1232) ``` fun box tcp_maxhlen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_maxolen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1233) ``` fun box tcp_maxolen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_maxseg [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1234) ``` fun box tcp_maxseg() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_maxwin [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1235) ``` fun box tcp_maxwin() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_max\_sack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1236) ``` fun box tcp_max_sack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_max\_winshift [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1237) ``` fun box tcp_max_winshift() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_md5sig [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1238) ``` fun box tcp_md5sig() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_md5sig\_maxkeylen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1239) ``` fun box tcp_md5sig_maxkeylen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_minmss [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1240) ``` fun box tcp_minmss() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_mss [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1241) ``` fun box tcp_mss() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_mss\_default [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1242) ``` fun box tcp_mss_default() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_mss\_desired [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1243) ``` fun box tcp_mss_desired() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_nodelay [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1244) ``` fun box tcp_nodelay() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_noopt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1245) ``` fun box tcp_noopt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_nopush [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1246) ``` fun box tcp_nopush() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_notsent\_lowat [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1247) ``` fun box tcp_notsent_lowat() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_pcap\_in [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1248) ``` fun box tcp_pcap_in() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_pcap\_out [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1249) ``` fun box tcp_pcap_out() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_queue\_seq [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1250) ``` fun box tcp_queue_seq() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_quickack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1251) ``` fun box tcp_quickack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_repair [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1252) ``` fun box tcp_repair() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_repair\_options [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1253) ``` fun box tcp_repair_options() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_repair\_queue [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1254) ``` fun box tcp_repair_queue() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_rxt\_conndroptime [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1255) ``` fun box tcp_rxt_conndroptime() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_rxt\_findrop [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1256) ``` fun box tcp_rxt_findrop() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_saved\_syn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1257) ``` fun box tcp_saved_syn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_save\_syn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1258) ``` fun box tcp_save_syn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_sendmoreacks [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1259) ``` fun box tcp_sendmoreacks() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_syncnt [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1260) ``` fun box tcp_syncnt() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_s\_data\_in [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1261) ``` fun box tcp_s_data_in() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_s\_data\_out [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1262) ``` fun box tcp_s_data_out() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_thin\_dupack [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1263) ``` fun box tcp_thin_dupack() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_thin\_linear\_timeouts [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1264) ``` fun box tcp_thin_linear_timeouts() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_timestamp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1265) ``` fun box tcp_timestamp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_user\_timeout [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1266) ``` fun box tcp_user_timeout() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_vendor [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1267) ``` fun box tcp_vendor() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tcp\_window\_clamp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1268) ``` fun box tcp_window_clamp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_addr\_id [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1269) ``` fun box tipc_addr_id() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_addr\_mcast [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1270) ``` fun box tipc_addr_mcast() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_addr\_name [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1271) ``` fun box tipc_addr_name() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_addr\_nameseq [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1272) ``` fun box tipc_addr_nameseq() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_cfg\_srv [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1273) ``` fun box tipc_cfg_srv() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_cluster\_scope [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1274) ``` fun box tipc_cluster_scope() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_conn\_shutdown [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1275) ``` fun box tipc_conn_shutdown() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_conn\_timeout [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1276) ``` fun box tipc_conn_timeout() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_critical\_importance [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1277) ``` fun box tipc_critical_importance() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_destname [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1278) ``` fun box tipc_destname() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_dest\_droppable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1279) ``` fun box tipc_dest_droppable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_errinfo [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1280) ``` fun box tipc_errinfo() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_err\_no\_name [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1281) ``` fun box tipc_err_no_name() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_err\_no\_node [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1282) ``` fun box tipc_err_no_node() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_err\_no\_port [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1283) ``` fun box tipc_err_no_port() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_err\_overload [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1284) ``` fun box tipc_err_overload() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_high\_importance [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1285) ``` fun box tipc_high_importance() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_importance [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1286) ``` fun box tipc_importance() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_link\_state [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1287) ``` fun box tipc_link_state() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_low\_importance [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1288) ``` fun box tipc_low_importance() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_max\_bearer\_name [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1289) ``` fun box tipc_max_bearer_name() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_max\_if\_name [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1290) ``` fun box tipc_max_if_name() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_max\_link\_name [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1291) ``` fun box tipc_max_link_name() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_max\_media\_name [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1292) ``` fun box tipc_max_media_name() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_max\_user\_msg\_size [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1293) ``` fun box tipc_max_user_msg_size() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_medium\_importance [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1294) ``` fun box tipc_medium_importance() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_node\_recvq\_depth [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1295) ``` fun box tipc_node_recvq_depth() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_node\_scope [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1296) ``` fun box tipc_node_scope() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_ok [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1297) ``` fun box tipc_ok() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_published [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1298) ``` fun box tipc_published() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_reserved\_types [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1299) ``` fun box tipc_reserved_types() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_retdata [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1300) ``` fun box tipc_retdata() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_sock\_recvq\_depth [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1301) ``` fun box tipc_sock_recvq_depth() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_src\_droppable [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1302) ``` fun box tipc_src_droppable() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_subscr\_timeout [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1303) ``` fun box tipc_subscr_timeout() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_sub\_cancel [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1304) ``` fun box tipc_sub_cancel() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_sub\_ports [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1305) ``` fun box tipc_sub_ports() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_sub\_service [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1306) ``` fun box tipc_sub_service() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_top\_srv [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1307) ``` fun box tipc_top_srv() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_wait\_forever [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1308) ``` fun box tipc_wait_forever() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_withdrawn [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1309) ``` fun box tipc_withdrawn() : I32 val ``` #### Returns * [I32](builtin-i32) val ### tipc\_zone\_scope [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1310) ``` fun box tipc_zone_scope() : I32 val ``` #### Returns * [I32](builtin-i32) val ### ttcp\_client\_snd\_wnd [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1311) ``` fun box ttcp_client_snd_wnd() : I32 val ``` #### Returns * [I32](builtin-i32) val ### udp\_cork [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1312) ``` fun box udp_cork() : I32 val ``` #### Returns * [I32](builtin-i32) val ### udp\_encap [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1313) ``` fun box udp_encap() : I32 val ``` #### Returns * [I32](builtin-i32) val ### udp\_encap\_espinudp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1314) ``` fun box udp_encap_espinudp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### udp\_encap\_espinudp\_maxfraglen [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1315) ``` fun box udp_encap_espinudp_maxfraglen() : I32 val ``` #### Returns * [I32](builtin-i32) val ### udp\_encap\_espinudp\_non\_ike [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1316) ``` fun box udp_encap_espinudp_non_ike() : I32 val ``` #### Returns * [I32](builtin-i32) val ### udp\_encap\_espinudp\_port [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1317) ``` fun box udp_encap_espinudp_port() : I32 val ``` #### Returns * [I32](builtin-i32) val ### udp\_encap\_l2tpinudp [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1318) ``` fun box udp_encap_l2tpinudp() : I32 val ``` #### Returns * [I32](builtin-i32) val ### udp\_nocksum [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1319) ``` fun box udp_nocksum() : I32 val ``` #### Returns * [I32](builtin-i32) val ### udp\_no\_check6\_rx [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1320) ``` fun box udp_no_check6_rx() : I32 val ``` #### Returns * [I32](builtin-i32) val ### udp\_no\_check6\_tx [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1321) ``` fun box udp_no_check6_tx() : I32 val ``` #### Returns * [I32](builtin-i32) val ### udp\_vendor [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1322) ``` fun box udp_vendor() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_rcvtimeo\_old [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1323) ``` fun box so_rcvtimeo_old() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_rcvtimeo\_new [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1324) ``` fun box so_rcvtimeo_new() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_sndtimeo\_old [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1325) ``` fun box so_sndtimeo_old() : I32 val ``` #### Returns * [I32](builtin-i32) val ### so\_sndtimeo\_new [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L1326) ``` fun box so_sndtimeo_new() : I32 val ``` #### Returns * [I32](builtin-i32) val ### eq [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L76) ``` fun box eq( that: OSSockOpt val) : Bool val ``` #### Parameters * that: [OSSockOpt](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/net/ossockopt/#L76) ``` fun box ne( that: OSSockOpt val) : Bool val ``` #### Parameters * that: [OSSockOpt](index) val #### Returns * [Bool](builtin-bool) val
programming_docs
pony ApplyReleaseBackpressureAuth ApplyReleaseBackpressureAuth ============================ [[Source]](https://stdlib.ponylang.io/src/backpressure/auth/#L1) ``` primitive val ApplyReleaseBackpressureAuth ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/backpressure/auth/#L2) ``` new val create( from: AmbientAuth val) : ApplyReleaseBackpressureAuth val^ ``` #### Parameters * from: [AmbientAuth](builtin-ambientauth) val #### Returns * [ApplyReleaseBackpressureAuth](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/backpressure/auth/#L2) ``` fun box eq( that: ApplyReleaseBackpressureAuth val) : Bool val ``` #### Parameters * that: [ApplyReleaseBackpressureAuth](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/backpressure/auth/#L2) ``` fun box ne( that: ApplyReleaseBackpressureAuth val) : Bool val ``` #### Parameters * that: [ApplyReleaseBackpressureAuth](index) val #### Returns * [Bool](builtin-bool) val pony Array[A: A] Array[A: A] =========== [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L1) Contiguous, resizable memory to store elements of type A. Usage ----- Creating an Array of String: ``` let array: Array[String] = ["dog"; "cat"; "wombat"] // array.size() == 3 // array.space() >= 3 ``` Creating an empty Array of String, which may hold at least 10 elements before requesting more space: ``` let array = Array[String](10) // array.size() == 0 // array.space() >= 10 ``` Accessing elements can be done via the `apply(i: USize): this->A ?` method. The provided index might be out of bounds so `apply` is partial and has to be called within a try-catch block or inside another partial method: ``` let array: Array[String] = ["dog"; "cat"; "wombat"] let is_second_element_wobat = try // indexes start from 0, so 1 is the second element array(1)? == "wombat" else false end ``` Adding and removing elements to and from the end of the Array can be done via `push` and `pop` methods. You could treat the array as a LIFO stack using those methods: ``` while (array.size() > 0) do let elem = array.pop()? // do something with element end ``` Modifying the Array can be done via `update`, `insert` and `delete` methods which alter the Array at an arbitrary index, moving elements left (when deleting) or right (when inserting) as necessary. Iterating over the elements of an Array can be done using the `values` method: ``` for element in array.values() do // do something with element end ``` Memory allocation ----------------- Array allocates contiguous memory. It always allocates at least enough memory space to hold all of its elements. Space is the number of elements the Array can hold without allocating more memory. The `space()` method returns the number of elements an Array can hold. The `size()` method returns the number of elements the Array holds. Different data types require different amounts of memory. Array[U64] with size of 6 will take more memory than an Array[U8] of the same size. When creating an Array or adding more elements will calculate the next power of 2 of the requested number of elements and allocate that much space, with a lower bound of space for 8 elements. Here's a few examples of the space allocated when initialising an Array with various number of elements: | size | space | | --- | --- | | 0 | 0 | | 1 | 8 | | 8 | 8 | | 9 | 16 | | 16 | 16 | | 17 | 32 | Call the `compact()` method to ask the GC to reclaim unused space. There are no guarantees that the GC will actually reclaim any space. ``` class ref Array[A: A] is Seq[A] ref ``` #### Implements * [Seq](builtin-seq)[A] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L89) Create an array with zero elements, but space for len elements. ``` new ref create( len: USize val = 0) : Array[A] ref^ ``` #### Parameters * len: [USize](builtin-usize) val = 0 #### Returns * [Array](index)[A] ref^ ### init [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L103) Create an array of len elements, all initialised to the given value. ``` new ref init( from: A^, len: USize val) : Array[A] ref^ ``` #### Parameters * from: A^ * len: [USize](builtin-usize) val #### Returns * [Array](index)[A] ref^ ### from\_cpointer [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L124) Create an array from a C-style pointer and length. The contents are not copied. ``` new ref from_cpointer( ptr: Pointer[A] ref, len: USize val, alloc: USize val = 0) : Array[A] ref^ ``` #### Parameters * ptr: [Pointer](builtin-pointer)[A] ref * len: [USize](builtin-usize) val * alloc: [USize](builtin-usize) val = 0 #### Returns * [Array](index)[A] ref^ Public Functions ---------------- ### cpointer [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L150) Return the underlying C-style pointer. ``` fun box cpointer( offset: USize val = 0) : Pointer[A] tag ``` #### Parameters * offset: [USize](builtin-usize) val = 0 #### Returns * [Pointer](builtin-pointer)[A] tag ### size [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L156) The number of elements in the array. ``` fun box size() : USize val ``` #### Returns * [USize](builtin-usize) val ### space [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L162) The available space in the array. ``` fun box space() : USize val ``` #### Returns * [USize](builtin-usize) val ### reserve [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L168) Reserve space for len elements, including whatever elements are already in the array. Array space grows geometrically. ``` fun ref reserve( len: USize val) : None val ``` #### Parameters * len: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### compact [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L184) Try to remove unused space, making it available for garbage collection. The request may be ignored. ``` fun ref compact() : None val ``` #### Returns * [None](builtin-none) val ### undefined[optional B: (A & [Real](builtin-real)[B] val & ([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](builtin-i32) val | [I64](builtin-i64) val | [I128](builtin-i128) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val | [U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val | [F32](builtin-f32) val | [F64](builtin-f64) val))] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L201) Resize to len elements, populating previously empty elements with random memory. This is only allowed for an array of numbers. ``` fun ref undefined[optional B: (A & Real[B] val & (I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val))]( len: USize val) : None val ``` #### Parameters * len: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### read\_u8[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L209) Reads a U8 from offset. This is only allowed for an array of U8s. ``` fun box read_u8[optional B: (A & Real[B] val & U8 val)]( offset: USize val) : U8 val ? ``` #### Parameters * offset: [USize](builtin-usize) val #### Returns * [U8](builtin-u8) val ? ### read\_u16[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L219) Reads a U16 from offset. This is only allowed for an array of U8s. ``` fun box read_u16[optional B: (A & Real[B] val & U8 val)]( offset: USize val) : U16 val ? ``` #### Parameters * offset: [USize](builtin-usize) val #### Returns * [U16](builtin-u16) val ? ### read\_u32[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L230) Reads a U32 from offset. This is only allowed for an array of U8s. ``` fun box read_u32[optional B: (A & Real[B] val & U8 val)]( offset: USize val) : U32 val ? ``` #### Parameters * offset: [USize](builtin-usize) val #### Returns * [U32](builtin-u32) val ? ### read\_u64[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L241) Reads a U64 from offset. This is only allowed for an array of U8s. ``` fun box read_u64[optional B: (A & Real[B] val & U8 val)]( offset: USize val) : U64 val ? ``` #### Parameters * offset: [USize](builtin-usize) val #### Returns * [U64](builtin-u64) val ? ### read\_u128[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L252) Reads a U128 from offset. This is only allowed for an array of U8s. ``` fun box read_u128[optional B: (A & Real[B] val & U8 val)]( offset: USize val) : U128 val ? ``` #### Parameters * offset: [USize](builtin-usize) val #### Returns * [U128](builtin-u128) val ? ### apply [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L263) Get the i-th element, raising an error if the index is out of bounds. ``` fun box apply( i: USize val) : this->A ? ``` #### Parameters * i: [USize](builtin-usize) val #### Returns * this->A ? ### update\_u8[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L273) Write a U8 at offset. This is only allowed for an array of U8s. ``` fun ref update_u8[optional B: (A & Real[B] val & U8 val)]( offset: USize val, value: U8 val) : U8 val ? ``` #### Parameters * offset: [USize](builtin-usize) val * value: [U8](builtin-u8) val #### Returns * [U8](builtin-u8) val ? ### update\_u16[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L283) Write a U16 at offset. This is only allowed for an array of U8s. ``` fun ref update_u16[optional B: (A & Real[B] val & U8 val)]( offset: USize val, value: U16 val) : U16 val ? ``` #### Parameters * offset: [USize](builtin-usize) val * value: [U16](builtin-u16) val #### Returns * [U16](builtin-u16) val ? ### update\_u32[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L294) Write a U32 at offset. This is only allowed for an array of U8s. ``` fun ref update_u32[optional B: (A & Real[B] val & U8 val)]( offset: USize val, value: U32 val) : U32 val ? ``` #### Parameters * offset: [USize](builtin-usize) val * value: [U32](builtin-u32) val #### Returns * [U32](builtin-u32) val ? ### update\_u64[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L305) Write a U64 at offset. This is only allowed for an array of U8s. ``` fun ref update_u64[optional B: (A & Real[B] val & U8 val)]( offset: USize val, value: U64 val) : U64 val ? ``` #### Parameters * offset: [USize](builtin-usize) val * value: [U64](builtin-u64) val #### Returns * [U64](builtin-u64) val ? ### update\_u128[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L316) Write a U128 at offset. This is only allowed for an array of U8s. ``` fun ref update_u128[optional B: (A & Real[B] val & U8 val)]( offset: USize val, value: U128 val) : U128 val ? ``` #### Parameters * offset: [USize](builtin-usize) val * value: [U128](builtin-u128) val #### Returns * [U128](builtin-u128) val ? ### update [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L327) Change the i-th element, raising an error if the index is out of bounds. ``` fun ref update( i: USize val, value: A) : A^ ? ``` #### Parameters * i: [USize](builtin-usize) val * value: A #### Returns * A^ ? ### insert [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L337) Insert an element into the array. Elements after this are moved up by one index, extending the array. When inserting right beyond the last element, at index `this.size()`, the element will be appended, similar to `push()`, an insert at index `0` prepends the value to the array. An insert into an index beyond `this.size()` raises an error. ``` let array = Array[U8](4) // [] array.insert(0, 0xDE)? // prepend: [0xDE] array.insert(array.size(), 0xBE)? // append: [0xDE; 0xBE] array.insert(1, 0xAD)? // insert: [0xDE; 0xAD; 0xBE] array.insert(array.size() + 1, 0xEF)? // error ``` ``` fun ref insert( i: USize val, value: A) : None val ? ``` #### Parameters * i: [USize](builtin-usize) val * value: A #### Returns * [None](builtin-none) val ? ### delete [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L364) Delete an element from the array. Elements after this are moved down by one index, compacting the array. An out of bounds index raises an error. The deleted element is returned. ``` fun ref delete( i: USize val) : A^ ? ``` #### Parameters * i: [USize](builtin-usize) val #### Returns * A^ ? ### truncate [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L378) Truncate an array to the given length, discarding excess elements. If the array is already smaller than len, do nothing. ``` fun ref truncate( len: USize val) : None val ``` #### Parameters * len: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### trim\_in\_place [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L385) Trim the array to a portion of itself, covering `from` until `to`. Unlike slice, the operation does not allocate a new array nor copy elements. ``` fun ref trim_in_place( from: USize val = 0, to: USize val = call) : None val ``` #### Parameters * from: [USize](builtin-usize) val = 0 * to: [USize](builtin-usize) val = call #### Returns * [None](builtin-none) val ### trim [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L412) Return a shared portion of this array, covering `from` until `to`. Both the original and the new array are immutable, as they share memory. The operation does not allocate a new array pointer nor copy elements. ``` fun val trim( from: USize val = 0, to: USize val = call) : Array[A] val ``` #### Parameters * from: [USize](builtin-usize) val = 0 * to: [USize](builtin-usize) val = call #### Returns * [Array](index)[A] val ### chop[optional B: (A & [Any](builtin-any) #send)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L436) Chops the array in half at the split point requested and returns both the left and right portions. The original array is trimmed in place and returned as the left portion. If the split point is larger than the array, the left portion is the original array and the right portion is a new empty array. The operation does not allocate a new array pointer nor copy elements. The entry type must be sendable so that the two halves can be isolated. Otherwise, two entries may have shared references to mutable data, or even to each other, such as in the code below: ``` class Example var other: (Example | None) = None let arr: Array[Example] iso = recover let obj1 = Example let obj2 = Example obj1.other = obj2 obj2.other = obj1 [obj1; obj2] end ``` ``` fun iso chop[optional B: (A & Any #send)]( split_point: USize val) : (Array[A] iso^ , Array[A] iso^) ``` #### Parameters * split\_point: [USize](builtin-usize) val #### Returns * ([Array](index)[A] iso^ , [Array](index)[A] iso^) ### unchop [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L479) Unchops two iso arrays to return the original array they were chopped from. Both input arrays are isolated and mutable and were originally chopped from a single array. This function checks that they are indeed two arrays chopped from the same original array and can be unchopped before doing the unchopping and returning the unchopped array. If the two arrays cannot be unchopped it returns both arrays without modifying them. The operation does not allocate a new array pointer nor copy elements. ``` fun iso unchop( b: Array[A] iso) : ((Array[A] iso^ , Array[A] iso^) | Array[A] iso^) ``` #### Parameters * b: [Array](index)[A] iso #### Returns * (([Array](index)[A] iso^ , [Array](index)[A] iso^) | [Array](index)[A] iso^) ### copy\_from[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L523) Copy len elements from src(src\_idx) to this(dst\_idx). Only works for Array[U8]. ``` fun ref copy_from[optional B: (A & Real[B] val & U8 val)]( src: Array[U8 val] box, src_idx: USize val, dst_idx: USize val, len: USize val) : None val ``` #### Parameters * src: [Array](index)[[U8](builtin-u8) val] box * src\_idx: [USize](builtin-usize) val * dst\_idx: [USize](builtin-usize) val * len: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### copy\_to [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L540) Copy len elements from this(src\_idx) to dst(dst\_idx). ``` fun box copy_to( dst: Array[this->A!] ref, src_idx: USize val, dst_idx: USize val, len: USize val) : None val ``` #### Parameters * dst: [Array](index)[this->A!] ref * src\_idx: [USize](builtin-usize) val * dst\_idx: [USize](builtin-usize) val * len: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### remove [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L556) Remove n elements from the array, beginning at index i. ``` fun ref remove( i: USize val, n: USize val) : None val ``` #### Parameters * i: [USize](builtin-usize) val * n: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### clear [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L566) Remove all elements from the array. ``` fun ref clear() : None val ``` #### Returns * [None](builtin-none) val ### push\_u8[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L572) Add a U8 to the end of the array. This is only allowed for an array of U8s. ``` fun ref push_u8[optional B: (A & Real[B] val & U8 val)]( value: U8 val) : None val ``` #### Parameters * value: [U8](builtin-u8) val #### Returns * [None](builtin-none) val ### push\_u16[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L581) Add a U16 to the end of the array. This is only allowed for an array of U8s. ``` fun ref push_u16[optional B: (A & Real[B] val & U8 val)]( value: U16 val) : None val ``` #### Parameters * value: [U16](builtin-u16) val #### Returns * [None](builtin-none) val ### push\_u32[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L590) Add a U32 to the end of the array. This is only allowed for an array of U8s. ``` fun ref push_u32[optional B: (A & Real[B] val & U8 val)]( value: U32 val) : None val ``` #### Parameters * value: [U32](builtin-u32) val #### Returns * [None](builtin-none) val ### push\_u64[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L599) Add a U64 to the end of the array. This is only allowed for an array of U8s. ``` fun ref push_u64[optional B: (A & Real[B] val & U8 val)]( value: U64 val) : None val ``` #### Parameters * value: [U64](builtin-u64) val #### Returns * [None](builtin-none) val ### push\_u128[optional B: (A & [Real](builtin-real)[B] val & [U8](builtin-u8) val)] [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L608) Add a U128 to the end of the array. This is only allowed for an array of U8s. ``` fun ref push_u128[optional B: (A & Real[B] val & U8 val)]( value: U128 val) : None val ``` #### Parameters * value: [U128](builtin-u128) val #### Returns * [None](builtin-none) val ### push [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L617) Add an element to the end of the array. ``` fun ref push( value: A) : None val ``` #### Parameters * value: A #### Returns * [None](builtin-none) val ### pop [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L625) Remove an element from the end of the array. The removed element is returned. ``` fun ref pop() : A^ ? ``` #### Returns * A^ ? ### unshift [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L632) Add an element to the beginning of the array. ``` fun ref unshift( value: A) : None val ``` #### Parameters * value: A #### Returns * [None](builtin-none) val ### shift [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L640) Remove an element from the beginning of the array. The removed element is returned. ``` fun ref shift() : A^ ? ``` #### Returns * A^ ? ### append [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L647) Append the elements from a sequence, starting from the given offset. ``` fun ref append( seq: (ReadSeq[A] box & ReadElement[A^] box), offset: USize val = 0, len: USize val = call) : None val ``` #### Parameters * seq: ([ReadSeq](builtin-readseq)[A] box & [ReadElement](builtin-readelement)[A^] box) * offset: [USize](builtin-usize) val = 0 * len: [USize](builtin-usize) val = call #### Returns * [None](builtin-none) val ### concat [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L674) Add len iterated elements to the end of the array, starting from the given offset. ``` fun ref concat( iter: Iterator[A^] ref, offset: USize val = 0, len: USize val = call) : None val ``` #### Parameters * iter: [Iterator](builtin-iterator)[A^] ref * offset: [USize](builtin-usize) val = 0 * len: [USize](builtin-usize) val = call #### Returns * [None](builtin-none) val ### find [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L730) Find the `nth` appearance of `value` from the beginning of the array, starting at `offset` and examining higher indices, and using the supplied `predicate` for comparisons. Returns the index of the value, or raise an error if the value isn't present. By default, the search starts at the first element of the array, returns the first instance of `value` found, and uses object identity for comparison. ``` fun box find( value: A!, offset: USize val = 0, nth: USize val = 0, predicate: {(box->A!, box->A!): Bool}[A] val = lambda) : USize val ? ``` #### Parameters * value: A! * offset: [USize](builtin-usize) val = 0 * nth: [USize](builtin-usize) val = 0 * predicate: {(box->A!, box->A!): Bool}[A] val = lambda #### Returns * [USize](builtin-usize) val ? ### contains [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L764) Returns true if the array contains `value`, false otherwise. The default predicate checks for matches by identity. To search for matches by structural equality, pass an object literal such as `{(l, r) => l == r}`. ``` fun box contains( value: A!, predicate: {(box->A!, box->A!): Bool}[A] val = lambda) : Bool val ``` #### Parameters * value: A! * predicate: {(box->A!, box->A!): Bool}[A] val = lambda #### Returns * [Bool](builtin-bool) val ### rfind [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L787) Find the `nth` appearance of `value` from the end of the array, starting at `offset` and examining lower indices, and using the supplied `predicate` for comparisons. Returns the index of the value, or raise an error if the value isn't present. By default, the search starts at the last element of the array, returns the first instance of `value` found, and uses object identity for comparison. ``` fun box rfind( value: A!, offset: USize val = call, nth: USize val = 0, predicate: {(box->A!, box->A!): Bool}[A] val = lambda) : USize val ? ``` #### Parameters * value: A! * offset: [USize](builtin-usize) val = call * nth: [USize](builtin-usize) val = 0 * predicate: {(box->A!, box->A!): Bool}[A] val = lambda #### Returns * [USize](builtin-usize) val ? ### clone [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L822) Clone the array. The new array contains references to the same elements that the old array contains, the elements themselves are not cloned. ``` fun box clone() : Array[this->A!] ref^ ``` #### Returns * [Array](index)[this->A!] ref^ ### slice [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L833) Create a new array that is a clone of a portion of this array. The range is exclusive and saturated. The new array contains references to the same elements that the old array contains, the elements themselves are not cloned. ``` fun box slice( from: USize val = 0, to: USize val = call, step: USize val = 1) : Array[this->A!] ref^ ``` #### Parameters * from: [USize](builtin-usize) val = 0 * to: [USize](builtin-usize) val = call * step: [USize](builtin-usize) val = 1 #### Returns * [Array](index)[this->A!] ref^ ### permute [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L868) Create a new array with the elements permuted. Permute to an arbitrary order that may include duplicates. An out of bounds index raises an error. The new array contains references to the same elements that the old array contains, the elements themselves are not copied. ``` fun box permute( indices: Iterator[USize val] ref) : Array[this->A!] ref^ ? ``` #### Parameters * indices: [Iterator](builtin-iterator)[[USize](builtin-usize) val] ref #### Returns * [Array](index)[this->A!] ref^ ? ### reverse [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L882) Create a new array with the elements in reverse order. The new array contains references to the same elements that the old array contains, the elements themselves are not copied. ``` fun box reverse() : Array[this->A!] ref^ ``` #### Returns * [Array](index)[this->A!] ref^ ### reverse\_in\_place [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L890) Reverse the array in place. ``` fun ref reverse_in_place() : None val ``` #### Returns * [None](builtin-none) val ### swap\_elements [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L907) Swap the element at index i with the element at index j. If either i or j are out of bounds, an error is raised. ``` fun ref swap_elements( i: USize val, j: USize val) : None val ? ``` #### Parameters * i: [USize](builtin-usize) val * j: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ? ### keys [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L918) Return an iterator over the indices in the array. ``` fun box keys() : ArrayKeys[A, this->Array[A] ref] ref^ ``` #### Returns * [ArrayKeys](builtin-arraykeys)[A, this->[Array](index)[A] ref] ref^ ### values [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L924) Return an iterator over the values in the array. ``` fun box values() : ArrayValues[A, this->Array[A] ref] ref^ ``` #### Returns * [ArrayValues](builtin-arrayvalues)[A, this->[Array](index)[A] ref] ref^ ### pairs [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L930) Return an iterator over the (index, value) pairs in the array. ``` fun box pairs() : ArrayPairs[A, this->Array[A] ref] ref^ ``` #### Returns * [ArrayPairs](builtin-arraypairs)[A, this->[Array](index)[A] ref] ref^
programming_docs
pony DoNotOptimise DoNotOptimise ============= [[Source]](https://stdlib.ponylang.io/src/builtin/do_not_optimise/#L1) Contains functions preventing some compiler optimisations, namely dead code removal. This is useful for benchmarking purposes. ``` primitive val DoNotOptimise ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/do_not_optimise/#L1) ``` new val create() : DoNotOptimise val^ ``` #### Returns * [DoNotOptimise](index) val^ Public Functions ---------------- ### apply[A: A] [[Source]](https://stdlib.ponylang.io/src/builtin/do_not_optimise/#L7) Prevent the compiler from optimising out obj and any computation it is derived from. This doesn't prevent constant propagation. ``` fun box apply[A: A]( obj: A) : None val ``` #### Parameters * obj: A #### Returns * [None](builtin-none) val ### observe [[Source]](https://stdlib.ponylang.io/src/builtin/do_not_optimise/#L14) Prevent the compiler from optimising out writes to an object marked by the apply function. ``` fun box observe() : None val ``` #### Returns * [None](builtin-none) val ### eq [[Source]](https://stdlib.ponylang.io/src/builtin/do_not_optimise/#L7) ``` fun box eq( that: DoNotOptimise val) : Bool val ``` #### Parameters * that: [DoNotOptimise](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/builtin/do_not_optimise/#L7) ``` fun box ne( that: DoNotOptimise val) : Bool val ``` #### Parameters * that: [DoNotOptimise](index) val #### Returns * [Bool](builtin-bool) val pony PipeError PipeError ========= [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L41) ``` primitive val PipeError ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L41) ``` new val create() : PipeError val^ ``` #### Returns * [PipeError](index) val^ Public Functions ---------------- ### string [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L42) ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### eq [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L42) ``` fun box eq( that: PipeError val) : Bool val ``` #### Parameters * that: [PipeError](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L42) ``` fun box ne( that: PipeError val) : Bool val ``` #### Parameters * that: [PipeError](index) val #### Returns * [Bool](builtin-bool) val pony ProcessMonitor ProcessMonitor ============== [[Source]](https://stdlib.ponylang.io/src/process/process_monitor/#L102) Fork+execs / creates a child process and monitors it. Notifies a client about STDOUT / STDERR events. ``` actor tag ProcessMonitor ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/process/process_monitor/#L128) Create infrastructure to communicate with a forked child process and register the asio events. Fork child process and notify our user about incoming data via the notifier. ``` new tag create( auth: (AmbientAuth val | StartProcessAuth val), backpressure_auth: (AmbientAuth val | ApplyReleaseBackpressureAuth val), notifier: ProcessNotify iso, filepath: FilePath val, args: Array[String val] val, vars: Array[String val] val, wdir: (FilePath val | None val) = reference, process_poll_interval: U64 val = call) : ProcessMonitor tag^ ``` #### Parameters * auth: ([AmbientAuth](builtin-ambientauth) val | [StartProcessAuth](process-startprocessauth) val) * backpressure\_auth: ([AmbientAuth](builtin-ambientauth) val | [ApplyReleaseBackpressureAuth](backpressure-applyreleasebackpressureauth) val) * notifier: [ProcessNotify](process-processnotify) iso * filepath: [FilePath](files-filepath) val * args: [Array](builtin-array)[[String](builtin-string) val] val * vars: [Array](builtin-array)[[String](builtin-string) val] val * wdir: ([FilePath](files-filepath) val | [None](builtin-none) val) = reference * process\_poll\_interval: [U64](builtin-u64) val = call #### Returns * [ProcessMonitor](index) tag^ Public Behaviours ----------------- ### print [[Source]](https://stdlib.ponylang.io/src/process/process_monitor/#L243) Print some bytes and append a newline. ``` be print( data: (String val | Array[U8 val] val)) ``` #### Parameters * data: ([String](builtin-string) val | [Array](builtin-array)[[U8](builtin-u8) val] val) ### write [[Source]](https://stdlib.ponylang.io/src/process/process_monitor/#L252) Write to STDIN of the child process. ``` be write( data: (String val | Array[U8 val] val)) ``` #### Parameters * data: ([String](builtin-string) val | [Array](builtin-array)[[U8](builtin-u8) val] val) ### printv [[Source]](https://stdlib.ponylang.io/src/process/process_monitor/#L260) Print an iterable collection of ByteSeqs. ``` be printv( data: ByteSeqIter val) ``` #### Parameters * data: [ByteSeqIter](builtin-byteseqiter) val ### writev [[Source]](https://stdlib.ponylang.io/src/process/process_monitor/#L269) Write an iterable collection of ByteSeqs. ``` be writev( data: ByteSeqIter val) ``` #### Parameters * data: [ByteSeqIter](builtin-byteseqiter) val ### done\_writing [[Source]](https://stdlib.ponylang.io/src/process/process_monitor/#L277) Set the \_done\_writing flag to true. If \_pending is empty we can close the \_stdin pipe. ``` be done_writing() ``` ### dispose [[Source]](https://stdlib.ponylang.io/src/process/process_monitor/#L288) Terminate child and close down everything. ``` be dispose() ``` ### timer\_notify [[Source]](https://stdlib.ponylang.io/src/process/process_monitor/#L336) Windows IO polling timer has fired ``` be timer_notify() ``` Public Functions ---------------- ### expect [[Source]](https://stdlib.ponylang.io/src/process/process_monitor/#L296) A `stdout` call on the notifier must contain exactly `qty` bytes. If `qty` is zero, the call can contain any amount of data. ``` fun ref expect( qty: USize val = 0) : None val ``` #### Parameters * qty: [USize](builtin-usize) val = 0 #### Returns * [None](builtin-none) val pony Options package Options package =============== The Options package provides support for parsing command line arguments. Deprectation warning -------------------- This package is deprecated and will be removed in a future release. Use the [cli](cli--index) package instead. Example program --------------- ``` use "options" actor Main let _env: Env // Some values we can set via command line options var _a_string: String = "default" var _a_number: USize = 0 var _a_unumber: USize = 0 var _a_float: Float = F64(0.0) new create(env: Env) => _env = env try arguments()? end _env.out.print("The String is " + _a_string) _env.out.print("The Number is " + _a_number.string()) _env.out.print("The UNumber is " + _a_unumber.string()) _env.out.print("The Float is " + _a_float.string()) fun ref arguments() ? => var options = Options(_env.args) options .add("string", "t", StringArgument) .add("number", "i", I64Argument) .add("unumber", "u", U64Argument) .add("float", "c", F64Argument) for option in options do match option | ("string", let arg: String) => _a_string = arg | ("number", let arg: I64) => _a_number = arg.usize() | ("unumber", let arg: U64) => _a_unumber = arg.usize() | ("float", let arg: F64) => _a_float = arg | let err: ParseError => err.report(_env.out) ; usage() ; error end end fun ref usage() => // this exists inside a doc-string to create the docs you are reading // in real code, we would use a single string literal for this but // docstrings are themselves string literals and you can't put a // string literal in a string literal. That would lead to total // protonic reversal. In your own code, use a string literal instead // of string concatenation for this. _env.out.print( "program [OPTIONS]\n" + " --string N a string argument. Defaults to 'default'.\n" + " --number N a number argument. Defaults to 0.\n" + " --unumber N a unsigned number argument. Defaults to 0.\n" + " --float N a floating point argument. Defaults to 0.0.\n" ) ``` Public Types ------------ * [primitive StringArgument](options-stringargument) * [primitive I64Argument](options-i64argument) * [primitive U64Argument](options-u64argument) * [primitive F64Argument](options-f64argument) * [primitive Required](options-required) * [primitive Optional](options-optional) * [primitive UnrecognisedOption](options-unrecognisedoption) * [primitive AmbiguousMatch](options-ambiguousmatch) * [primitive MissingArgument](options-missingargument) * [primitive InvalidArgument](options-invalidargument) * [type ArgumentType](options-argumenttype) * [type ErrorReason](options-errorreason) * [type ParsedOption](options-parsedoption) * [interface ParseError](options-parseerror) * [class Options](options-options) * [primitive EnvVars](options-envvars) pony Unsigned Unsigned ======== [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L841) ``` type Unsigned is (U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) ``` #### Type Alias For * ([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) pony Package Package ======= No package doc string provided for collections. Public Types ------------ * [primitive Sort](collections-sort) * [type Set](collections-set) * [type SetIs](collections-setis) * [class HashSet](collections-hashset) * [class SetValues](collections-setvalues) * [class RingBuffer](collections-ringbuffer) * [class Reverse](collections-reverse) * [class Range](collections-range) * [type Map](collections-map) * [type MapIs](collections-mapis) * [class HashMap](collections-hashmap) * [class MapKeys](collections-mapkeys) * [class MapValues](collections-mapvalues) * [class MapPairs](collections-mappairs) * [class ListNode](collections-listnode) * [class List](collections-list) * [class ListNodes](collections-listnodes) * [class ListValues](collections-listvalues) * [type MinHeap](collections-minheap) * [type MaxHeap](collections-maxheap) * [class BinaryHeap](collections-binaryheap) * [type BinaryHeapPriority](collections-binaryheappriority) * [primitive MinHeapPriority](collections-minheappriority) * [primitive MaxHeapPriority](collections-maxheappriority) * [interface Hashable](collections-hashable) * [interface Hashable64](collections-hashable64) * [interface HashFunction](collections-hashfunction) * [interface HashFunction64](collections-hashfunction64) * [primitive HashEq](collections-hasheq) * [primitive HashEq64](collections-hasheq64) * [primitive HashIs](collections-hashis) * [primitive HashByteSeq](collections-hashbyteseq) * [interface Flag](collections-flag) * [class Flags](collections-flags) pony NoProxy NoProxy ======= [[Source]](https://stdlib.ponylang.io/src/net/proxy/#L5) Default implementation of a proxy that does not alter the supplied `TCPConnectionNotify`. ``` actor MyClient new create(host: String, service: String, proxy: Proxy = NoProxy) => let conn: TCPConnection = TCPConnection.create( env.root as AmbientAuth, proxy.apply(MyConnectionNotify.create()), "localhost", "80") ``` ``` class val NoProxy is Proxy ref ``` #### Implements * [Proxy](net-proxy) ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/net/proxy/#L5) ``` new iso create() : NoProxy iso^ ``` #### Returns * [NoProxy](index) iso^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/net/proxy/#L19) ``` fun box apply( wrap: TCPConnectionNotify iso) : TCPConnectionNotify iso^ ``` #### Parameters * wrap: [TCPConnectionNotify](net-tcpconnectionnotify) iso #### Returns * [TCPConnectionNotify](net-tcpconnectionnotify) iso^ pony Registrar Registrar ========= [[Source]](https://stdlib.ponylang.io/src/bureaucracy/registrar/#L4) A Registrar keeps a map of lookup string to anything. Generally, this is used to keep a directory of long-lived service-providing actors that can be looked up name. ``` actor tag Registrar ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/bureaucracy/registrar/#L4) ``` new tag create() : Registrar tag^ ``` #### Returns * [Registrar](index) tag^ Public Behaviours ----------------- ### update [[Source]](https://stdlib.ponylang.io/src/bureaucracy/registrar/#L12) Add, or change, a lookup mapping. ``` be update( key: String val, value: Any tag) ``` #### Parameters * key: [String](builtin-string) val * value: [Any](builtin-any) tag ### remove [[Source]](https://stdlib.ponylang.io/src/bureaucracy/registrar/#L18) Remove a mapping. This only takes effect if provided key currently maps to the provided value. If the key maps to some other value (perhaps after updating), the mapping won't be removed. ``` be remove( key: String val, value: Any tag) ``` #### Parameters * key: [String](builtin-string) val * value: [Any](builtin-any) tag Public Functions ---------------- ### apply[optional A: [Any](builtin-any) tag] [[Source]](https://stdlib.ponylang.io/src/bureaucracy/registrar/#L30) Lookup by name. Returns a promise that will be fulfilled with the mapped value if it exists and is a subtype of A. Otherwise, the promise will be rejected. ``` fun tag apply[optional A: Any tag]( key: String val) : Promise[A] tag ``` #### Parameters * key: [String](builtin-string) val #### Returns * [Promise](promises-promise)[A] tag pony MaxHeapPriority[A: Comparable[A] #read] MaxHeapPriority[A: [Comparable](builtin-comparable)[A] #read] ============================================================= [[Source]](https://stdlib.ponylang.io/src/collections/heap/#L143) ``` primitive val MaxHeapPriority[A: Comparable[A] #read] is _BinaryHeapPriority[A] val ``` #### Implements * \_BinaryHeapPriority[A] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/heap/#L143) ``` new val create() : MaxHeapPriority[A] val^ ``` #### Returns * [MaxHeapPriority](index)[A] val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/collections/heap/#L144) ``` fun box apply( x: A, y: A) : Bool val ``` #### Parameters * x: A * y: A #### Returns * [Bool](builtin-bool) val ### eq [[Source]](https://stdlib.ponylang.io/src/collections/heap/#L144) ``` fun box eq( that: MaxHeapPriority[A] val) : Bool val ``` #### Parameters * that: [MaxHeapPriority](index)[A] val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/collections/heap/#L144) ``` fun box ne( that: MaxHeapPriority[A] val) : Bool val ``` #### Parameters * that: [MaxHeapPriority](index)[A] val #### Returns * [Bool](builtin-bool) val pony SetIs[A: A] SetIs[A: A] =========== [[Source]](https://stdlib.ponylang.io/src/collections/set/#L3) ``` type SetIs[A: A] is HashSet[A, HashIs[A!] val] ref ``` #### Type Alias For * [HashSet](collections-hashset)[A, [HashIs](collections-hashis)[A!] val] ref pony Custodian Custodian ========= [[Source]](https://stdlib.ponylang.io/src/bureaucracy/custodian/#L21) A Custodian keeps a set of actors to dispose. When the Custodian is disposed, it disposes of the actors in its set and then clears the set. Example program --------------- Imagine you have a program with 3 actors that you need to shutdown when it receives a TERM signal. We can set up a Custodian that knows about each of our actors and when a TERM signal is received, is disposed of. ``` use "bureaucracy" use "signals" actor Actor1 be dispose() => None // dispose of resources here. actor Actor2 be dispose() => None // dispose of resources here. actor Actor3 be dispose() => None // dispose of resources here. actor Main new create(env: Env) => let actor1 = Actor1 let actor2 = Actor2 let actor3 = Actor3 let custodian = Custodian custodian(actor1) custodian(actor2) custodian(actor3) SignalHandler(TermHandler(custodian), Sig.term()) class TermHandler is SignalNotify let _custodian: Custodian new iso create(custodian: Custodian) => _custodian = custodian fun ref apply(count: U32): Bool => _custodian.dispose() true ``` ``` actor tag Custodian ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/bureaucracy/custodian/#L21) ``` new tag create() : Custodian tag^ ``` #### Returns * [Custodian](index) tag^ Public Behaviours ----------------- ### apply [[Source]](https://stdlib.ponylang.io/src/bureaucracy/custodian/#L71) Add an actor to be disposed of. ``` be apply( worker: DisposableActor tag) ``` #### Parameters * worker: [DisposableActor](builtin-disposableactor) tag ### remove [[Source]](https://stdlib.ponylang.io/src/bureaucracy/custodian/#L77) Removes an actor from the set of things to be disposed. ``` be remove( worker: DisposableActor tag) ``` #### Parameters * worker: [DisposableActor](builtin-disposableactor) tag ### dispose [[Source]](https://stdlib.ponylang.io/src/bureaucracy/custodian/#L83) Dispose of the actors in the set and then clear the set. ``` be dispose() ``` pony Error Error ===== [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L107) ``` primitive val Error ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L107) ``` new val create() : Error val^ ``` #### Returns * [Error](index) val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L108) ``` fun box apply() : U32 val ``` #### Returns * [U32](builtin-u32) val ### eq [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L108) ``` fun box eq( that: Error val) : Bool val ``` #### Parameters * that: [Error](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L108) ``` fun box ne( that: Error val) : Bool val ``` #### Parameters * that: [Error](index) val #### Returns * [Bool](builtin-bool) val pony F64Argument F64Argument =========== [[Source]](https://stdlib.ponylang.io/src/options/options/#L72) ``` primitive val F64Argument ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/options/options/#L72) ``` new val create() : F64Argument val^ ``` #### Returns * [F64Argument](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/options/options/#L73) ``` fun box eq( that: F64Argument val) : Bool val ``` #### Parameters * that: [F64Argument](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/options/options/#L73) ``` fun box ne( that: F64Argument val) : Bool val ``` #### Parameters * that: [F64Argument](index) val #### Returns * [Bool](builtin-bool) val pony OverheadBenchmark OverheadBenchmark ================= [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L79) Default benchmark for measuring synchronous overhead. ``` class iso OverheadBenchmark is MicroBenchmark iso ``` #### Implements * [MicroBenchmark](ponybench-microbenchmark) iso Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L79) ``` new iso create() : OverheadBenchmark iso^ ``` #### Returns * [OverheadBenchmark](index) iso^ Public Functions ---------------- ### name [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L83) ``` fun box name() : String val ``` #### Returns * [String](builtin-string) val ### apply [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L86) ``` fun ref apply() : None val ``` #### Returns * [None](builtin-none) val ### config [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L20) ``` fun box config() : BenchConfig val ``` #### Returns * [BenchConfig](ponybench-benchconfig) val ### overhead [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L21) ``` fun box overhead() : MicroBenchmark iso^ ``` #### Returns * [MicroBenchmark](ponybench-microbenchmark) iso^ ### before [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L22) ``` fun ref before() : None val ? ``` #### Returns * [None](builtin-none) val ? ### before\_iteration [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L23) ``` fun ref before_iteration() : None val ? ``` #### Returns * [None](builtin-none) val ? ### after [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L25) ``` fun ref after() : None val ? ``` #### Returns * [None](builtin-none) val ? ### after\_iteration [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L26) ``` fun ref after_iteration() : None val ? ``` #### Returns * [None](builtin-none) val ?
programming_docs
pony FormatUTF32 FormatUTF32 =========== [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L5) ``` primitive val FormatUTF32 is FormatSpec val ``` #### Implements * [FormatSpec](format-formatspec) val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L5) ``` new val create() : FormatUTF32 val^ ``` #### Returns * [FormatUTF32](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L6) ``` fun box eq( that: FormatUTF32 val) : Bool val ``` #### Parameters * that: [FormatUTF32](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L6) ``` fun box ne( that: FormatUTF32 val) : Bool val ``` #### Parameters * that: [FormatUTF32](index) val #### Returns * [Bool](builtin-bool) val pony UDPNotify UDPNotify ========= [[Source]](https://stdlib.ponylang.io/src/net/udp_notify/#L1) Notifications for UDP connections. For an example of using this class please see the documentatoin for the `UDPSocket` actor. ``` interface ref UDPNotify ``` Public Functions ---------------- ### listening [[Source]](https://stdlib.ponylang.io/src/net/udp_notify/#L8) Called when the socket has been bound to an address. ``` fun ref listening( sock: UDPSocket ref) : None val ``` #### Parameters * sock: [UDPSocket](net-udpsocket) ref #### Returns * [None](builtin-none) val ### not\_listening [[Source]](https://stdlib.ponylang.io/src/net/udp_notify/#L14) Called if it wasn't possible to bind the socket to an address. It is expected to implement proper error handling. You need to opt in to ignoring errors, which can be implemented like this: ``` fun ref not_listening(sock: UDPSocket ref) => None ``` ``` fun ref not_listening( sock: UDPSocket ref) : None val ``` #### Parameters * sock: [UDPSocket](net-udpsocket) ref #### Returns * [None](builtin-none) val ### received [[Source]](https://stdlib.ponylang.io/src/net/udp_notify/#L27) Called when new data is received on the socket. ``` fun ref received( sock: UDPSocket ref, data: Array[U8 val] iso, from: NetAddress val) : None val ``` #### Parameters * sock: [UDPSocket](net-udpsocket) ref * data: [Array](builtin-array)[[U8](builtin-u8) val] iso * from: [NetAddress](net-netaddress) val #### Returns * [None](builtin-none) val ### closed [[Source]](https://stdlib.ponylang.io/src/net/udp_notify/#L37) Called when the socket is closed. ``` fun ref closed( sock: UDPSocket ref) : None val ``` #### Parameters * sock: [UDPSocket](net-udpsocket) ref #### Returns * [None](builtin-none) val pony VecValues[A: Any #share] VecValues[A: [Any](builtin-any) #share] ======================================= [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L271) ``` class ref VecValues[A: Any #share] ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L274) ``` new ref create( v: Vec[A] val) : VecValues[A] ref^ ``` #### Parameters * v: [Vec](collections-persistent-vec)[A] val #### Returns * [VecValues](index)[A] ref^ Public Functions ---------------- ### has\_next [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L276) ``` fun box has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### next [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L278) ``` fun ref next() : val->A ? ``` #### Returns * val->A ? pony Reject[A: Any #share] Reject[A: [Any](builtin-any) #share] ==================================== [[Source]](https://stdlib.ponylang.io/src/promises/fulfill/#L10) A function on A that is called when a promise is rejected. ``` interface iso Reject[A: Any #share] ``` Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/promises/fulfill/#L14) ``` fun ref apply() : A ? ``` #### Returns * A ? pony U32 U32 === [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L145) ``` primitive val U32 is UnsignedInteger[U32 val] val ``` #### Implements * [UnsignedInteger](builtin-unsignedinteger)[[U32](index) val] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L146) ``` new val create( value: U32 val) : U32 val^ ``` #### Parameters * value: [U32](index) val #### Returns * [U32](index) val^ ### from[A: (([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](builtin-i32) val | [I64](builtin-i64) val | [I128](builtin-i128) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val | [U8](builtin-u8) val | [U16](builtin-u16) val | [U32](index) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val | [F32](builtin-f32) val | [F64](builtin-f64) val) & [Real](builtin-real)[A] val)] [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L147) ``` new val from[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[A] val)]( a: A) : U32 val^ ``` #### Parameters * a: A #### Returns * [U32](index) val^ ### min\_value [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L149) ``` new val min_value() : U32 val^ ``` #### Returns * [U32](index) val^ ### max\_value [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L150) ``` new val max_value() : U32 val^ ``` #### Returns * [U32](index) val^ Public Functions ---------------- ### next\_pow2 [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L152) ``` fun box next_pow2() : U32 val ``` #### Returns * [U32](index) val ### abs [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L156) ``` fun box abs() : U32 val ``` #### Returns * [U32](index) val ### bit\_reverse [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L157) ``` fun box bit_reverse() : U32 val ``` #### Returns * [U32](index) val ### bswap [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L158) ``` fun box bswap() : U32 val ``` #### Returns * [U32](index) val ### popcount [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L159) ``` fun box popcount() : U32 val ``` #### Returns * [U32](index) val ### clz [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L160) ``` fun box clz() : U32 val ``` #### Returns * [U32](index) val ### ctz [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L161) ``` fun box ctz() : U32 val ``` #### Returns * [U32](index) val ### clz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L163) Unsafe operation. If this is 0, the result is undefined. ``` fun box clz_unsafe() : U32 val ``` #### Returns * [U32](index) val ### ctz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L170) Unsafe operation. If this is 0, the result is undefined. ``` fun box ctz_unsafe() : U32 val ``` #### Returns * [U32](index) val ### bitwidth [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L177) ``` fun box bitwidth() : U32 val ``` #### Returns * [U32](index) val ### bytewidth [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L179) ``` fun box bytewidth() : USize val ``` #### Returns * [USize](builtin-usize) val ### min [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L181) ``` fun box min( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### max [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L182) ``` fun box max( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### addc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L184) ``` fun box addc( y: U32 val) : (U32 val , Bool val) ``` #### Parameters * y: [U32](index) val #### Returns * ([U32](index) val , [Bool](builtin-bool) val) ### subc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L187) ``` fun box subc( y: U32 val) : (U32 val , Bool val) ``` #### Parameters * y: [U32](index) val #### Returns * ([U32](index) val , [Bool](builtin-bool) val) ### mulc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L190) ``` fun box mulc( y: U32 val) : (U32 val , Bool val) ``` #### Parameters * y: [U32](index) val #### Returns * ([U32](index) val , [Bool](builtin-bool) val) ### divc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L193) ``` fun box divc( y: U32 val) : (U32 val , Bool val) ``` #### Parameters * y: [U32](index) val #### Returns * ([U32](index) val , [Bool](builtin-bool) val) ### remc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L196) ``` fun box remc( y: U32 val) : (U32 val , Bool val) ``` #### Parameters * y: [U32](index) val #### Returns * ([U32](index) val , [Bool](builtin-bool) val) ### add\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L199) ``` fun box add_partial( y: U32 val) : U32 val ? ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ? ### sub\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L202) ``` fun box sub_partial( y: U32 val) : U32 val ? ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ? ### mul\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L205) ``` fun box mul_partial( y: U32 val) : U32 val ? ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ? ### div\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L208) ``` fun box div_partial( y: U32 val) : U32 val ? ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ? ### rem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L211) ``` fun box rem_partial( y: U32 val) : U32 val ? ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ? ### divrem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L214) ``` fun box divrem_partial( y: U32 val) : (U32 val , U32 val) ? ``` #### Parameters * y: [U32](index) val #### Returns * ([U32](index) val , [U32](index) val) ? ### shl ``` fun box shl( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### shr ``` fun box shr( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### fld ``` fun box fld( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### fldc ``` fun box fldc( y: U32 val) : (U32 val , Bool val) ``` #### Parameters * y: [U32](index) val #### Returns * ([U32](index) val , [Bool](builtin-bool) val) ### fld\_partial ``` fun box fld_partial( y: U32 val) : U32 val ? ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ? ### fld\_unsafe ``` fun box fld_unsafe( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### mod ``` fun box mod( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### modc ``` fun box modc( y: U32 val) : (U32 val , Bool val) ``` #### Parameters * y: [U32](index) val #### Returns * ([U32](index) val , [Bool](builtin-bool) val) ### mod\_partial ``` fun box mod_partial( y: U32 val) : U32 val ? ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ? ### mod\_unsafe ``` fun box mod_unsafe( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### shl\_unsafe ``` fun box shl_unsafe( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### shr\_unsafe ``` fun box shr_unsafe( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### rotl ``` fun box rotl( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### rotr ``` fun box rotr( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### string ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### add\_unsafe ``` fun box add_unsafe( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### sub\_unsafe ``` fun box sub_unsafe( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### mul\_unsafe ``` fun box mul_unsafe( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### div\_unsafe ``` fun box div_unsafe( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### divrem\_unsafe ``` fun box divrem_unsafe( y: U32 val) : (U32 val , U32 val) ``` #### Parameters * y: [U32](index) val #### Returns * ([U32](index) val , [U32](index) val) ### rem\_unsafe ``` fun box rem_unsafe( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### neg\_unsafe ``` fun box neg_unsafe() : U32 val ``` #### Returns * [U32](index) val ### op\_and ``` fun box op_and( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### op\_or ``` fun box op_or( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### op\_xor ``` fun box op_xor( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### op\_not ``` fun box op_not() : U32 val ``` #### Returns * [U32](index) val ### add ``` fun box add( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### sub ``` fun box sub( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### mul ``` fun box mul( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### div ``` fun box div( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### divrem ``` fun box divrem( y: U32 val) : (U32 val , U32 val) ``` #### Parameters * y: [U32](index) val #### Returns * ([U32](index) val , [U32](index) val) ### rem ``` fun box rem( y: U32 val) : U32 val ``` #### Parameters * y: [U32](index) val #### Returns * [U32](index) val ### neg ``` fun box neg() : U32 val ``` #### Returns * [U32](index) val ### eq ``` fun box eq( y: U32 val) : Bool val ``` #### Parameters * y: [U32](index) val #### Returns * [Bool](builtin-bool) val ### ne ``` fun box ne( y: U32 val) : Bool val ``` #### Parameters * y: [U32](index) val #### Returns * [Bool](builtin-bool) val ### lt ``` fun box lt( y: U32 val) : Bool val ``` #### Parameters * y: [U32](index) val #### Returns * [Bool](builtin-bool) val ### le ``` fun box le( y: U32 val) : Bool val ``` #### Parameters * y: [U32](index) val #### Returns * [Bool](builtin-bool) val ### ge ``` fun box ge( y: U32 val) : Bool val ``` #### Parameters * y: [U32](index) val #### Returns * [Bool](builtin-bool) val ### gt ``` fun box gt( y: U32 val) : Bool val ``` #### Parameters * y: [U32](index) val #### Returns * [Bool](builtin-bool) val ### hash ``` fun box hash() : USize val ``` #### Returns * [USize](builtin-usize) val ### hash64 ``` fun box hash64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### i8 ``` fun box i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 ``` fun box i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 ``` fun box i32() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64 ``` fun box i64() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128 ``` fun box i128() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong ``` fun box ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize ``` fun box isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8 ``` fun box u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 ``` fun box u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 ``` fun box u32() : U32 val ``` #### Returns * [U32](index) val ### u64 ``` fun box u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 ``` fun box u128() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong ``` fun box ulong() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize ``` fun box usize() : USize val ``` #### Returns * [USize](builtin-usize) val ### f32 ``` fun box f32() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64 ``` fun box f64() : F64 val ``` #### Returns * [F64](builtin-f64) val ### i8\_unsafe ``` fun box i8_unsafe() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16\_unsafe ``` fun box i16_unsafe() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32\_unsafe ``` fun box i32_unsafe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64\_unsafe ``` fun box i64_unsafe() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128\_unsafe ``` fun box i128_unsafe() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong\_unsafe ``` fun box ilong_unsafe() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize\_unsafe ``` fun box isize_unsafe() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8\_unsafe ``` fun box u8_unsafe() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16\_unsafe ``` fun box u16_unsafe() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32\_unsafe ``` fun box u32_unsafe() : U32 val ``` #### Returns * [U32](index) val ### u64\_unsafe ``` fun box u64_unsafe() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128\_unsafe ``` fun box u128_unsafe() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong\_unsafe ``` fun box ulong_unsafe() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize\_unsafe ``` fun box usize_unsafe() : USize val ``` #### Returns * [USize](builtin-usize) val ### f32\_unsafe ``` fun box f32_unsafe() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64\_unsafe ``` fun box f64_unsafe() : F64 val ``` #### Returns * [F64](builtin-f64) val ### compare ``` fun box compare( that: U32 val) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [U32](index) val #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val) pony DebugStream DebugStream =========== [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L22) ``` type DebugStream is (DebugOut val | DebugErr val) ``` #### Type Alias For * ([DebugOut](debug-debugout) val | [DebugErr](debug-debugerr) val)
programming_docs
pony FormatFix FormatFix ========= [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L29) ``` primitive val FormatFix is FormatSpec val ``` #### Implements * [FormatSpec](format-formatspec) val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L29) ``` new val create() : FormatFix val^ ``` #### Returns * [FormatFix](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L30) ``` fun box eq( that: FormatFix val) : Bool val ``` #### Parameters * that: [FormatFix](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L30) ``` fun box ne( that: FormatFix val) : Bool val ``` #### Parameters * that: [FormatFix](index) val #### Returns * [Bool](builtin-bool) val pony FileTruncate FileTruncate ============ [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L42) ``` primitive val FileTruncate ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L42) ``` new val create() : FileTruncate val^ ``` #### Returns * [FileTruncate](index) val^ Public Functions ---------------- ### value [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L43) ``` fun box value() : U32 val ``` #### Returns * [U32](builtin-u32) val ### eq [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L43) ``` fun box eq( that: FileTruncate val) : Bool val ``` #### Parameters * that: [FileTruncate](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L43) ``` fun box ne( that: FileTruncate val) : Bool val ``` #### Parameters * that: [FileTruncate](index) val #### Returns * [Bool](builtin-bool) val pony WaitpidError WaitpidError ============ [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L47) ``` primitive val WaitpidError ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L47) ``` new val create() : WaitpidError val^ ``` #### Returns * [WaitpidError](index) val^ Public Functions ---------------- ### string [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L48) ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### eq [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L48) ``` fun box eq( that: WaitpidError val) : Bool val ``` #### Parameters * that: [WaitpidError](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L48) ``` fun box ne( that: WaitpidError val) : Bool val ``` #### Parameters * that: [WaitpidError](index) val #### Returns * [Bool](builtin-bool) val pony FormatGeneral FormatGeneral ============= [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L31) ``` primitive val FormatGeneral is FormatSpec val ``` #### Implements * [FormatSpec](format-formatspec) val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L31) ``` new val create() : FormatGeneral val^ ``` #### Returns * [FormatGeneral](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L32) ``` fun box eq( that: FormatGeneral val) : Bool val ``` #### Parameters * that: [FormatGeneral](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L32) ``` fun box ne( that: FormatGeneral val) : Bool val ``` #### Parameters * that: [FormatGeneral](index) val #### Returns * [Bool](builtin-bool) val pony ProcessErrorType ProcessErrorType ================ [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L26) ``` type ProcessErrorType is (ExecveError val | PipeError val | ForkError val | WaitpidError val | WriteError val | KillError val | CapError val | ChdirError val | UnknownError val) ``` #### Type Alias For * ([ExecveError](process-execveerror) val | [PipeError](process-pipeerror) val | [ForkError](process-forkerror) val | [WaitpidError](process-waitpiderror) val | [WriteError](process-writeerror) val | [KillError](process-killerror) val | [CapError](process-caperror) val | [ChdirError](process-chdirerror) val | [UnknownError](process-unknownerror) val) pony IniParse IniParse ======== [[Source]](https://stdlib.ponylang.io/src/ini/ini_map/#L5) This is used to parse INI formatted text as a nested map of strings. ``` primitive val IniParse ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/ini/ini_map/#L5) ``` new val create() : IniParse val^ ``` #### Returns * [IniParse](index) val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/ini/ini_map/#L9) This accepts a string iterator and returns a nested map of strings. If parsing fails, an error is raised. ``` fun box apply( lines: Iterator[String val] ref) : HashMap[String val, HashMap[String val, String val, HashEq[String val] val] ref, HashEq[String val] val] ref^ ? ``` #### Parameters * lines: [Iterator](builtin-iterator)[[String](builtin-string) val] ref #### Returns * [HashMap](collections-hashmap)[[String](builtin-string) val, [HashMap](collections-hashmap)[[String](builtin-string) val, [String](builtin-string) val, [HashEq](collections-hasheq)[[String](builtin-string) val] val] ref, [HashEq](collections-hasheq)[[String](builtin-string) val] val] ref^ ? ### eq [[Source]](https://stdlib.ponylang.io/src/ini/ini_map/#L9) ``` fun box eq( that: IniParse val) : Bool val ``` #### Parameters * that: [IniParse](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/ini/ini_map/#L9) ``` fun box ne( that: IniParse val) : Bool val ``` #### Parameters * that: [IniParse](index) val #### Returns * [Bool](builtin-bool) val pony Random Random ====== [[Source]](https://stdlib.ponylang.io/src/random/random/#L21) The `Random` trait should be implemented by all random number generators. The only method you need to implement is `fun ref next(): 64`. Once that method has been implemented, the `Random` trait provides default implementations of conversions to other number types. ``` trait ref Random ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/random/random/#L28) Create with the specified seed. Returned values are deterministic for a given seed. ``` new ref create( x: U64 val = 5489, y: U64 val = 0) : Random ref^ ``` #### Parameters * x: [U64](builtin-u64) val = 5489 * y: [U64](builtin-u64) val = 0 #### Returns * [Random](index) ref^ Public Functions ---------------- ### has\_next [[Source]](https://stdlib.ponylang.io/src/random/random/#L34) If used as an iterator, this always has another value. ``` fun tag has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### next [[Source]](https://stdlib.ponylang.io/src/random/random/#L40) A random integer in [0, 2^64) ``` fun ref next() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u8 [[Source]](https://stdlib.ponylang.io/src/random/random/#L45) A random integer in [0, 2^8) ``` fun ref u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 [[Source]](https://stdlib.ponylang.io/src/random/random/#L51) A random integer in [0, 2^16) ``` fun ref u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 [[Source]](https://stdlib.ponylang.io/src/random/random/#L57) A random integer in [0, 2^32) ``` fun ref u32() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64 [[Source]](https://stdlib.ponylang.io/src/random/random/#L63) A random integer in [0, 2^64) ``` fun ref u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 [[Source]](https://stdlib.ponylang.io/src/random/random/#L69) A random integer in [0, 2^128) ``` fun ref u128() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong [[Source]](https://stdlib.ponylang.io/src/random/random/#L75) A random integer in [0, ULong.max\_value()] ``` fun ref ulong() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize [[Source]](https://stdlib.ponylang.io/src/random/random/#L85) A random integer in [0, USize.max\_value()] ``` fun ref usize() : USize val ``` #### Returns * [USize](builtin-usize) val ### i8 [[Source]](https://stdlib.ponylang.io/src/random/random/#L95) A random integer in [-2^7, 2^7) ``` fun ref i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 [[Source]](https://stdlib.ponylang.io/src/random/random/#L101) A random integer in [-2^15, 2^15) ``` fun ref i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 [[Source]](https://stdlib.ponylang.io/src/random/random/#L107) A random integer in [-2^31, 2^31) ``` fun ref i32() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64 [[Source]](https://stdlib.ponylang.io/src/random/random/#L113) A random integer in [-2^63, 2^63) ``` fun ref i64() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128 [[Source]](https://stdlib.ponylang.io/src/random/random/#L119) A random integer in [-2^127, 2^127) ``` fun ref i128() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong [[Source]](https://stdlib.ponylang.io/src/random/random/#L125) A random integer in [ILong.min\_value(), ILong.max\_value()] ``` fun ref ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize [[Source]](https://stdlib.ponylang.io/src/random/random/#L131) A random integer in [ISize.min\_value(), ISize.max\_value()] ``` fun ref isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### int\_fp\_mult[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] [[Source]](https://stdlib.ponylang.io/src/random/random/#L137) A random integer in [0, n) ``` fun ref int_fp_mult[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### int[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] [[Source]](https://stdlib.ponylang.io/src/random/random/#L143) A random integer in [0, n) Uses fixed-point inversion if platform supports native 128 bit operations otherwise uses floating-point multiplication. ``` fun ref int[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### int\_unbiased[optional N: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Real](builtin-real)[N] val)] [[Source]](https://stdlib.ponylang.io/src/random/random/#L159) A random integer in [0, n) Not biased with small values of `n` like `int`. ``` fun ref int_unbiased[optional N: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Real[N] val)]( n: N) : N ``` #### Parameters * n: N #### Returns * N ### real [[Source]](https://stdlib.ponylang.io/src/random/random/#L195) A random number in [0, 1) ``` fun ref real() : F64 val ``` #### Returns * [F64](builtin-f64) val ### shuffle[A: A] [[Source]](https://stdlib.ponylang.io/src/random/random/#L201) Shuffle the elements of the array into a random order, mutating the array. ``` fun ref shuffle[A: A]( array: Array[A] ref) : None val ``` #### Parameters * array: [Array](builtin-array)[A] ref #### Returns * [None](builtin-none) val pony Debug package Debug package ============= Provides facilities to create output to either `STDOUT` or `STDERR` that will only appear when the platform is debug configured. To create a binary with debug configured, pass the `-d` flag to `ponyc` when compiling e.g.: `ponyc -d` Example code ------------ ``` actor Main new create(env: Env) => Debug.out("This will only be seen when configured for debug info") env.out.print("This will always be seen") ``` Public Types ------------ * [primitive DebugOut](debug-debugout) * [primitive DebugErr](debug-debugerr) * [type DebugStream](debug-debugstream) * [primitive Debug](debug-debug) pony Package Package ======= No package doc string provided for strings. Public Types ------------ * [primitive CommonPrefix](strings-commonprefix) pony Platform Platform ======== [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L1) ``` primitive val Platform ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L1) ``` new val create() : Platform val^ ``` #### Returns * [Platform](index) val^ Public Functions ---------------- ### bsd [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L2) ``` fun box bsd() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### freebsd [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L3) ``` fun box freebsd() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### dragonfly [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L4) ``` fun box dragonfly() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### openbsd [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L5) ``` fun box openbsd() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### linux [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L6) ``` fun box linux() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### osx [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L7) ``` fun box osx() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### posix [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L8) ``` fun box posix() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### windows [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L9) ``` fun box windows() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### x86 [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L11) ``` fun box x86() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### arm [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L12) ``` fun box arm() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### lp64 [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L14) ``` fun box lp64() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### llp64 [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L15) ``` fun box llp64() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### ilp32 [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L16) ``` fun box ilp32() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### bigendian [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L18) ``` fun box bigendian() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### littleendian [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L19) ``` fun box littleendian() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### native128 [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L21) ``` fun box native128() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### debug [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L22) ``` fun box debug() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### eq [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L2) ``` fun box eq( that: Platform val) : Bool val ``` #### Parameters * that: [Platform](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/builtin/platform/#L2) ``` fun box ne( that: Platform val) : Bool val ``` #### Parameters * that: [Platform](index) val #### Returns * [Bool](builtin-bool) val pony Iterator[A: A] Iterator[A: A] ============== [[Source]](https://stdlib.ponylang.io/src/builtin/iterator/#L1) Iterators generate a series of values, one value at a time on each call to `next()`. An Iterator is considered exhausted, once its `has_next()` method returns `false`. Thus every call to `next()` should be preceeded with a call to `has_next()` to check for exhaustiveness. Usage ----- Given the rules for using Iterators mentioned above, basic usage of an iterator looks like this: ``` while iterator.has_next() do let elem = iterator.next()? // do something with elem end ``` The `For`-loop provides a more concise way of iteration: ``` for elem in iterator do // do something with elem end ``` Iteration using `While` is more flexible as it allows to continue iterating if a call to `next()` errors. The `For`-loop does not allow this. Implementing Iterators ---------------------- Iterator implementations need to adhere to the following rules to be considered well-behaved: * If the Iterator is exhausted, `has_next()` needs to return `false`. * Once `has_next()` returned `false` it is not allowed to switch back to `true` (Unless the Iterator supports rewinding) * `has_next()` does not change its returned value if `next()` has not been called. That means, that between two calls to `next()` any number of calls to `has_next()` need to return the same value. (Unless the Iterator supports rewinding) * A call to `next()` erroring does not necessarily denote exhaustiveness. ### Example ``` // Generates values from `from` to 0 class ref Countdown is Iterator[USize] var _cur: USize var _has_next: Bool = true new ref create(from: USize) => _cur = from fun ref has_next(): Bool => _has_next fun ref next(): USize => let elem = _cur = _cur - 1 if elem == 0 then _has_next = false end elem ``` ``` interface ref Iterator[A: A] ``` Public Functions ---------------- ### has\_next [[Source]](https://stdlib.ponylang.io/src/builtin/iterator/#L69) Returns `true` if this Iterator is not yet exhausted. That means that a value returned from a subsequent call to `next()` is a valid part of this iterator. Returns `false` if this Iterator is exhausted. The behavior of `next()` after this function returned `false` is undefined, it might throw an error or return values which are not part of this Iterator. ``` fun ref has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### next [[Source]](https://stdlib.ponylang.io/src/builtin/iterator/#L81) Generate the next value. This might error, which does not necessarily mean that the Iterator is exhausted. ``` fun ref next() : A ? ``` #### Returns * A ? pony Hashable Hashable ======== [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L1) Anything with a hash method is hashable. ``` interface ref Hashable ``` Public Functions ---------------- ### hash [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L5) ``` fun box hash() : USize val ``` #### Returns * [USize](builtin-usize) val
programming_docs
pony VecKeys[A: Any #share] VecKeys[A: [Any](builtin-any) #share] ===================================== [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L262) ``` class ref VecKeys[A: Any #share] ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L265) ``` new ref create( v: Vec[A] val) : VecKeys[A] ref^ ``` #### Parameters * v: [Vec](collections-persistent-vec)[A] val #### Returns * [VecKeys](index)[A] ref^ Public Functions ---------------- ### has\_next [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L267) ``` fun box has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### next [[Source]](https://stdlib.ponylang.io/src/collections-persistent/vec/#L269) ``` fun ref next() : USize val ? ``` #### Returns * [USize](builtin-usize) val ? pony IniNoDelimiter IniNoDelimiter ============== [[Source]](https://stdlib.ponylang.io/src/ini/ini/#L32) ``` primitive val IniNoDelimiter ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/ini/ini/#L32) ``` new val create() : IniNoDelimiter val^ ``` #### Returns * [IniNoDelimiter](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/ini/ini/#L34) ``` fun box eq( that: IniNoDelimiter val) : Bool val ``` #### Parameters * that: [IniNoDelimiter](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/ini/ini/#L34) ``` fun box ne( that: IniNoDelimiter val) : Bool val ``` #### Parameters * that: [IniNoDelimiter](index) val #### Returns * [Bool](builtin-bool) val pony Sort[A: Seq[B] ref, B: Comparable[B] #read] Sort[A: [Seq](builtin-seq)[B] ref, B: [Comparable](builtin-comparable)[B] #read] ================================================================================ [[Source]](https://stdlib.ponylang.io/src/collections/sort/#L1) Implementation of dual-pivot quicksort. It operates in-place on the provided Seq, using a small amount of additional memory. The nature of the element-realation is expressed via the supplied comparator. (The following is paraphrased from [Wikipedia](https://en.wikipedia.org/wiki/Quicksort).) Quicksort is a common implementation of a sort algorithm which can sort items of any type for which a "less-than" relation (formally, a total order) is defined. On average, the algorithm takes O(n log n) comparisons to sort n items. In the worst case, it makes O(n2) comparisons, though this behavior is rare. Multi-pivot implementations (of which dual-pivot is one) make efficient use of modern processor caches. Example program --------------- The following takes an reverse-alphabetical array of Strings ("third", "second", "first"), and sorts it in place alphabetically using the default String Comparator. It outputs: > first second third > > ``` use "collections" actor Main new create(env:Env) => let array = [ "third"; "second"; "first" ] let sorted_array = Sort[Array[String], String](array) for e in sorted_array.values() do env.out.print(e) // prints "first \n second \n third" end ``` ``` primitive val Sort[A: Seq[B] ref, B: Comparable[B] #read] ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/sort/#L1) ``` new val create() : Sort[A, B] val^ ``` #### Returns * [Sort](index)[A, B] val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/collections/sort/#L38) Sort the given seq. ``` fun box apply( a: A) : A^ ``` #### Parameters * a: A #### Returns * A^ ### eq [[Source]](https://stdlib.ponylang.io/src/collections/sort/#L38) ``` fun box eq( that: Sort[A, B] val) : Bool val ``` #### Parameters * that: [Sort](index)[A, B] val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/collections/sort/#L38) ``` fun box ne( that: Sort[A, B] val) : Bool val ``` #### Parameters * that: [Sort](index)[A, B] val #### Returns * [Bool](builtin-bool) val pony HashByteSeq HashByteSeq =========== [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L103) Hash and equality functions for arbitrary ByteSeq. ``` primitive val HashByteSeq is HashFunction[(String box | Array[U8 val] box)] val, HashFunction64[(String box | Array[U8 val] box)] val ``` #### Implements * [HashFunction](collections-hashfunction)[([String](builtin-string) box | [Array](builtin-array)[[U8](builtin-u8) val] box)] val * [HashFunction64](collections-hashfunction64)[([String](builtin-string) box | [Array](builtin-array)[[U8](builtin-u8) val] box)] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L103) ``` new val create() : HashByteSeq val^ ``` #### Returns * [HashByteSeq](index) val^ Public Functions ---------------- ### hash [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L108) ``` fun box hash( x: (String box | Array[U8 val] box)) : USize val ``` #### Parameters * x: ([String](builtin-string) box | [Array](builtin-array)[[U8](builtin-u8) val] box) #### Returns * [USize](builtin-usize) val ### hash64 [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L111) ``` fun box hash64( x: (String box | Array[U8 val] box)) : U64 val ``` #### Parameters * x: ([String](builtin-string) box | [Array](builtin-array)[[U8](builtin-u8) val] box) #### Returns * [U64](builtin-u64) val ### eq [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L114) ``` fun box eq( x: (String box | Array[U8 val] box), y: (String box | Array[U8 val] box)) : Bool val ``` #### Parameters * x: ([String](builtin-string) box | [Array](builtin-array)[[U8](builtin-u8) val] box) * y: ([String](builtin-string) box | [Array](builtin-array)[[U8](builtin-u8) val] box) #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L108) ``` fun box ne( that: HashByteSeq val) : Bool val ``` #### Parameters * that: [HashByteSeq](index) val #### Returns * [Bool](builtin-bool) val pony AlignRight AlignRight ========== [[Source]](https://stdlib.ponylang.io/src/format/align/#L2) ``` primitive val AlignRight ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/format/align/#L2) ``` new val create() : AlignRight val^ ``` #### Returns * [AlignRight](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/format/align/#L3) ``` fun box eq( that: AlignRight val) : Bool val ``` #### Parameters * that: [AlignRight](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/format/align/#L3) ``` fun box ne( that: AlignRight val) : Bool val ``` #### Parameters * that: [AlignRight](index) val #### Returns * [Bool](builtin-bool) val pony Fact Fact ==== [[Source]](https://stdlib.ponylang.io/src/assert/assert/#L19) This is an assertion that is always enabled. If the test is false, it will print any supplied error message to stderr and raise an error. ``` primitive val Fact ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/assert/assert/#L19) ``` new val create() : Fact val^ ``` #### Returns * [Fact](index) val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/assert/assert/#L24) ``` fun box apply( test: Bool val, msg: String val = "") : None val ? ``` #### Parameters * test: [Bool](builtin-bool) val * msg: [String](builtin-string) val = "" #### Returns * [None](builtin-none) val ? ### eq [[Source]](https://stdlib.ponylang.io/src/assert/assert/#L24) ``` fun box eq( that: Fact val) : Bool val ``` #### Parameters * that: [Fact](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/assert/assert/#L24) ``` fun box ne( that: Fact val) : Bool val ``` #### Parameters * that: [Fact](index) val #### Returns * [Bool](builtin-bool) val pony ULong ULong ===== [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L296) ``` primitive val ULong is UnsignedInteger[ULong val] val ``` #### Implements * [UnsignedInteger](builtin-unsignedinteger)[[ULong](index) val] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L297) ``` new val create( value: ULong val) : ULong val^ ``` #### Parameters * value: [ULong](index) val #### Returns * [ULong](index) val^ ### from[A: (([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](builtin-i32) val | [I64](builtin-i64) val | [I128](builtin-i128) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val | [U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](index) val | [USize](builtin-usize) val | [F32](builtin-f32) val | [F64](builtin-f64) val) & [Real](builtin-real)[A] val)] [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L298) ``` new val from[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[A] val)]( a: A) : ULong val^ ``` #### Parameters * a: A #### Returns * [ULong](index) val^ ### min\_value [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L300) ``` new val min_value() : ULong val^ ``` #### Returns * [ULong](index) val^ ### max\_value [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L302) ``` new val max_value() : ULong val^ ``` #### Returns * [ULong](index) val^ Public Functions ---------------- ### next\_pow2 [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L309) ``` fun box next_pow2() : ULong val ``` #### Returns * [ULong](index) val ### abs [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L313) ``` fun box abs() : ULong val ``` #### Returns * [ULong](index) val ### bit\_reverse [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L315) ``` fun box bit_reverse() : ULong val ``` #### Returns * [ULong](index) val ### bswap [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L322) ``` fun box bswap() : ULong val ``` #### Returns * [ULong](index) val ### popcount [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L329) ``` fun box popcount() : ULong val ``` #### Returns * [ULong](index) val ### clz [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L336) ``` fun box clz() : ULong val ``` #### Returns * [ULong](index) val ### ctz [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L343) ``` fun box ctz() : ULong val ``` #### Returns * [ULong](index) val ### clz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L350) Unsafe operation. If this is 0, the result is undefined. ``` fun box clz_unsafe() : ULong val ``` #### Returns * [ULong](index) val ### ctz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L361) Unsafe operation. If this is 0, the result is undefined. ``` fun box ctz_unsafe() : ULong val ``` #### Returns * [ULong](index) val ### bitwidth [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L372) ``` fun box bitwidth() : ULong val ``` #### Returns * [ULong](index) val ### bytewidth [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L374) ``` fun box bytewidth() : USize val ``` #### Returns * [USize](builtin-usize) val ### min [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L376) ``` fun box min( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### max [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L377) ``` fun box max( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### hash [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L379) ``` fun box hash() : USize val ``` #### Returns * [USize](builtin-usize) val ### addc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L386) ``` fun box addc( y: ULong val) : (ULong val , Bool val) ``` #### Parameters * y: [ULong](index) val #### Returns * ([ULong](index) val , [Bool](builtin-bool) val) ### subc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L393) ``` fun box subc( y: ULong val) : (ULong val , Bool val) ``` #### Parameters * y: [ULong](index) val #### Returns * ([ULong](index) val , [Bool](builtin-bool) val) ### mulc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L400) ``` fun box mulc( y: ULong val) : (ULong val , Bool val) ``` #### Parameters * y: [ULong](index) val #### Returns * ([ULong](index) val , [Bool](builtin-bool) val) ### divc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L407) ``` fun box divc( y: ULong val) : (ULong val , Bool val) ``` #### Parameters * y: [ULong](index) val #### Returns * ([ULong](index) val , [Bool](builtin-bool) val) ### remc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L410) ``` fun box remc( y: ULong val) : (ULong val , Bool val) ``` #### Parameters * y: [ULong](index) val #### Returns * ([ULong](index) val , [Bool](builtin-bool) val) ### add\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L413) ``` fun box add_partial( y: ULong val) : ULong val ? ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ? ### sub\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L416) ``` fun box sub_partial( y: ULong val) : ULong val ? ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ? ### mul\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L419) ``` fun box mul_partial( y: ULong val) : ULong val ? ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ? ### div\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L422) ``` fun box div_partial( y: ULong val) : ULong val ? ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ? ### rem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L425) ``` fun box rem_partial( y: ULong val) : ULong val ? ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ? ### divrem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L428) ``` fun box divrem_partial( y: ULong val) : (ULong val , ULong val) ? ``` #### Parameters * y: [ULong](index) val #### Returns * ([ULong](index) val , [ULong](index) val) ? ### shl ``` fun box shl( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### shr ``` fun box shr( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### fld ``` fun box fld( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### fldc ``` fun box fldc( y: ULong val) : (ULong val , Bool val) ``` #### Parameters * y: [ULong](index) val #### Returns * ([ULong](index) val , [Bool](builtin-bool) val) ### fld\_partial ``` fun box fld_partial( y: ULong val) : ULong val ? ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ? ### fld\_unsafe ``` fun box fld_unsafe( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### mod ``` fun box mod( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### modc ``` fun box modc( y: ULong val) : (ULong val , Bool val) ``` #### Parameters * y: [ULong](index) val #### Returns * ([ULong](index) val , [Bool](builtin-bool) val) ### mod\_partial ``` fun box mod_partial( y: ULong val) : ULong val ? ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ? ### mod\_unsafe ``` fun box mod_unsafe( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### shl\_unsafe ``` fun box shl_unsafe( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### shr\_unsafe ``` fun box shr_unsafe( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### rotl ``` fun box rotl( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### rotr ``` fun box rotr( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### string ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### add\_unsafe ``` fun box add_unsafe( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### sub\_unsafe ``` fun box sub_unsafe( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### mul\_unsafe ``` fun box mul_unsafe( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### div\_unsafe ``` fun box div_unsafe( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### divrem\_unsafe ``` fun box divrem_unsafe( y: ULong val) : (ULong val , ULong val) ``` #### Parameters * y: [ULong](index) val #### Returns * ([ULong](index) val , [ULong](index) val) ### rem\_unsafe ``` fun box rem_unsafe( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### neg\_unsafe ``` fun box neg_unsafe() : ULong val ``` #### Returns * [ULong](index) val ### op\_and ``` fun box op_and( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### op\_or ``` fun box op_or( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### op\_xor ``` fun box op_xor( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### op\_not ``` fun box op_not() : ULong val ``` #### Returns * [ULong](index) val ### add ``` fun box add( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### sub ``` fun box sub( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### mul ``` fun box mul( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### div ``` fun box div( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### divrem ``` fun box divrem( y: ULong val) : (ULong val , ULong val) ``` #### Parameters * y: [ULong](index) val #### Returns * ([ULong](index) val , [ULong](index) val) ### rem ``` fun box rem( y: ULong val) : ULong val ``` #### Parameters * y: [ULong](index) val #### Returns * [ULong](index) val ### neg ``` fun box neg() : ULong val ``` #### Returns * [ULong](index) val ### eq ``` fun box eq( y: ULong val) : Bool val ``` #### Parameters * y: [ULong](index) val #### Returns * [Bool](builtin-bool) val ### ne ``` fun box ne( y: ULong val) : Bool val ``` #### Parameters * y: [ULong](index) val #### Returns * [Bool](builtin-bool) val ### lt ``` fun box lt( y: ULong val) : Bool val ``` #### Parameters * y: [ULong](index) val #### Returns * [Bool](builtin-bool) val ### le ``` fun box le( y: ULong val) : Bool val ``` #### Parameters * y: [ULong](index) val #### Returns * [Bool](builtin-bool) val ### ge ``` fun box ge( y: ULong val) : Bool val ``` #### Parameters * y: [ULong](index) val #### Returns * [Bool](builtin-bool) val ### gt ``` fun box gt( y: ULong val) : Bool val ``` #### Parameters * y: [ULong](index) val #### Returns * [Bool](builtin-bool) val ### hash64 ``` fun box hash64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### i8 ``` fun box i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 ``` fun box i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 ``` fun box i32() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64 ``` fun box i64() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128 ``` fun box i128() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong ``` fun box ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize ``` fun box isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8 ``` fun box u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 ``` fun box u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 ``` fun box u32() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64 ``` fun box u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 ``` fun box u128() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong ``` fun box ulong() : ULong val ``` #### Returns * [ULong](index) val ### usize ``` fun box usize() : USize val ``` #### Returns * [USize](builtin-usize) val ### f32 ``` fun box f32() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64 ``` fun box f64() : F64 val ``` #### Returns * [F64](builtin-f64) val ### i8\_unsafe ``` fun box i8_unsafe() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16\_unsafe ``` fun box i16_unsafe() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32\_unsafe ``` fun box i32_unsafe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64\_unsafe ``` fun box i64_unsafe() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128\_unsafe ``` fun box i128_unsafe() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong\_unsafe ``` fun box ilong_unsafe() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize\_unsafe ``` fun box isize_unsafe() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8\_unsafe ``` fun box u8_unsafe() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16\_unsafe ``` fun box u16_unsafe() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32\_unsafe ``` fun box u32_unsafe() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64\_unsafe ``` fun box u64_unsafe() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128\_unsafe ``` fun box u128_unsafe() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong\_unsafe ``` fun box ulong_unsafe() : ULong val ``` #### Returns * [ULong](index) val ### usize\_unsafe ``` fun box usize_unsafe() : USize val ``` #### Returns * [USize](builtin-usize) val ### f32\_unsafe ``` fun box f32_unsafe() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64\_unsafe ``` fun box f64_unsafe() : F64 val ``` #### Returns * [F64](builtin-f64) val ### compare ``` fun box compare( that: ULong val) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [ULong](index) val #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val)
programming_docs
pony CommandHelp CommandHelp =========== [[Source]](https://stdlib.ponylang.io/src/cli/command_help/#L37) CommandHelp encapsulates the information needed to generate a user help message for a given CommandSpec, optionally with a specific command identified to print help about. Use `Help.general()` or `Help.for_command()` to create a CommandHelp instance. ``` class box CommandHelp ``` Public Functions ---------------- ### fullname [[Source]](https://stdlib.ponylang.io/src/cli/command_help/#L51) ``` fun box fullname() : String val ``` #### Returns * [String](builtin-string) val ### string [[Source]](https://stdlib.ponylang.io/src/cli/command_help/#L58) ``` fun box string() : String val ``` #### Returns * [String](builtin-string) val ### help\_string [[Source]](https://stdlib.ponylang.io/src/cli/command_help/#L60) Renders the help message as a String. ``` fun box help_string() : String val ``` #### Returns * [String](builtin-string) val ### print\_help [[Source]](https://stdlib.ponylang.io/src/cli/command_help/#L70) Prints the help message to an OutStream. ``` fun box print_help( os: OutStream tag) : None val ``` #### Parameters * os: [OutStream](builtin-outstream) tag #### Returns * [None](builtin-none) val pony FileStream FileStream ========== [[Source]](https://stdlib.ponylang.io/src/files/file_stream/#L1) Asynchronous access to a File object. Wraps file operations print, write, printv and writev. The File will be disposed through File.\_final. ``` actor tag FileStream is OutStream tag ``` #### Implements * [OutStream](builtin-outstream) tag Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file_stream/#L8) ``` new tag create( file: File iso) : FileStream tag^ ``` #### Parameters * file: [File](files-file) iso #### Returns * [FileStream](index) tag^ Public Behaviours ----------------- ### print [[Source]](https://stdlib.ponylang.io/src/files/file_stream/#L11) Print some bytes and insert a newline afterwards. ``` be print( data: (String val | Array[U8 val] val)) ``` #### Parameters * data: ([String](builtin-string) val | [Array](builtin-array)[[U8](builtin-u8) val] val) ### write [[Source]](https://stdlib.ponylang.io/src/files/file_stream/#L17) Print some bytes without inserting a newline afterwards. ``` be write( data: (String val | Array[U8 val] val)) ``` #### Parameters * data: ([String](builtin-string) val | [Array](builtin-array)[[U8](builtin-u8) val] val) ### printv [[Source]](https://stdlib.ponylang.io/src/files/file_stream/#L23) Print an iterable collection of ByteSeqs. ``` be printv( data: ByteSeqIter val) ``` #### Parameters * data: [ByteSeqIter](builtin-byteseqiter) val ### writev [[Source]](https://stdlib.ponylang.io/src/files/file_stream/#L29) Write an iterable collection of ByteSeqs. ``` be writev( data: ByteSeqIter val) ``` #### Parameters * data: [ByteSeqIter](builtin-byteseqiter) val ### flush [[Source]](https://stdlib.ponylang.io/src/files/file_stream/#L35) Flush pending data to write. ``` be flush() ``` pony PrefixSign PrefixSign ========== [[Source]](https://stdlib.ponylang.io/src/format/prefix_spec/#L6) ``` primitive val PrefixSign is PrefixSpec val ``` #### Implements * [PrefixSpec](format-prefixspec) val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/format/prefix_spec/#L6) ``` new val create() : PrefixSign val^ ``` #### Returns * [PrefixSign](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/format/prefix_spec/#L8) ``` fun box eq( that: PrefixSign val) : Bool val ``` #### Parameters * that: [PrefixSign](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/format/prefix_spec/#L8) ``` fun box ne( that: PrefixSign val) : Bool val ``` #### Parameters * that: [PrefixSign](index) val #### Returns * [Bool](builtin-bool) val pony MapIs[K: Any #share, V: Any #share] MapIs[K: [Any](builtin-any) #share, V: [Any](builtin-any) #share] ================================================================= [[Source]](https://stdlib.ponylang.io/src/collections-persistent/map/#L9) A map that uses identity comparison on the key. ``` type MapIs[K: Any #share, V: Any #share] is HashMap[K, V, HashIs[K] val] val ``` #### Type Alias For * [HashMap](collections-persistent-hashmap)[K, V, [HashIs](collections-hashis)[K] val] val pony LogFormatter LogFormatter ============ [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L143) Interface required to implement custom log formatting. * `msg` is the logged message * `loc` is the location log was called from See `DefaultLogFormatter` for an example of how to implement a LogFormatter. ``` interface val LogFormatter ``` Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L152) ``` fun box apply( msg: String val, loc: SourceLoc val) : String val ``` #### Parameters * msg: [String](builtin-string) val * loc: [SourceLoc](builtin-sourceloc) val #### Returns * [String](builtin-string) val pony LogLevel LogLevel ======== [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L91) ``` type LogLevel is (Fine val | Info val | Warn val | Error val) ``` #### Type Alias For * ([Fine](logger-fine) val | [Info](logger-info) val | [Warn](logger-warn) val | [Error](logger-error) val) pony Rand Rand ==== [[Source]](https://stdlib.ponylang.io/src/random/random/#L19) ``` type Rand is XorOshiro128Plus ref ``` #### Type Alias For * [XorOshiro128Plus](random-xoroshiro128plus) ref pony ArrayValues[A: A, B: Array[A] #read] ArrayValues[A: A, B: [Array](builtin-array)[A] #read] ===================================================== [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L954) ``` class ref ArrayValues[A: A, B: Array[A] #read] is Iterator[B->A] ref ``` #### Implements * [Iterator](builtin-iterator)[B->A] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L958) ``` new ref create( array: B) : ArrayValues[A, B] ref^ ``` #### Parameters * array: B #### Returns * [ArrayValues](index)[A, B] ref^ Public Functions ---------------- ### has\_next [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L962) ``` fun box has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### next [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L965) ``` fun ref next() : B->A ? ``` #### Returns * B->A ? ### rewind [[Source]](https://stdlib.ponylang.io/src/builtin/array/#L968) ``` fun ref rewind() : ArrayValues[A, B] ref ``` #### Returns * [ArrayValues](index)[A, B] ref pony DeserialiseAuth DeserialiseAuth =============== [[Source]](https://stdlib.ponylang.io/src/serialise/serialise/#L48) This is a capability token that allows the holder to deserialise objects. It does not allow the holder to serialise objects or examine serialised. ``` primitive val DeserialiseAuth ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/serialise/serialise/#L53) ``` new val create( auth: AmbientAuth val) : DeserialiseAuth val^ ``` #### Parameters * auth: [AmbientAuth](builtin-ambientauth) val #### Returns * [DeserialiseAuth](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/serialise/serialise/#L53) ``` fun box eq( that: DeserialiseAuth val) : Bool val ``` #### Parameters * that: [DeserialiseAuth](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/serialise/serialise/#L53) ``` fun box ne( that: DeserialiseAuth val) : Bool val ``` #### Parameters * that: [DeserialiseAuth](index) val #### Returns * [Bool](builtin-bool) val pony Comparable[A: Comparable[A] #read] Comparable[A: [Comparable](index)[A] #read] =========================================== [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L22) ``` interface ref Comparable[A: Comparable[A] #read] is Equatable[A] ref ``` #### Implements * [Equatable](builtin-equatable)[A] ref Public Functions ---------------- ### lt [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L23) ``` fun box lt( that: box->A) : Bool val ``` #### Parameters * that: box->A #### Returns * [Bool](builtin-bool) val ### le [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L24) ``` fun box le( that: box->A) : Bool val ``` #### Parameters * that: box->A #### Returns * [Bool](builtin-bool) val ### ge [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L25) ``` fun box ge( that: box->A) : Bool val ``` #### Parameters * that: box->A #### Returns * [Bool](builtin-bool) val ### gt [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L26) ``` fun box gt( that: box->A) : Bool val ``` #### Parameters * that: box->A #### Returns * [Bool](builtin-bool) val ### compare [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L28) ``` fun box compare( that: box->A) : (Less val | Equal val | Greater val) ``` #### Parameters * that: box->A #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val) ### eq [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L19) ``` fun box eq( that: box->A) : Bool val ``` #### Parameters * that: box->A #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L20) ``` fun box ne( that: box->A) : Bool val ``` #### Parameters * that: box->A #### Returns * [Bool](builtin-bool) val pony BenchmarkList BenchmarkList ============= [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L49) ``` interface tag BenchmarkList ``` Public Functions ---------------- ### benchmarks [[Source]](https://stdlib.ponylang.io/src/ponybench/benchmark/#L50) ``` fun tag benchmarks( bench: PonyBench tag) : None val ``` #### Parameters * bench: [PonyBench](ponybench-ponybench) tag #### Returns * [None](builtin-none) val pony ForkError ForkError ========= [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L44) ``` primitive val ForkError ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L44) ``` new val create() : ForkError val^ ``` #### Returns * [ForkError](index) val^ Public Functions ---------------- ### string [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L45) ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### eq [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L45) ``` fun box eq( that: ForkError val) : Bool val ``` #### Parameters * that: [ForkError](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/process/process_error/#L45) ``` fun box ne( that: ForkError val) : Bool val ``` #### Parameters * that: [ForkError](index) val #### Returns * [Bool](builtin-bool) val pony Debug Debug ===== [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L24) This is a debug only print utility. ``` primitive val Debug ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L24) ``` new val create() : Debug val^ ``` #### Returns * [Debug](index) val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L28) If platform is debug configured, print either a single stringable or a sequence of stringables. The default separator is ", ", and the default output stream is stdout. ``` fun box apply( msg: (Stringable box | ReadSeq[Stringable box] box), sep: String val = ", ", stream: (DebugOut val | DebugErr val) = reference) : None val ``` #### Parameters * msg: ([Stringable](builtin-stringable) box | [ReadSeq](builtin-readseq)[[Stringable](builtin-stringable) box] box) * sep: [String](builtin-string) val = ", " * stream: ([DebugOut](debug-debugout) val | [DebugErr](debug-debugerr) val) = reference #### Returns * [None](builtin-none) val ### out [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L47) If platform is debug configured, print message to standard output ``` fun box out( msg: Stringable box = "") : None val ``` #### Parameters * msg: [Stringable](builtin-stringable) box = "" #### Returns * [None](builtin-none) val ### err [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L53) If platform is debug configured, print message to standard error ``` fun box err( msg: Stringable box = "") : None val ``` #### Parameters * msg: [Stringable](builtin-stringable) box = "" #### Returns * [None](builtin-none) val ### eq [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L28) ``` fun box eq( that: Debug val) : Bool val ``` #### Parameters * that: [Debug](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L28) ``` fun box ne( that: Debug val) : Bool val ``` #### Parameters * that: [Debug](index) val #### Returns * [Bool](builtin-bool) val pony HashSet[A: A, H: HashFunction[A!] val] HashSet[A: A, H: [HashFunction](collections-hashfunction)[A!] val] ================================================================== [[Source]](https://stdlib.ponylang.io/src/collections/set/#L5) A set, built on top of a HashMap. This is implemented as map of an alias of a type to itself ``` class ref HashSet[A: A, H: HashFunction[A!] val] is Comparable[HashSet[A, H] box] ref ``` #### Implements * [Comparable](builtin-comparable)[[HashSet](index)[A, H] box] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/set/#L12) Defaults to a prealloc of 8. ``` new ref create( prealloc: USize val = 8) : HashSet[A, H] ref^ ``` #### Parameters * prealloc: [USize](builtin-usize) val = 8 #### Returns * [HashSet](index)[A, H] ref^ Public Functions ---------------- ### size [[Source]](https://stdlib.ponylang.io/src/collections/set/#L18) The number of items in the set. ``` fun box size() : USize val ``` #### Returns * [USize](builtin-usize) val ### space [[Source]](https://stdlib.ponylang.io/src/collections/set/#L24) The available space in the set. ``` fun box space() : USize val ``` #### Returns * [USize](builtin-usize) val ### apply [[Source]](https://stdlib.ponylang.io/src/collections/set/#L30) Return the value if its in the set, otherwise raise an error. ``` fun box apply( value: box->A!) : this->A ? ``` #### Parameters * value: box->A! #### Returns * this->A ? ### contains [[Source]](https://stdlib.ponylang.io/src/collections/set/#L36) Checks whether the set contains the value. ``` fun box contains( value: box->A!) : Bool val ``` #### Parameters * value: box->A! #### Returns * [Bool](builtin-bool) val ### clear [[Source]](https://stdlib.ponylang.io/src/collections/set/#L42) Remove all elements from the set. ``` fun ref clear() : None val ``` #### Returns * [None](builtin-none) val ### set [[Source]](https://stdlib.ponylang.io/src/collections/set/#L48) Add a value to the set. ``` fun ref set( value: A) : None val ``` #### Parameters * value: A #### Returns * [None](builtin-none) val ### unset [[Source]](https://stdlib.ponylang.io/src/collections/set/#L54) Remove a value from the set. ``` fun ref unset( value: box->A!) : None val ``` #### Parameters * value: box->A! #### Returns * [None](builtin-none) val ### extract [[Source]](https://stdlib.ponylang.io/src/collections/set/#L60) Remove a value from the set and return it. Raises an error if the value wasn't in the set. ``` fun ref extract( value: box->A!) : A^ ? ``` #### Parameters * value: box->A! #### Returns * A^ ? ### union [[Source]](https://stdlib.ponylang.io/src/collections/set/#L67) Add everything in that to the set. ``` fun ref union( that: Iterator[A^] ref) : None val ``` #### Parameters * that: [Iterator](builtin-iterator)[A^] ref #### Returns * [None](builtin-none) val ### intersect[optional K: [HashFunction](collections-hashfunction)[box->A!] val] [[Source]](https://stdlib.ponylang.io/src/collections/set/#L75) Remove everything that isn't in that. ``` fun ref intersect[optional K: HashFunction[box->A!] val]( that: HashSet[box->A!, K] ref) : None val ``` #### Parameters * that: [HashSet](index)[box->A!, K] ref #### Returns * [None](builtin-none) val ### difference [[Source]](https://stdlib.ponylang.io/src/collections/set/#L95) Remove elements in this which are also in that. Add elements in that which are not in this. ``` fun ref difference( that: Iterator[A^] ref) : None val ``` #### Parameters * that: [Iterator](builtin-iterator)[A^] ref #### Returns * [None](builtin-none) val ### remove [[Source]](https://stdlib.ponylang.io/src/collections/set/#L108) Remove everything that is in that. ``` fun ref remove( that: Iterator[box->A!] ref) : None val ``` #### Parameters * that: [Iterator](builtin-iterator)[box->A!] ref #### Returns * [None](builtin-none) val ### add[optional K: [HashFunction](collections-hashfunction)[this->A!] val] [[Source]](https://stdlib.ponylang.io/src/collections/set/#L116) Add a value to the set. ``` fun box add[optional K: HashFunction[this->A!] val]( value: this->A!) : HashSet[this->A!, K] ref^ ``` #### Parameters * value: this->A! #### Returns * [HashSet](index)[this->A!, K] ref^ ### sub[optional K: [HashFunction](collections-hashfunction)[this->A!] val] [[Source]](https://stdlib.ponylang.io/src/collections/set/#L125) Remove a value from the set. ``` fun box sub[optional K: HashFunction[this->A!] val]( value: box->this->A!) : HashSet[this->A!, K] ref^ ``` #### Parameters * value: box->this->A! #### Returns * [HashSet](index)[this->A!, K] ref^ ### op\_or[optional K: [HashFunction](collections-hashfunction)[this->A!] val] [[Source]](https://stdlib.ponylang.io/src/collections/set/#L134) Create a set with the elements of both this and that. ``` fun box op_or[optional K: HashFunction[this->A!] val]( that: this->HashSet[A, H] ref) : HashSet[this->A!, K] ref^ ``` #### Parameters * that: this->[HashSet](index)[A, H] ref #### Returns * [HashSet](index)[this->A!, K] ref^ ### op\_and[optional K: [HashFunction](collections-hashfunction)[this->A!] val] [[Source]](https://stdlib.ponylang.io/src/collections/set/#L148) Create a set with the elements that are in both this and that. ``` fun box op_and[optional K: HashFunction[this->A!] val]( that: this->HashSet[A, H] ref) : HashSet[this->A!, K] ref^ ``` #### Parameters * that: this->[HashSet](index)[A, H] ref #### Returns * [HashSet](index)[this->A!, K] ref^ ### op\_xor[optional K: [HashFunction](collections-hashfunction)[this->A!] val] [[Source]](https://stdlib.ponylang.io/src/collections/set/#L165) Create a set with the elements that are in either set but not both. ``` fun box op_xor[optional K: HashFunction[this->A!] val]( that: this->HashSet[A, H] ref) : HashSet[this->A!, K] ref^ ``` #### Parameters * that: this->[HashSet](index)[A, H] ref #### Returns * [HashSet](index)[this->A!, K] ref^ ### without[optional K: [HashFunction](collections-hashfunction)[this->A!] val] [[Source]](https://stdlib.ponylang.io/src/collections/set/#L191) Create a set with the elements of this that are not in that. ``` fun box without[optional K: HashFunction[this->A!] val]( that: this->HashSet[A, H] ref) : HashSet[this->A!, K] ref^ ``` #### Parameters * that: this->[HashSet](index)[A, H] ref #### Returns * [HashSet](index)[this->A!, K] ref^ ### clone[optional K: [HashFunction](collections-hashfunction)[this->A!] val] [[Source]](https://stdlib.ponylang.io/src/collections/set/#L209) Create a clone. The element type may be different due to aliasing and viewpoint adaptation. ``` fun box clone[optional K: HashFunction[this->A!] val]() : HashSet[this->A!, K] ref^ ``` #### Returns * [HashSet](index)[this->A!, K] ref^ ### eq [[Source]](https://stdlib.ponylang.io/src/collections/set/#L221) Returns true if the sets contain the same elements. ``` fun box eq( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/collections/set/#L227) Returns false if the sets contain the same elements. ``` fun box ne( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val ### lt [[Source]](https://stdlib.ponylang.io/src/collections/set/#L233) Returns true if every element in this is also in that, and this has fewer elements than that. ``` fun box lt( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val ### le [[Source]](https://stdlib.ponylang.io/src/collections/set/#L240) Returns true if every element in this is also in that. ``` fun box le( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val ### gt [[Source]](https://stdlib.ponylang.io/src/collections/set/#L253) Returns true if every element in that is also in this, and this has more elements than that. ``` fun box gt( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val ### ge [[Source]](https://stdlib.ponylang.io/src/collections/set/#L260) Returns true if every element in that is also in this. ``` fun box ge( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val ### next\_index [[Source]](https://stdlib.ponylang.io/src/collections/set/#L266) Given an index, return the next index that has a populated value. Raise an error if there is no next populated index. ``` fun box next_index( prev: USize val = call) : USize val ? ``` #### Parameters * prev: [USize](builtin-usize) val = call #### Returns * [USize](builtin-usize) val ? ### index [[Source]](https://stdlib.ponylang.io/src/collections/set/#L273) Returns the value at a given index. Raise an error if the index is not populated. ``` fun box index( i: USize val) : this->A ? ``` #### Parameters * i: [USize](builtin-usize) val #### Returns * this->A ? ### values [[Source]](https://stdlib.ponylang.io/src/collections/set/#L280) Return an iterator over the values. ``` fun box values() : SetValues[A, H, this->HashSet[A, H] ref] ref^ ``` #### Returns * [SetValues](collections-setvalues)[A, H, this->[HashSet](index)[A, H] ref] ref^ ### compare [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L28) ``` fun box compare( that: HashSet[A, H] box) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val)
programming_docs
pony OutStream OutStream ========= [[Source]](https://stdlib.ponylang.io/src/builtin/std_stream/#L9) Asnychronous access to some output stream. ``` interface tag OutStream ``` Public Behaviours ----------------- ### print [[Source]](https://stdlib.ponylang.io/src/builtin/std_stream/#L13) Print some bytes and insert a newline afterwards. ``` be print( data: (String val | Array[U8 val] val)) ``` #### Parameters * data: ([String](builtin-string) val | [Array](builtin-array)[[U8](builtin-u8) val] val) ### write [[Source]](https://stdlib.ponylang.io/src/builtin/std_stream/#L18) Print some bytes without inserting a newline afterwards. ``` be write( data: (String val | Array[U8 val] val)) ``` #### Parameters * data: ([String](builtin-string) val | [Array](builtin-array)[[U8](builtin-u8) val] val) ### printv [[Source]](https://stdlib.ponylang.io/src/builtin/std_stream/#L23) Print an iterable collection of ByteSeqs. ``` be printv( data: ByteSeqIter val) ``` #### Parameters * data: [ByteSeqIter](builtin-byteseqiter) val ### writev [[Source]](https://stdlib.ponylang.io/src/builtin/std_stream/#L28) Write an iterable collection of ByteSeqs. ``` be writev( data: ByteSeqIter val) ``` #### Parameters * data: [ByteSeqIter](builtin-byteseqiter) val ### flush [[Source]](https://stdlib.ponylang.io/src/builtin/std_stream/#L33) Flush the stream. ``` be flush() ``` pony DNSAuth DNSAuth ======= [[Source]](https://stdlib.ponylang.io/src/net/auth/#L5) ``` primitive val DNSAuth ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/net/auth/#L6) ``` new val create( from: (AmbientAuth val | NetAuth val)) : DNSAuth val^ ``` #### Parameters * from: ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val) #### Returns * [DNSAuth](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/net/auth/#L6) ``` fun box eq( that: DNSAuth val) : Bool val ``` #### Parameters * that: [DNSAuth](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/net/auth/#L6) ``` fun box ne( that: DNSAuth val) : Bool val ``` #### Parameters * that: [DNSAuth](index) val #### Returns * [Bool](builtin-bool) val pony Persistent Collections Package Persistent Collections Package ============================== List - A persistent list with functional transformations. Map - A persistent map based on the Compressed Hash Array Mapped Prefix-tree from 'Optimizing Hash-Array Mapped Tries for Fast and Lean Immutable JVM Collections' by Michael J. Steindorfer and Jurgen J. Vinju. Set - A persistent set implemented as a persistent map of an alias of a type to itself. Vec - A persistent vector based on the Hash Array Mapped Trie from 'Ideal Hash Trees' by Phil Bagwell. Public Types ------------ * [class Vec](collections-persistent-vec) * [class VecKeys](collections-persistent-veckeys) * [class VecValues](collections-persistent-vecvalues) * [class VecPairs](collections-persistent-vecpairs) * [type Set](collections-persistent-set) * [type SetIs](collections-persistent-setis) * [class HashSet](collections-persistent-hashset) * [type Map](collections-persistent-map) * [type MapIs](collections-persistent-mapis) * [class HashMap](collections-persistent-hashmap) * [class MapKeys](collections-persistent-mapkeys) * [class MapValues](collections-persistent-mapvalues) * [class MapPairs](collections-persistent-mappairs) * [type List](collections-persistent-list) * [primitive Lists](collections-persistent-lists) * [primitive Nil](collections-persistent-nil) * [class Cons](collections-persistent-cons) * [primitive CollisionHash](collections-persistent-collisionhash) pony InputNotify InputNotify =========== [[Source]](https://stdlib.ponylang.io/src/builtin/stdin/#L11) Notification for data arriving via an input stream. ``` interface ref InputNotify ``` Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/builtin/stdin/#L15) Called when data is available on the stream. ``` fun ref apply( data: Array[U8 val] iso) : None val ``` #### Parameters * data: [Array](builtin-array)[[U8](builtin-u8) val] iso #### Returns * [None](builtin-none) val ### dispose [[Source]](https://stdlib.ponylang.io/src/builtin/stdin/#L21) Called when no more data will arrive on the stream. ``` fun ref dispose() : None val ``` #### Returns * [None](builtin-none) val pony HashEq[A: (Hashable #read & Equatable[A] #read)] HashEq[A: ([Hashable](collections-hashable) #read & [Equatable](builtin-equatable)[A] #read)] ============================================================================================= [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L57) ``` primitive val HashEq[A: (Hashable #read & Equatable[A] #read)] is HashFunction[A] val ``` #### Implements * [HashFunction](collections-hashfunction)[A] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L57) ``` new val create() : HashEq[A] val^ ``` #### Returns * [HashEq](index)[A] val^ Public Functions ---------------- ### hash [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L58) Use the hash function from the type parameter. ``` fun box hash( x: box->A) : USize val ``` #### Parameters * x: box->A #### Returns * [USize](builtin-usize) val ### eq [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L64) Use the structural equality function from the type parameter. ``` fun box eq( x: box->A, y: box->A) : Bool val ``` #### Parameters * x: box->A * y: box->A #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L58) ``` fun box ne( that: HashEq[A] val) : Bool val ``` #### Parameters * that: [HashEq](index)[A] val #### Returns * [Bool](builtin-bool) val pony ArgumentType ArgumentType ============ [[Source]](https://stdlib.ponylang.io/src/options/options/#L81) ``` type ArgumentType is (None val | StringArgument val | I64Argument val | U64Argument val | F64Argument val) ``` #### Type Alias For * ([None](builtin-none) val | [StringArgument](options-stringargument) val | [I64Argument](options-i64argument) val | [U64Argument](options-u64argument) val | [F64Argument](options-f64argument) val) pony UDPSocketAuth UDPSocketAuth ============= [[Source]](https://stdlib.ponylang.io/src/net/udp_socket/#L3) ``` type UDPSocketAuth is (AmbientAuth val | NetAuth val | UDPAuth val) ``` #### Type Alias For * ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [UDPAuth](net-udpauth) val) pony TCPListenerAuth TCPListenerAuth =============== [[Source]](https://stdlib.ponylang.io/src/net/tcp_listener/#L1) ``` type TCPListenerAuth is (AmbientAuth val | NetAuth val | TCPAuth val | TCPListenAuth val) ``` #### Type Alias For * ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [TCPAuth](net-tcpauth) val | [TCPListenAuth](net-tcplistenauth) val) pony AmbiguousMatch AmbiguousMatch ============== [[Source]](https://stdlib.ponylang.io/src/options/options/#L77) ``` primitive val AmbiguousMatch ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/options/options/#L77) ``` new val create() : AmbiguousMatch val^ ``` #### Returns * [AmbiguousMatch](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/options/options/#L78) ``` fun box eq( that: AmbiguousMatch val) : Bool val ``` #### Parameters * that: [AmbiguousMatch](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/options/options/#L78) ``` fun box ne( that: AmbiguousMatch val) : Bool val ``` #### Parameters * that: [AmbiguousMatch](index) val #### Returns * [Bool](builtin-bool) val pony StringArgument StringArgument ============== [[Source]](https://stdlib.ponylang.io/src/options/options/#L69) ``` primitive val StringArgument ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/options/options/#L69) ``` new val create() : StringArgument val^ ``` #### Returns * [StringArgument](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/options/options/#L70) ``` fun box eq( that: StringArgument val) : Bool val ``` #### Parameters * that: [StringArgument](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/options/options/#L70) ``` fun box ne( that: StringArgument val) : Bool val ``` #### Parameters * that: [StringArgument](index) val #### Returns * [Bool](builtin-bool) val pony IniNotify IniNotify ========= [[Source]](https://stdlib.ponylang.io/src/ini/ini/#L39) Notifications for INI parsing. ``` interface ref IniNotify ``` Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/ini/ini/#L43) This is called for every valid entry in the INI file. If key/value pairs occur before a section name, the section can be an empty string. Return false to halt processing. ``` fun ref apply( section: String val, key: String val, value: String val) : Bool val ``` #### Parameters * section: [String](builtin-string) val * key: [String](builtin-string) val * value: [String](builtin-string) val #### Returns * [Bool](builtin-bool) val ### add\_section [[Source]](https://stdlib.ponylang.io/src/ini/ini/#L50) This is called for every valid section in the INI file. Return false to halt processing. ``` fun ref add_section( section: String val) : Bool val ``` #### Parameters * section: [String](builtin-string) val #### Returns * [Bool](builtin-bool) val ### errors [[Source]](https://stdlib.ponylang.io/src/ini/ini/#L57) This is called for each error encountered. Return false to halt processing. ``` fun ref errors( line: USize val, err: (IniIncompleteSection val | IniNoDelimiter val)) : Bool val ``` #### Parameters * line: [USize](builtin-usize) val * err: ([IniIncompleteSection](ini-iniincompletesection) val | [IniNoDelimiter](ini-ininodelimiter) val) #### Returns * [Bool](builtin-bool) val pony RejectAlways[A: Any #share] RejectAlways[A: [Any](builtin-any) #share] ========================================== [[Source]](https://stdlib.ponylang.io/src/promises/fulfill/#L23) A reject that always raises an error. ``` class iso RejectAlways[A: Any #share] ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/promises/fulfill/#L23) ``` new iso create() : RejectAlways[A] iso^ ``` #### Returns * [RejectAlways](index)[A] iso^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/promises/fulfill/#L27) ``` fun ref apply() : A ? ``` #### Returns * A ? pony ListNodes[A: A, N: ListNode[A] #read] ListNodes[A: A, N: [ListNode](collections-listnode)[A] #read] ============================================================= [[Source]](https://stdlib.ponylang.io/src/collections/list/#L677) Iterate over the nodes in a list. ``` class ref ListNodes[A: A, N: ListNode[A] #read] is Iterator[N] ref ``` #### Implements * [Iterator](builtin-iterator)[N] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/list/#L684) Keep the next list node to be examined. ``` new ref create( head: (N | None val), reverse: Bool val = false) : ListNodes[A, N] ref^ ``` #### Parameters * head: (N | [None](builtin-none) val) * reverse: [Bool](builtin-bool) val = false #### Returns * [ListNodes](index)[A, N] ref^ Public Functions ---------------- ### has\_next [[Source]](https://stdlib.ponylang.io/src/collections/list/#L691) If we have a list node, we have more values. ``` fun box has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### next [[Source]](https://stdlib.ponylang.io/src/collections/list/#L697) Get the list node and replace it with the next one. ``` fun ref next() : N ? ``` #### Returns * N ? pony I32 I32 === [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L186) ``` primitive val I32 is SignedInteger[I32 val, U32 val] val ``` #### Implements * [SignedInteger](builtin-signedinteger)[[I32](index) val, [U32](builtin-u32) val] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L187) ``` new val create( value: I32 val) : I32 val^ ``` #### Parameters * value: [I32](index) val #### Returns * [I32](index) val^ ### from[A: (([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](index) val | [I64](builtin-i64) val | [I128](builtin-i128) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val | [U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val | [F32](builtin-f32) val | [F64](builtin-f64) val) & [Real](builtin-real)[A] val)] [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L188) ``` new val from[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[A] val)]( a: A) : I32 val^ ``` #### Parameters * a: A #### Returns * [I32](index) val^ ### min\_value [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L190) ``` new val min_value() : I32 val^ ``` #### Returns * [I32](index) val^ ### max\_value [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L191) ``` new val max_value() : I32 val^ ``` #### Returns * [I32](index) val^ Public Functions ---------------- ### abs [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L193) ``` fun box abs() : U32 val ``` #### Returns * [U32](builtin-u32) val ### bit\_reverse [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L194) ``` fun box bit_reverse() : I32 val ``` #### Returns * [I32](index) val ### bswap [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L195) ``` fun box bswap() : I32 val ``` #### Returns * [I32](index) val ### popcount [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L196) ``` fun box popcount() : U32 val ``` #### Returns * [U32](builtin-u32) val ### clz [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L197) ``` fun box clz() : U32 val ``` #### Returns * [U32](builtin-u32) val ### ctz [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L198) ``` fun box ctz() : U32 val ``` #### Returns * [U32](builtin-u32) val ### clz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L200) Unsafe operation. If this is 0, the result is undefined. ``` fun box clz_unsafe() : U32 val ``` #### Returns * [U32](builtin-u32) val ### ctz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L207) Unsafe operation. If this is 0, the result is undefined. ``` fun box ctz_unsafe() : U32 val ``` #### Returns * [U32](builtin-u32) val ### bitwidth [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L214) ``` fun box bitwidth() : U32 val ``` #### Returns * [U32](builtin-u32) val ### bytewidth [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L216) ``` fun box bytewidth() : USize val ``` #### Returns * [USize](builtin-usize) val ### min [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L218) ``` fun box min( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### max [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L219) ``` fun box max( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### fld [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L221) ``` fun box fld( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### fld\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L224) ``` fun box fld_unsafe( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### mod [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L227) ``` fun box mod( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### mod\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L230) ``` fun box mod_unsafe( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### addc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L233) ``` fun box addc( y: I32 val) : (I32 val , Bool val) ``` #### Parameters * y: [I32](index) val #### Returns * ([I32](index) val , [Bool](builtin-bool) val) ### subc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L236) ``` fun box subc( y: I32 val) : (I32 val , Bool val) ``` #### Parameters * y: [I32](index) val #### Returns * ([I32](index) val , [Bool](builtin-bool) val) ### mulc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L239) ``` fun box mulc( y: I32 val) : (I32 val , Bool val) ``` #### Parameters * y: [I32](index) val #### Returns * ([I32](index) val , [Bool](builtin-bool) val) ### divc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L242) ``` fun box divc( y: I32 val) : (I32 val , Bool val) ``` #### Parameters * y: [I32](index) val #### Returns * ([I32](index) val , [Bool](builtin-bool) val) ### remc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L245) ``` fun box remc( y: I32 val) : (I32 val , Bool val) ``` #### Parameters * y: [I32](index) val #### Returns * ([I32](index) val , [Bool](builtin-bool) val) ### fldc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L248) ``` fun box fldc( y: I32 val) : (I32 val , Bool val) ``` #### Parameters * y: [I32](index) val #### Returns * ([I32](index) val , [Bool](builtin-bool) val) ### modc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L251) ``` fun box modc( y: I32 val) : (I32 val , Bool val) ``` #### Parameters * y: [I32](index) val #### Returns * ([I32](index) val , [Bool](builtin-bool) val) ### add\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L254) ``` fun box add_partial( y: I32 val) : I32 val ? ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ? ### sub\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L257) ``` fun box sub_partial( y: I32 val) : I32 val ? ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ? ### mul\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L260) ``` fun box mul_partial( y: I32 val) : I32 val ? ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ? ### div\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L263) ``` fun box div_partial( y: I32 val) : I32 val ? ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ? ### rem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L266) ``` fun box rem_partial( y: I32 val) : I32 val ? ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ? ### divrem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L269) ``` fun box divrem_partial( y: I32 val) : (I32 val , I32 val) ? ``` #### Parameters * y: [I32](index) val #### Returns * ([I32](index) val , [I32](index) val) ? ### fld\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L272) ``` fun box fld_partial( y: I32 val) : I32 val ? ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ? ### mod\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L275) ``` fun box mod_partial( y: I32 val) : I32 val ? ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ? ### shl ``` fun box shl( y: U32 val) : I32 val ``` #### Parameters * y: [U32](builtin-u32) val #### Returns * [I32](index) val ### shr ``` fun box shr( y: U32 val) : I32 val ``` #### Parameters * y: [U32](builtin-u32) val #### Returns * [I32](index) val ### shl\_unsafe ``` fun box shl_unsafe( y: U32 val) : I32 val ``` #### Parameters * y: [U32](builtin-u32) val #### Returns * [I32](index) val ### shr\_unsafe ``` fun box shr_unsafe( y: U32 val) : I32 val ``` #### Parameters * y: [U32](builtin-u32) val #### Returns * [I32](index) val ### string ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### add\_unsafe ``` fun box add_unsafe( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### sub\_unsafe ``` fun box sub_unsafe( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### mul\_unsafe ``` fun box mul_unsafe( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### div\_unsafe ``` fun box div_unsafe( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### divrem\_unsafe ``` fun box divrem_unsafe( y: I32 val) : (I32 val , I32 val) ``` #### Parameters * y: [I32](index) val #### Returns * ([I32](index) val , [I32](index) val) ### rem\_unsafe ``` fun box rem_unsafe( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### neg\_unsafe ``` fun box neg_unsafe() : I32 val ``` #### Returns * [I32](index) val ### op\_and ``` fun box op_and( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### op\_or ``` fun box op_or( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### op\_xor ``` fun box op_xor( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### op\_not ``` fun box op_not() : I32 val ``` #### Returns * [I32](index) val ### add ``` fun box add( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### sub ``` fun box sub( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### mul ``` fun box mul( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### div ``` fun box div( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### divrem ``` fun box divrem( y: I32 val) : (I32 val , I32 val) ``` #### Parameters * y: [I32](index) val #### Returns * ([I32](index) val , [I32](index) val) ### rem ``` fun box rem( y: I32 val) : I32 val ``` #### Parameters * y: [I32](index) val #### Returns * [I32](index) val ### neg ``` fun box neg() : I32 val ``` #### Returns * [I32](index) val ### eq ``` fun box eq( y: I32 val) : Bool val ``` #### Parameters * y: [I32](index) val #### Returns * [Bool](builtin-bool) val ### ne ``` fun box ne( y: I32 val) : Bool val ``` #### Parameters * y: [I32](index) val #### Returns * [Bool](builtin-bool) val ### lt ``` fun box lt( y: I32 val) : Bool val ``` #### Parameters * y: [I32](index) val #### Returns * [Bool](builtin-bool) val ### le ``` fun box le( y: I32 val) : Bool val ``` #### Parameters * y: [I32](index) val #### Returns * [Bool](builtin-bool) val ### ge ``` fun box ge( y: I32 val) : Bool val ``` #### Parameters * y: [I32](index) val #### Returns * [Bool](builtin-bool) val ### gt ``` fun box gt( y: I32 val) : Bool val ``` #### Parameters * y: [I32](index) val #### Returns * [Bool](builtin-bool) val ### hash ``` fun box hash() : USize val ``` #### Returns * [USize](builtin-usize) val ### hash64 ``` fun box hash64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### i8 ``` fun box i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 ``` fun box i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 ``` fun box i32() : I32 val ``` #### Returns * [I32](index) val ### i64 ``` fun box i64() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128 ``` fun box i128() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong ``` fun box ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize ``` fun box isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8 ``` fun box u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 ``` fun box u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 ``` fun box u32() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64 ``` fun box u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 ``` fun box u128() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong ``` fun box ulong() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize ``` fun box usize() : USize val ``` #### Returns * [USize](builtin-usize) val ### f32 ``` fun box f32() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64 ``` fun box f64() : F64 val ``` #### Returns * [F64](builtin-f64) val ### i8\_unsafe ``` fun box i8_unsafe() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16\_unsafe ``` fun box i16_unsafe() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32\_unsafe ``` fun box i32_unsafe() : I32 val ``` #### Returns * [I32](index) val ### i64\_unsafe ``` fun box i64_unsafe() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128\_unsafe ``` fun box i128_unsafe() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong\_unsafe ``` fun box ilong_unsafe() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize\_unsafe ``` fun box isize_unsafe() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8\_unsafe ``` fun box u8_unsafe() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16\_unsafe ``` fun box u16_unsafe() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32\_unsafe ``` fun box u32_unsafe() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64\_unsafe ``` fun box u64_unsafe() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128\_unsafe ``` fun box u128_unsafe() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong\_unsafe ``` fun box ulong_unsafe() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize\_unsafe ``` fun box usize_unsafe() : USize val ``` #### Returns * [USize](builtin-usize) val ### f32\_unsafe ``` fun box f32_unsafe() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64\_unsafe ``` fun box f64_unsafe() : F64 val ``` #### Returns * [F64](builtin-f64) val ### compare ``` fun box compare( that: I32 val) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [I32](index) val #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val)
programming_docs
pony Iter[A: A] Iter[A: A] ========== [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L3) Wrapper class containing methods to modify iterators. ``` class ref Iter[A: A] is Iterator[A] ref ``` #### Implements * [Iterator](builtin-iterator)[A] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L9) ``` new ref create( iter: Iterator[A] ref) : Iter[A] ref^ ``` #### Parameters * iter: [Iterator](builtin-iterator)[A] ref #### Returns * [Iter](index)[A] ref^ ### maybe [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L18) ``` new ref maybe( value: (A | None val)) : Iter[A] ref^ ``` #### Parameters * value: (A | [None](builtin-none) val) #### Returns * [Iter](index)[A] ref^ ### chain [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L28) Take an iterator of iterators and return an Iter containing the items of the first one, then the second one, and so on. Example ------- ``` let xs = [as I64: 1; 2].values() let ys = [as I64: 3; 4].values() Iter[I64].chain([xs; ys].values()) ``` `1 2 3 4` ``` new ref chain( outer_iterator: Iterator[Iterator[A] ref] ref) : Iter[A] ref^ ``` #### Parameters * outer\_iterator: [Iterator](builtin-iterator)[[Iterator](builtin-iterator)[A] ref] ref #### Returns * [Iter](index)[A] ref^ ### repeat\_value [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L82) Create an iterator that returns the given value forever. Example ------- ``` Iter[U32].repeat_value(7) ``` `7 7 7 7 7 7 7 7 7 ...` ``` new ref repeat_value( value: A) : Iter[A] ref^ ``` #### Parameters * value: A #### Returns * [Iter](index)[A] ref^ Public Functions ---------------- ### has\_next [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L12) ``` fun ref has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### next [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L15) ``` fun ref next() : A ? ``` #### Returns * A ? ### next\_or [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L102) Return the next value, or the given default. Example ------- ``` let x: (U64 | None) = 42 Iter[U64].maybe(x).next_or(0) ``` `42` ``` fun ref next_or( default: A) : A ``` #### Parameters * default: A #### Returns * A ### map\_stateful[B: B] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L120) Allows stateful transformation of each element from the iterator, similar to `map`. ``` fun ref map_stateful[B: B]( f: {ref(A!): B^ ?}[A, B] ref) : Iter[B] ref^ ``` #### Parameters * f: {ref(A!): B^ ?}[A, B] ref #### Returns * [Iter](index)[B] ref^ ### filter\_stateful [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L134) Allows filtering of elements based on a stateful adapter, similar to `filter`. ``` fun ref filter_stateful( f: {ref(A!): Bool ?}[A] ref) : Iter[A!] ref^ ``` #### Parameters * f: {ref(A!): Bool ?}[A] ref #### Returns * [Iter](index)[A!] ref^ ### filter\_map\_stateful[B: B] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L184) Allows stateful modification to the stream of elements from an iterator, similar to `filter_map`. ``` fun ref filter_map_stateful[B: B]( f: {ref(A!): (B^ | None) ?}[A, B] ref) : Iter[B] ref^ ``` #### Parameters * f: {ref(A!): (B^ | None) ?}[A, B] ref #### Returns * [Iter](index)[B] ref^ ### all [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L233) Return false if at least one value of the iterator fails to match the predicate `f`. This method short-circuits at the first value where the predicate returns false, otherwise true is returned. Examples -------- ``` Iter[I64]([2; 4; 6].values()) .all({(x) => (x % 2) == 0 }) ``` `true` ``` Iter[I64]([2; 3; 4].values()) .all({(x) => (x % 2) == 0 }) ``` `false` ``` fun ref all( f: {(A!): Bool ?}[A] box) : Bool val ``` #### Parameters * f: {(A!): Bool ?}[A] box #### Returns * [Bool](builtin-bool) val ### any [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L260) Return true if at least one value of the iterator matches the predicate `f`. This method short-circuits at the first value where the predicate returns true, otherwise false is returned. Examples -------- ``` Iter[I64]([2; 4; 6].values()) .any({(I64) => (x % 2) == 1 }) ``` `false` ``` Iter[I64]([2; 3; 4].values()) .any({(I64) => (x % 2) == 1 }) ``` `true` ``` fun ref any( f: {(A!): Bool ?}[A] box) : Bool val ``` #### Parameters * f: {(A!): Bool ?}[A] box #### Returns * [Bool](builtin-bool) val ### collect[optional B: [Seq](builtin-seq)[A!] ref] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L287) Push each value from the iterator into the collection `coll`. Example ------- ``` Iter[I64]([1; 2; 3].values()) .collect(Array[I64](3)) ``` `[1, 2, 3]` ``` fun ref collect[optional B: Seq[A!] ref]( coll: B) : B^ ``` #### Parameters * coll: B #### Returns * B^ ### count [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L304) Return the number of values in the iterator. Example ------- ``` Iter[I64]([1; 2; 3].values()) .count() ``` `3` ``` fun ref count() : USize val ``` #### Returns * [USize](builtin-usize) val ### cycle [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L322) Repeatedly cycle through the values from the iterator. WARNING: The values returned by the original iterator are cached, so the input iterator should be finite. Example ------- ``` Iter[I64]([1; 2; 3].values()) .cycle() ``` `1 2 3 1 2 3 1 2 3 ...` ``` fun ref cycle() : Iter[A!] ref^ ``` #### Returns * [Iter](index)[A!] ref^ ### enum[optional B: ([Real](builtin-real)[B] val & ([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](builtin-i32) val | [I64](builtin-i64) val | [I128](builtin-i128) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val | [U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val | [F32](builtin-f32) val | [F64](builtin-f64) val))] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L379) An iterator which yields the current iteration count as well as the next value from the iterator. Example ------- ``` Iter[I64]([1; 2; 3].values()) .enum() ``` `(0, 1) (1, 2) (2, 3)` ``` fun ref enum[optional B: (Real[B] val & (I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val))]() : Iter[(B , A)] ref^ ``` #### Returns * [Iter](index)[(B , A)] ref^ ### filter [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L402) Return an iterator that only returns items that match the predicate `f`. Example ------- ``` Iter[I64]([1; 2; 3; 4; 5; 6].values()) .filter({(x) => (x % 2) == 0 }) ``` `2 4 6` ``` fun ref filter( f: {(A!): Bool ?}[A] box) : Iter[A!] ref^ ``` #### Parameters * f: {(A!): Bool ?}[A] box #### Returns * [Iter](index)[A!] ref^ ### find [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L416) Return the nth value in the iterator that satisfies the predicate `f`. Examples -------- ``` Iter[I64]([1; 2; 3].values()) .find({(x) => (x % 2) == 0 }) ``` `2` ``` Iter[I64]([1; 2; 3; 4].values()) .find({(x) => (x % 2) == 0 }, 2) ``` `4` ``` fun ref find( f: {(A!): Bool ?}[A] box, n: USize val = 1) : A! ? ``` #### Parameters * f: {(A!): Bool ?}[A] box * n: [USize](builtin-usize) val = 1 #### Returns * A! ? ### filter\_map[B: B] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L446) Return an iterator which applies `f` to each element. If `None` is returned, then the iterator will try again by applying `f` to the next element. Otherwise, the value of type `B` is returned. Example ------- ``` Iter[I64]([as I64: 1; -2; 4; 7; -5]) .filter_map[USize]( {(i: I64): (USize | None) => if i >= 0 then i.usize() end }) ``` `1 4 7` ``` ```pony fun ref filter_map[B: B]( f: {(A!): (B^ | None) ?}[A, B] box) : Iter[B] ref^ ``` #### Parameters * f: {(A!): (B^ | None) ?}[A, B] box #### Returns * [Iter](index)[B] ref^ ### flat\_map[B: B] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L463) Return an iterator over the values of the iterators produced from the application of the given function. Example ------- ``` Iter[String](["alpha"; "beta"; "gamma"]) .flat_map[U8]({(s: String): Iterator[U8] => s.values() }) ``` `a l p h a b e t a g a m m a` ``` fun ref flat_map[B: B]( f: {(A!): Iterator[B] ?}[A, B] box) : Iter[B] ref^ ``` #### Parameters * f: {(A!): Iterator[B] ?}[A, B] box #### Returns * [Iter](index)[B] ref^ ### fold[B: B] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L505) Apply a function to every element, producing an accumulated value. Example ------- ``` Iter[I64]([1; 2; 3].values()) .fold[I64](0, {(sum, x) => sum + x }) ``` `6` ``` fun ref fold[B: B]( acc: B, f: {(B, A!): B^}[A, B] box) : B^ ``` #### Parameters * acc: B * f: {(B, A!): B^}[A, B] box #### Returns * B^ ### fold\_partial[B: B] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L523) A partial version of `fold`. ``` fun ref fold_partial[B: B]( acc: B, f: {(B, A!): B^ ?}[A, B] box) : B^ ? ``` #### Parameters * acc: B * f: {(B, A!): B^ ?}[A, B] box #### Returns * B^ ? ### last [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L576) Return the last value of the iterator. Example ------- ``` Iter[I64]([1; 2; 3].values()) .last() ``` `3` ``` fun ref last() : A ? ``` #### Returns * A ? ### map[B: B] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L592) Return an iterator where each item's value is the application of the given function to the value in the original iterator. Example ------- ``` Iter[I64]([1; 2; 3].values()) .map[I64]({(x) => x * x }) ``` `1 4 9` ``` fun ref map[B: B]( f: {(A!): B^ ?}[A, B] box) : Iter[B] ref^ ``` #### Parameters * f: {(A!): B^ ?}[A, B] box #### Returns * [Iter](index)[B] ref^ ### nth [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L607) Return the nth value of the iterator. Example ------- ``` Iter[I64]([1; 2; 3].values()) .nth(2) ``` `2` ``` fun ref nth( n: USize val) : A ? ``` #### Parameters * n: [USize](builtin-usize) val #### Returns * A ? ### run [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L630) Iterate through the values of the iterator without a for loop. The function `on_error` will be called if the iterator's `has_next` method returns true but its `next` method throws an error. Example ------- ``` Iter[I64]([1; 2; 3].values()) .map[None]({(x) => env.out.print(x.string()) }) .run() ``` ``` 1 2 3 ``` ``` fun ref run( on_error: {ref()}[A] ref = lambda) : None val ``` #### Parameters * on\_error: {ref()}[A] ref = lambda #### Returns * [None](builtin-none) val ### skip [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L657) Skip the first n values of the iterator. Example ------- ``` Iter[I64]([1; 2; 3; 4; 5; 6].values()) .skip(3) ``` `4 5 6` ``` Iter[I64]([1; 2; 3].values()) .skip(3) .has_next() ``` `false` ``` fun ref skip( n: USize val) : Iter[A] ref^ ``` #### Parameters * n: [USize](builtin-usize) val #### Returns * [Iter](index)[A] ref^ ### skip\_while [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L685) Skip values of the iterator while the predicate `f` returns true. Example ------- ``` Iter[I64]([1; 2; 3; 4; 5; 6].values()) .skip_while({(x) => x < 4 }) ``` `4 5 6` ``` fun ref skip_while( f: {(A!): Bool ?}[A] box) : Iter[A!] ref^ ``` #### Parameters * f: {(A!): Bool ?}[A] box #### Returns * [Iter](index)[A!] ref^ ### take [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L711) Return an iterator for the first n elements. Example ------- ``` Iter[I64]([1; 2; 3; 4; 5; 6].values()) .take(3) ``` `1 2 3` ``` fun ref take( n: USize val) : Iter[A] ref^ ``` #### Parameters * n: [USize](builtin-usize) val #### Returns * [Iter](index)[A] ref^ ### take\_while [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L739) Return an iterator that returns values while the predicate `f` returns true. This iterator short-circuits the first time that `f` returns false or raises an error. Example ------- ``` Iter[I64]([1; 2; 3; 4; 5; 6].values()) .take_while({(x) => x < 4 }) ``` `1 2 3` ``` fun ref take_while( f: {(A!): Bool ?}[A] box) : Iter[A!] ref^ ``` #### Parameters * f: {(A!): Bool ?}[A] box #### Returns * [Iter](index)[A!] ref^ ### zip[B: B] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L802) Zip two iterators together so that each call to next() results in a tuple with the next value of the first iterator and the next value of the second iterator. The number of items returned is the minimum of the number of items returned by the two iterators. Example ------- ``` Iter[I64]([1; 2].values()) .zip[I64]([3; 4].values()) ``` `(1, 3) (2, 4)` ``` fun ref zip[B: B]( i2: Iterator[B] ref) : Iter[(A , B)] ref^ ``` #### Parameters * i2: [Iterator](builtin-iterator)[B] ref #### Returns * [Iter](index)[(A , B)] ref^ ### zip2[B: B, C: C] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L829) Zip three iterators together so that each call to next() results in a tuple with the next value of the first iterator, the next value of the second iterator, and the value of the third iterator. The number of items returned is the minimum of the number of items returned by the three iterators. ``` fun ref zip2[B: B, C: C]( i2: Iterator[B] ref, i3: Iterator[C] ref) : Iter[(A , B , C)] ref^ ``` #### Parameters * i2: [Iterator](builtin-iterator)[B] ref * i3: [Iterator](builtin-iterator)[C] ref #### Returns * [Iter](index)[(A , B , C)] ref^ ### zip3[B: B, C: C, D: D] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L850) Zip four iterators together so that each call to next() results in a tuple with the next value of each of the iterators. The number of items returned is the minimum of the number of items returned by the iterators. ``` fun ref zip3[B: B, C: C, D: D]( i2: Iterator[B] ref, i3: Iterator[C] ref, i4: Iterator[D] ref) : Iter[(A , B , C , D)] ref^ ``` #### Parameters * i2: [Iterator](builtin-iterator)[B] ref * i3: [Iterator](builtin-iterator)[C] ref * i4: [Iterator](builtin-iterator)[D] ref #### Returns * [Iter](index)[(A , B , C , D)] ref^ ### zip4[B: B, C: C, D: D, E: E] [[Source]](https://stdlib.ponylang.io/src/itertools/iter/#L876) Zip five iterators together so that each call to next() results in a tuple with the next value of each of the iterators. The number of items returned is the minimum of the number of items returned by the iterators. ``` fun ref zip4[B: B, C: C, D: D, E: E]( i2: Iterator[B] ref, i3: Iterator[C] ref, i4: Iterator[D] ref, i5: Iterator[E] ref) : Iter[(A , B , C , D , E)] ref^ ``` #### Parameters * i2: [Iterator](builtin-iterator)[B] ref * i3: [Iterator](builtin-iterator)[C] ref * i4: [Iterator](builtin-iterator)[D] ref * i5: [Iterator](builtin-iterator)[E] ref #### Returns * [Iter](index)[(A , B , C , D , E)] ref^ pony StringLogger StringLogger ============ [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L134) ``` primitive val StringLogger ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L134) ``` new val create() : StringLogger val^ ``` #### Returns * [StringLogger](index) val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L135) ``` fun box apply( level: (Fine val | Info val | Warn val | Error val), out: OutStream tag, formatter: LogFormatter val = reference) : Logger[String val] val ``` #### Parameters * level: ([Fine](logger-fine) val | [Info](logger-info) val | [Warn](logger-warn) val | [Error](logger-error) val) * out: [OutStream](builtin-outstream) tag * formatter: [LogFormatter](logger-logformatter) val = reference #### Returns * [Logger](logger-logger)[[String](builtin-string) val] val ### eq [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L135) ``` fun box eq( that: StringLogger val) : Bool val ``` #### Parameters * that: [StringLogger](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/logger/logger/#L135) ``` fun box ne( that: StringLogger val) : Bool val ``` #### Parameters * that: [StringLogger](index) val #### Returns * [Bool](builtin-bool) val pony UnitTest UnitTest ======== [[Source]](https://stdlib.ponylang.io/src/ponytest/unit_test/#L1) Each unit test class must provide this trait. Simple tests only need to define the name() and apply() functions. The remaining functions specify additional test options. ``` trait ref UnitTest ``` Public Functions ---------------- ### name [[Source]](https://stdlib.ponylang.io/src/ponytest/unit_test/#L8) Report the test name, which is used when printing test results and on the command line to select tests to run. ``` fun box name() : String val ``` #### Returns * [String](builtin-string) val ### exclusion\_group [[Source]](https://stdlib.ponylang.io/src/ponytest/unit_test/#L14) Report the test exclusion group, returning an empty string for none. The default body returns an empty string. ``` fun box exclusion_group() : String val ``` #### Returns * [String](builtin-string) val ### apply [[Source]](https://stdlib.ponylang.io/src/ponytest/unit_test/#L21) Run the test. Raising an error is interpreted as a test failure. ``` fun ref apply( h: TestHelper val) : None val ? ``` #### Parameters * h: [TestHelper](ponytest-testhelper) val #### Returns * [None](builtin-none) val ? ### timed\_out [[Source]](https://stdlib.ponylang.io/src/ponytest/unit_test/#L27) Tear down a possibly hanging test. Called when the timeout specified by to long\_test() expires. There is no need for this function to call complete(false). tear\_down() will still be called after this completes. The default is to do nothing. ``` fun ref timed_out( h: TestHelper val) : None val ``` #### Parameters * h: [TestHelper](ponytest-testhelper) val #### Returns * [None](builtin-none) val ### set\_up [[Source]](https://stdlib.ponylang.io/src/ponytest/unit_test/#L37) Set up the testing environment before a test method is called. Default is to do nothing. ``` fun ref set_up( h: TestHelper val) : None val ? ``` #### Parameters * h: [TestHelper](ponytest-testhelper) val #### Returns * [None](builtin-none) val ? ### tear\_down [[Source]](https://stdlib.ponylang.io/src/ponytest/unit_test/#L44) Tidy up after the test has completed. Called for each run test, whether that test passed, succeeded or timed out. The default is to do nothing. ``` fun ref tear_down( h: TestHelper val) : None val ``` #### Parameters * h: [TestHelper](ponytest-testhelper) val #### Returns * [None](builtin-none) val ### label [[Source]](https://stdlib.ponylang.io/src/ponytest/unit_test/#L52) Report the test label, returning an empty string for none. It can be later use to filter tests which we want to run, by labels. ``` fun box label() : String val ``` #### Returns * [String](builtin-string) val pony FileCaps FileCaps ======== [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L51) ``` type FileCaps is Flags[(FileCreate val | FileChmod val | FileChown val | FileLink val | FileLookup val | FileMkdir val | FileRead val | FileRemove val | FileRename val | FileSeek val | FileStat val | FileSync val | FileTime val | FileTruncate val | FileWrite val | FileExec val), U32 val] ref ``` #### Type Alias For * [Flags](collections-flags)[([FileCreate](files-filecreate) val | [FileChmod](files-filechmod) val | [FileChown](files-filechown) val | [FileLink](files-filelink) val | [FileLookup](files-filelookup) val | [FileMkdir](files-filemkdir) val | [FileRead](files-fileread) val | [FileRemove](files-fileremove) val | [FileRename](files-filerename) val | [FileSeek](files-fileseek) val | [FileStat](files-filestat) val | [FileSync](files-filesync) val | [FileTime](files-filetime) val | [FileTruncate](files-filetruncate) val | [FileWrite](files-filewrite) val | [FileExec](files-fileexec) val), [U32](builtin-u32) val] ref
programming_docs
pony FormatExpLarge FormatExpLarge ============== [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L28) ``` primitive val FormatExpLarge is FormatSpec val ``` #### Implements * [FormatSpec](format-formatspec) val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L28) ``` new val create() : FormatExpLarge val^ ``` #### Returns * [FormatExpLarge](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L29) ``` fun box eq( that: FormatExpLarge val) : Bool val ``` #### Parameters * that: [FormatExpLarge](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L29) ``` fun box ne( that: FormatExpLarge val) : Bool val ``` #### Parameters * that: [FormatExpLarge](index) val #### Returns * [Bool](builtin-bool) val pony JSON Package JSON Package ============ The `json` package provides the [JsonDoc](json-jsondoc) class both as a container for a JSON document and as means of parsing from and writing to [String](builtin-string). JSON Representation ------------------- JSON is represented in Pony as the following types: * object - [JsonObject](json-jsonobject) * array - [JsonArray](json-jsonarray) * string - [String](builtin-string) * integer - [I64](builtin-i64) * float - [F64](builtin-f64) * boolean - [Bool](builtin-bool) * null - [None](builtin-none) The collection types JsonObject and JsonArray can contain any other JSON structures arbitrarily nested. [JsonType](json-jsontype) is used to subsume all possible JSON types. It can also be used to describe everything that can be serialized using this package. Parsing JSON ------------ For getting JSON from a String into proper Pony data structures, [JsonDoc.parse](json-jsondoc#parse) needs to be used. This will populate the public field `JsonDoc.data`, which is [None](builtin-none), if [parse](json-jsondoc#parse) has not been called yet. Every call to [parse](json-jsondoc#parse) overwrites the `data` field, so one JsonDoc instance can be used to parse multiple JSON Strings one by one. ``` let doc = JsonDoc // parsing doc.parse("{\"key\":\"value\", \"property\": true, \"array\":[1, 2.5, false]}")? // extracting values from a JSON structure let json: JsonObject = doc.data as JsonObject let key: String = json.data("key")? as String let property: Bool = json.data("property")? as Bool let array: JsonArray = json.data("array")? as JsonArray let first: I64 = array.data(0)? as I64 let second: F64 = array.data(1)? as F64 let last: Bool = array.data(2)? as Bool ``` ### Sending JSON [JsonDoc](json-jsondoc) has the `ref` reference capability, which means it is not sendable by default. If you need to send it to another actor you need to recover it to a sendable reference capability (either `val` or `iso`). For the sake of simplicity it is recommended to do the parsing already in the recover block: ``` // sending an iso doc let json_string = "{\"array\":[1, true, null]}" let sendable_doc: JsonDoc iso = recover iso JsonDoc.>parse(json_string)? end some_actor.send(consume sendable_doc) // sending a val doc let val_doc: JsonDoc val = recover val JsonDoc.>parse(json_string)? end some_actor.send_val(val_doc) ``` When sending an `iso` JsonDoc it is important to recover it to a `ref` on the receiving side in order to be able to properly access the json structures in `data`. Writing JSON ------------ JSON is written using the [JsonDoc.string](json-jsondoc#string) method. This will serialize the contents of the `data` field to [String](builtin-string). ``` // building up the JSON data structure let doc = JsonDoc let obj = JsonObject obj.data("key") = "value" obj.data("property") = true obj.data("array") = JsonArray.from_array([ as JsonType: I64(1); F64(2.5); false]) doc.data = obj // writing to String env.out.print( doc.string(where indent=" ", pretty_print=true) ) ``` Public Types ------------ * [type JsonType](json-jsontype) * [class JsonArray](json-jsonarray) * [class JsonObject](json-jsonobject) * [class JsonDoc](json-jsondoc) pony HashIs[A: A] HashIs[A: A] ============ [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L84) ``` primitive val HashIs[A: A] is HashFunction[A] val, HashFunction64[A] val ``` #### Implements * [HashFunction](collections-hashfunction)[A] val * [HashFunction64](collections-hashfunction64)[A] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L84) ``` new val create() : HashIs[A] val^ ``` #### Returns * [HashIs](index)[A] val^ Public Functions ---------------- ### hash [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L85) Hash the identity rather than the contents. ``` fun box hash( x: box->A!) : USize val ``` #### Parameters * x: box->A! #### Returns * [USize](builtin-usize) val ### hash64 [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L91) Hash the identity rather than the contents. ``` fun box hash64( x: box->A!) : U64 val ``` #### Parameters * x: box->A! #### Returns * [U64](builtin-u64) val ### eq [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L97) Determine equality by identity rather than structurally. ``` fun box eq( x: box->A!, y: box->A!) : Bool val ``` #### Parameters * x: box->A! * y: box->A! #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L85) ``` fun box ne( that: HashIs[A] val) : Bool val ``` #### Parameters * that: [HashIs](index)[A] val #### Returns * [Bool](builtin-bool) val pony NetAuth NetAuth ======= [[Source]](https://stdlib.ponylang.io/src/net/auth/#L1) ``` primitive val NetAuth ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/net/auth/#L2) ``` new val create( from: AmbientAuth val) : NetAuth val^ ``` #### Parameters * from: [AmbientAuth](builtin-ambientauth) val #### Returns * [NetAuth](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/net/auth/#L2) ``` fun box eq( that: NetAuth val) : Bool val ``` #### Parameters * that: [NetAuth](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/net/auth/#L2) ``` fun box ne( that: NetAuth val) : Bool val ``` #### Parameters * that: [NetAuth](index) val #### Returns * [Bool](builtin-bool) val pony Set[A: (Hashable #read & Equatable[A] #read)] Set[A: ([Hashable](collections-hashable) #read & [Equatable](builtin-equatable)[A] #read)] ========================================================================================== [[Source]](https://stdlib.ponylang.io/src/collections/set/#L1) ``` type Set[A: (Hashable #read & Equatable[A] #read)] is HashSet[A, HashEq[A] val] ref ``` #### Type Alias For * [HashSet](collections-hashset)[A, [HashEq](collections-hasheq)[A] val] ref pony Backpressure Backpressure ============ [[Source]](https://stdlib.ponylang.io/src/backpressure/backpressure/#L95) ``` primitive val Backpressure ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/backpressure/backpressure/#L95) ``` new val create() : Backpressure val^ ``` #### Returns * [Backpressure](index) val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/backpressure/backpressure/#L96) ``` fun box apply( auth: (AmbientAuth val | ApplyReleaseBackpressureAuth val)) : None val ``` #### Parameters * auth: ([AmbientAuth](builtin-ambientauth) val | [ApplyReleaseBackpressureAuth](backpressure-applyreleasebackpressureauth) val) #### Returns * [None](builtin-none) val ### release [[Source]](https://stdlib.ponylang.io/src/backpressure/backpressure/#L99) ``` fun box release( auth: (AmbientAuth val | ApplyReleaseBackpressureAuth val)) : None val ``` #### Parameters * auth: ([AmbientAuth](builtin-ambientauth) val | [ApplyReleaseBackpressureAuth](backpressure-applyreleasebackpressureauth) val) #### Returns * [None](builtin-none) val ### eq [[Source]](https://stdlib.ponylang.io/src/backpressure/backpressure/#L96) ``` fun box eq( that: Backpressure val) : Bool val ``` #### Parameters * that: [Backpressure](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/backpressure/backpressure/#L96) ``` fun box ne( that: Backpressure val) : Bool val ``` #### Parameters * that: [Backpressure](index) val #### Returns * [Bool](builtin-bool) val pony HashSet[A: Any #share, H: HashFunction[A] val] HashSet[A: [Any](builtin-any) #share, H: [HashFunction](collections-hashfunction)[A] val] ========================================================================================= [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L7) A set, built on top of persistent Map. This is implemented as map of an alias of a type to itself. ``` class val HashSet[A: Any #share, H: HashFunction[A] val] is Comparable[HashSet[A, H] box] ref ``` #### Implements * [Comparable](builtin-comparable)[[HashSet](index)[A, H] box] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L15) ``` new val create() : HashSet[A, H] val^ ``` #### Returns * [HashSet](index)[A, H] val^ Public Functions ---------------- ### size [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L21) Return the number of elements in the set. ``` fun box size() : USize val ``` #### Returns * [USize](builtin-usize) val ### apply [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L27) Return the value if it is in the set, otherwise raise an error. ``` fun box apply( value: val->A) : val->A ? ``` #### Parameters * value: val->A #### Returns * val->A ? ### contains [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L33) Check whether the set contains the value. ``` fun box contains( value: val->A) : Bool val ``` #### Parameters * value: val->A #### Returns * [Bool](builtin-bool) val ### add [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L39) Return a set with the value added. ``` fun val add( value: val->A) : HashSet[A, H] val ``` #### Parameters * value: val->A #### Returns * [HashSet](index)[A, H] val ### sub [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L45) Return a set with the value removed. ``` fun val sub( value: val->A) : HashSet[A, H] val ``` #### Parameters * value: val->A #### Returns * [HashSet](index)[A, H] val ### op\_or [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L51) Return a set with the elements of both this and that. ``` fun val op_or( that: (HashSet[A, H] val | Iterator[A] ref)) : HashSet[A, H] val ``` #### Parameters * that: ([HashSet](index)[A, H] val | [Iterator](builtin-iterator)[A] ref) #### Returns * [HashSet](index)[A, H] val ### op\_and [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L66) Return a set with the elements that are in both this and that. ``` fun val op_and( that: (HashSet[A, H] val | Iterator[A] ref)) : HashSet[A, H] val ``` #### Parameters * that: ([HashSet](index)[A, H] val | [Iterator](builtin-iterator)[A] ref) #### Returns * [HashSet](index)[A, H] val ### op\_xor [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L83) Return a set with elements that are in either this or that, but not both. ``` fun val op_xor( that: (HashSet[A, H] val | Iterator[A] ref)) : HashSet[A, H] val ``` #### Parameters * that: ([HashSet](index)[A, H] val | [Iterator](builtin-iterator)[A] ref) #### Returns * [HashSet](index)[A, H] val ### without [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L102) Return a set with the elements of this that are not in that. ``` fun val without( that: (HashSet[A, H] val | Iterator[A] ref)) : HashSet[A, H] val ``` #### Parameters * that: ([HashSet](index)[A, H] val | [Iterator](builtin-iterator)[A] ref) #### Returns * [HashSet](index)[A, H] val ### eq [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L119) Return true if this and that contain the same elements. ``` fun box eq( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val ### lt [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L125) Return true if every element in this is also in that, and this has fewer elements than that. ``` fun box lt( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val ### le [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L132) Return true if every element in this is also in that. ``` fun box le( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val ### gt [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L141) Return true if every element in that is also in this, and this has more elements than that. ``` fun box gt( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val ### ge [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L148) Return true if every element in that is also in this. ``` fun box ge( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val ### values [[Source]](https://stdlib.ponylang.io/src/collections-persistent/set/#L154) Return an iterator over the values in the set. ``` fun box values() : Iterator[A] ref^ ``` #### Returns * [Iterator](builtin-iterator)[A] ref^ ### compare [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L28) ``` fun box compare( that: HashSet[A, H] box) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val) ### ne [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L20) ``` fun box ne( that: HashSet[A, H] box) : Bool val ``` #### Parameters * that: [HashSet](index)[A, H] box #### Returns * [Bool](builtin-bool) val pony Time Package Time Package ============ The Time Package provides classes and methods for timing operations, dealing with dates and times, and scheduling tasks. Public Types ------------ * [actor Timers](time-timers) * [interface TimerNotify](time-timernotify) * [class Timer](time-timer) * [primitive Time](time-time) * [class PosixDate](time-posixdate) * [primitive Nanos](time-nanos) pony U128 U128 ==== [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L559) ``` primitive val U128 is UnsignedInteger[U128 val] val ``` #### Implements * [UnsignedInteger](builtin-unsignedinteger)[[U128](index) val] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L560) ``` new val create( value: U128 val) : U128 val^ ``` #### Parameters * value: [U128](index) val #### Returns * [U128](index) val^ ### from[A: (([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](builtin-i32) val | [I64](builtin-i64) val | [I128](builtin-i128) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val | [U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](index) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val | [F32](builtin-f32) val | [F64](builtin-f64) val) & [Real](builtin-real)[A] val)] [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L561) ``` new val from[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[A] val)]( a: A) : U128 val^ ``` #### Parameters * a: A #### Returns * [U128](index) val^ ### min\_value [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L563) ``` new val min_value() : U128 val^ ``` #### Returns * [U128](index) val^ ### max\_value [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L564) ``` new val max_value() : U128 val^ ``` #### Returns * [U128](index) val^ Public Functions ---------------- ### next\_pow2 [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L566) ``` fun box next_pow2() : U128 val ``` #### Returns * [U128](index) val ### abs [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L570) ``` fun box abs() : U128 val ``` #### Returns * [U128](index) val ### bit\_reverse [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L571) ``` fun box bit_reverse() : U128 val ``` #### Returns * [U128](index) val ### bswap [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L572) ``` fun box bswap() : U128 val ``` #### Returns * [U128](index) val ### popcount [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L573) ``` fun box popcount() : U128 val ``` #### Returns * [U128](index) val ### clz [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L574) ``` fun box clz() : U128 val ``` #### Returns * [U128](index) val ### ctz [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L575) ``` fun box ctz() : U128 val ``` #### Returns * [U128](index) val ### clz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L577) Unsafe operation. If this is 0, the result is undefined. ``` fun box clz_unsafe() : U128 val ``` #### Returns * [U128](index) val ### ctz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L584) Unsafe operation. If this is 0, the result is undefined. ``` fun box ctz_unsafe() : U128 val ``` #### Returns * [U128](index) val ### bitwidth [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L591) ``` fun box bitwidth() : U128 val ``` #### Returns * [U128](index) val ### bytewidth [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L593) ``` fun box bytewidth() : USize val ``` #### Returns * [USize](builtin-usize) val ### min [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L595) ``` fun box min( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### max [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L596) ``` fun box max( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### hash [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L598) ``` fun box hash() : USize val ``` #### Returns * [USize](builtin-usize) val ### hash64 [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L608) ``` fun box hash64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### string [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L611) ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### mul [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L614) ``` fun box mul( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### divrem [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L643) ``` fun box divrem( y: U128 val) : (U128 val , U128 val) ``` #### Parameters * y: [U128](index) val #### Returns * ([U128](index) val , [U128](index) val) ### div [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L673) ``` fun box div( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### rem [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L681) ``` fun box rem( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### mul\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L689) Unsafe operation. If the operation overflows, the result is undefined. ``` fun box mul_unsafe( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### divrem\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L700) Unsafe operation. If y is 0, the result is undefined. If the operation overflows, the result is undefined. ``` fun box divrem_unsafe( y: U128 val) : (U128 val , U128 val) ``` #### Parameters * y: [U128](index) val #### Returns * ([U128](index) val , [U128](index) val) ### div\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L712) Unsafe operation. If y is 0, the result is undefined. If the operation overflows, the result is undefined. ``` fun box div_unsafe( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### rem\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L724) Unsafe operation. If y is 0, the result is undefined. If the operation overflows, the result is undefined. ``` fun box rem_unsafe( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### f32 [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L736) ``` fun box f32() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64 [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L744) ``` fun box f64() : F64 val ``` #### Returns * [F64](builtin-f64) val ### f32\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L778) Unsafe operation. If the value doesn't fit in the destination type, the result is undefined. ``` fun box f32_unsafe() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L785) Unsafe operation. If the value doesn't fit in the destination type, the result is undefined. ``` fun box f64_unsafe() : F64 val ``` #### Returns * [F64](builtin-f64) val ### addc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L792) ``` fun box addc( y: U128 val) : (U128 val , Bool val) ``` #### Parameters * y: [U128](index) val #### Returns * ([U128](index) val , [Bool](builtin-bool) val) ### subc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L800) ``` fun box subc( y: U128 val) : (U128 val , Bool val) ``` #### Parameters * y: [U128](index) val #### Returns * ([U128](index) val , [Bool](builtin-bool) val) ### mulc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L808) ``` fun box mulc( y: U128 val) : (U128 val , Bool val) ``` #### Parameters * y: [U128](index) val #### Returns * ([U128](index) val , [Bool](builtin-bool) val) ### divc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L817) ``` fun box divc( y: U128 val) : (U128 val , Bool val) ``` #### Parameters * y: [U128](index) val #### Returns * ([U128](index) val , [Bool](builtin-bool) val) ### remc [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L820) ``` fun box remc( y: U128 val) : (U128 val , Bool val) ``` #### Parameters * y: [U128](index) val #### Returns * ([U128](index) val , [Bool](builtin-bool) val) ### add\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L823) ``` fun box add_partial( y: U128 val) : U128 val ? ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ? ### sub\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L826) ``` fun box sub_partial( y: U128 val) : U128 val ? ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ? ### mul\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L829) ``` fun box mul_partial( y: U128 val) : U128 val ? ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ? ### div\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L832) ``` fun box div_partial( y: U128 val) : U128 val ? ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ? ### rem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L835) ``` fun box rem_partial( y: U128 val) : U128 val ? ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ? ### divrem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/unsigned/#L838) ``` fun box divrem_partial( y: U128 val) : (U128 val , U128 val) ? ``` #### Parameters * y: [U128](index) val #### Returns * ([U128](index) val , [U128](index) val) ? ### shl ``` fun box shl( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### shr ``` fun box shr( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### fld ``` fun box fld( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### fldc ``` fun box fldc( y: U128 val) : (U128 val , Bool val) ``` #### Parameters * y: [U128](index) val #### Returns * ([U128](index) val , [Bool](builtin-bool) val) ### fld\_partial ``` fun box fld_partial( y: U128 val) : U128 val ? ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ? ### fld\_unsafe ``` fun box fld_unsafe( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### mod ``` fun box mod( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### modc ``` fun box modc( y: U128 val) : (U128 val , Bool val) ``` #### Parameters * y: [U128](index) val #### Returns * ([U128](index) val , [Bool](builtin-bool) val) ### mod\_partial ``` fun box mod_partial( y: U128 val) : U128 val ? ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ? ### mod\_unsafe ``` fun box mod_unsafe( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### shl\_unsafe ``` fun box shl_unsafe( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### shr\_unsafe ``` fun box shr_unsafe( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### rotl ``` fun box rotl( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### rotr ``` fun box rotr( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### add\_unsafe ``` fun box add_unsafe( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### sub\_unsafe ``` fun box sub_unsafe( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### neg\_unsafe ``` fun box neg_unsafe() : U128 val ``` #### Returns * [U128](index) val ### op\_and ``` fun box op_and( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### op\_or ``` fun box op_or( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### op\_xor ``` fun box op_xor( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### op\_not ``` fun box op_not() : U128 val ``` #### Returns * [U128](index) val ### add ``` fun box add( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### sub ``` fun box sub( y: U128 val) : U128 val ``` #### Parameters * y: [U128](index) val #### Returns * [U128](index) val ### neg ``` fun box neg() : U128 val ``` #### Returns * [U128](index) val ### eq ``` fun box eq( y: U128 val) : Bool val ``` #### Parameters * y: [U128](index) val #### Returns * [Bool](builtin-bool) val ### ne ``` fun box ne( y: U128 val) : Bool val ``` #### Parameters * y: [U128](index) val #### Returns * [Bool](builtin-bool) val ### lt ``` fun box lt( y: U128 val) : Bool val ``` #### Parameters * y: [U128](index) val #### Returns * [Bool](builtin-bool) val ### le ``` fun box le( y: U128 val) : Bool val ``` #### Parameters * y: [U128](index) val #### Returns * [Bool](builtin-bool) val ### ge ``` fun box ge( y: U128 val) : Bool val ``` #### Parameters * y: [U128](index) val #### Returns * [Bool](builtin-bool) val ### gt ``` fun box gt( y: U128 val) : Bool val ``` #### Parameters * y: [U128](index) val #### Returns * [Bool](builtin-bool) val ### i8 ``` fun box i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 ``` fun box i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 ``` fun box i32() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64 ``` fun box i64() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128 ``` fun box i128() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong ``` fun box ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize ``` fun box isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8 ``` fun box u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 ``` fun box u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 ``` fun box u32() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64 ``` fun box u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 ``` fun box u128() : U128 val ``` #### Returns * [U128](index) val ### ulong ``` fun box ulong() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize ``` fun box usize() : USize val ``` #### Returns * [USize](builtin-usize) val ### i8\_unsafe ``` fun box i8_unsafe() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16\_unsafe ``` fun box i16_unsafe() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32\_unsafe ``` fun box i32_unsafe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64\_unsafe ``` fun box i64_unsafe() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128\_unsafe ``` fun box i128_unsafe() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong\_unsafe ``` fun box ilong_unsafe() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize\_unsafe ``` fun box isize_unsafe() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8\_unsafe ``` fun box u8_unsafe() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16\_unsafe ``` fun box u16_unsafe() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32\_unsafe ``` fun box u32_unsafe() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64\_unsafe ``` fun box u64_unsafe() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128\_unsafe ``` fun box u128_unsafe() : U128 val ``` #### Returns * [U128](index) val ### ulong\_unsafe ``` fun box ulong_unsafe() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize\_unsafe ``` fun box usize_unsafe() : USize val ``` #### Returns * [USize](builtin-usize) val ### compare ``` fun box compare( that: U128 val) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [U128](index) val #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val)
programming_docs
pony SourceLoc SourceLoc ========= [[Source]](https://stdlib.ponylang.io/src/builtin/source_loc/#L1) Represents a location in a Pony source file, as reported by `__loc`. ``` interface val SourceLoc ``` Public Functions ---------------- ### file [[Source]](https://stdlib.ponylang.io/src/builtin/source_loc/#L5) Name and path of source file. ``` fun box file() : String val ``` #### Returns * [String](builtin-string) val ### type\_name [[Source]](https://stdlib.ponylang.io/src/builtin/source_loc/#L10) Name of nearest class, actor, primitive, struct, interface, or trait. ``` fun box type_name() : String val ``` #### Returns * [String](builtin-string) val ### method\_name [[Source]](https://stdlib.ponylang.io/src/builtin/source_loc/#L15) Name of containing method. ``` fun box method_name() : String val ``` #### Returns * [String](builtin-string) val ### line [[Source]](https://stdlib.ponylang.io/src/builtin/source_loc/#L20) Line number within file. Line numbers start at 1. ``` fun box line() : USize val ``` #### Returns * [USize](builtin-usize) val ### pos [[Source]](https://stdlib.ponylang.io/src/builtin/source_loc/#L26) Character position on line. Character positions start at 1. ``` fun box pos() : USize val ``` #### Returns * [USize](builtin-usize) val pony Equal Equal ===== [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L5) ``` primitive val Equal is Equatable[(Less val | Equal val | Greater val)] ref ``` #### Implements * [Equatable](builtin-equatable)[([Less](builtin-less) val | [Equal](index) val | [Greater](builtin-greater) val)] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L5) ``` new val create() : Equal val^ ``` #### Returns * [Equal](index) val^ Public Functions ---------------- ### string [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L6) ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### eq [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L19) ``` fun box eq( that: (Less val | Equal val | Greater val)) : Bool val ``` #### Parameters * that: ([Less](builtin-less) val | [Equal](index) val | [Greater](builtin-greater) val) #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L20) ``` fun box ne( that: (Less val | Equal val | Greater val)) : Bool val ``` #### Parameters * that: ([Less](builtin-less) val | [Equal](index) val | [Greater](builtin-greater) val) #### Returns * [Bool](builtin-bool) val pony TestList TestList ======== [[Source]](https://stdlib.ponylang.io/src/ponytest/test_list/#L1) Source of unit tests for a PonyTest object. See package doc string for further information and example use. ``` trait ref TestList ``` Public Functions ---------------- ### tests [[Source]](https://stdlib.ponylang.io/src/ponytest/test_list/#L7) Add all the tests in this suite to the given test object. Typically the implementation of this function will be of the form: ``` fun tests(test: PonyTest) => test(_TestClass1) test(_TestClass2) test(_TestClass3) ``` ``` fun tag tests( test: PonyTest tag) : None val ``` #### Parameters * test: [PonyTest](ponytest-ponytest) tag #### Returns * [None](builtin-none) val pony I64 I64 === [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L278) ``` primitive val I64 is SignedInteger[I64 val, U64 val] val ``` #### Implements * [SignedInteger](builtin-signedinteger)[[I64](index) val, [U64](builtin-u64) val] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L279) ``` new val create( value: I64 val) : I64 val^ ``` #### Parameters * value: [I64](index) val #### Returns * [I64](index) val^ ### from[A: (([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](builtin-i32) val | [I64](index) val | [I128](builtin-i128) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val | [U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val | [F32](builtin-f32) val | [F64](builtin-f64) val) & [Real](builtin-real)[A] val)] [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L280) ``` new val from[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[A] val)]( a: A) : I64 val^ ``` #### Parameters * a: A #### Returns * [I64](index) val^ ### min\_value [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L282) ``` new val min_value() : I64 val^ ``` #### Returns * [I64](index) val^ ### max\_value [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L283) ``` new val max_value() : I64 val^ ``` #### Returns * [I64](index) val^ Public Functions ---------------- ### abs [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L285) ``` fun box abs() : U64 val ``` #### Returns * [U64](builtin-u64) val ### bit\_reverse [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L286) ``` fun box bit_reverse() : I64 val ``` #### Returns * [I64](index) val ### bswap [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L287) ``` fun box bswap() : I64 val ``` #### Returns * [I64](index) val ### popcount [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L288) ``` fun box popcount() : U64 val ``` #### Returns * [U64](builtin-u64) val ### clz [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L289) ``` fun box clz() : U64 val ``` #### Returns * [U64](builtin-u64) val ### ctz [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L290) ``` fun box ctz() : U64 val ``` #### Returns * [U64](builtin-u64) val ### clz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L292) Unsafe operation. If this is 0, the result is undefined. ``` fun box clz_unsafe() : U64 val ``` #### Returns * [U64](builtin-u64) val ### ctz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L299) Unsafe operation. If this is 0, the result is undefined. ``` fun box ctz_unsafe() : U64 val ``` #### Returns * [U64](builtin-u64) val ### bitwidth [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L306) ``` fun box bitwidth() : U64 val ``` #### Returns * [U64](builtin-u64) val ### bytewidth [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L308) ``` fun box bytewidth() : USize val ``` #### Returns * [USize](builtin-usize) val ### min [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L310) ``` fun box min( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### max [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L311) ``` fun box max( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### fld [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L313) ``` fun box fld( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### fld\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L316) ``` fun box fld_unsafe( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### mod [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L319) ``` fun box mod( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### mod\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L322) ``` fun box mod_unsafe( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### hash [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L325) ``` fun box hash() : USize val ``` #### Returns * [USize](builtin-usize) val ### addc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L327) ``` fun box addc( y: I64 val) : (I64 val , Bool val) ``` #### Parameters * y: [I64](index) val #### Returns * ([I64](index) val , [Bool](builtin-bool) val) ### subc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L330) ``` fun box subc( y: I64 val) : (I64 val , Bool val) ``` #### Parameters * y: [I64](index) val #### Returns * ([I64](index) val , [Bool](builtin-bool) val) ### mulc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L333) ``` fun box mulc( y: I64 val) : (I64 val , Bool val) ``` #### Parameters * y: [I64](index) val #### Returns * ([I64](index) val , [Bool](builtin-bool) val) ### divc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L336) ``` fun box divc( y: I64 val) : (I64 val , Bool val) ``` #### Parameters * y: [I64](index) val #### Returns * ([I64](index) val , [Bool](builtin-bool) val) ### remc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L339) ``` fun box remc( y: I64 val) : (I64 val , Bool val) ``` #### Parameters * y: [I64](index) val #### Returns * ([I64](index) val , [Bool](builtin-bool) val) ### fldc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L342) ``` fun box fldc( y: I64 val) : (I64 val , Bool val) ``` #### Parameters * y: [I64](index) val #### Returns * ([I64](index) val , [Bool](builtin-bool) val) ### modc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L345) ``` fun box modc( y: I64 val) : (I64 val , Bool val) ``` #### Parameters * y: [I64](index) val #### Returns * ([I64](index) val , [Bool](builtin-bool) val) ### add\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L348) ``` fun box add_partial( y: I64 val) : I64 val ? ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ? ### sub\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L351) ``` fun box sub_partial( y: I64 val) : I64 val ? ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ? ### mul\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L354) ``` fun box mul_partial( y: I64 val) : I64 val ? ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ? ### div\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L357) ``` fun box div_partial( y: I64 val) : I64 val ? ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ? ### rem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L360) ``` fun box rem_partial( y: I64 val) : I64 val ? ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ? ### divrem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L363) ``` fun box divrem_partial( y: I64 val) : (I64 val , I64 val) ? ``` #### Parameters * y: [I64](index) val #### Returns * ([I64](index) val , [I64](index) val) ? ### fld\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L366) ``` fun box fld_partial( y: I64 val) : I64 val ? ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ? ### mod\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L369) ``` fun box mod_partial( y: I64 val) : I64 val ? ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ? ### shl ``` fun box shl( y: U64 val) : I64 val ``` #### Parameters * y: [U64](builtin-u64) val #### Returns * [I64](index) val ### shr ``` fun box shr( y: U64 val) : I64 val ``` #### Parameters * y: [U64](builtin-u64) val #### Returns * [I64](index) val ### shl\_unsafe ``` fun box shl_unsafe( y: U64 val) : I64 val ``` #### Parameters * y: [U64](builtin-u64) val #### Returns * [I64](index) val ### shr\_unsafe ``` fun box shr_unsafe( y: U64 val) : I64 val ``` #### Parameters * y: [U64](builtin-u64) val #### Returns * [I64](index) val ### string ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### add\_unsafe ``` fun box add_unsafe( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### sub\_unsafe ``` fun box sub_unsafe( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### mul\_unsafe ``` fun box mul_unsafe( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### div\_unsafe ``` fun box div_unsafe( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### divrem\_unsafe ``` fun box divrem_unsafe( y: I64 val) : (I64 val , I64 val) ``` #### Parameters * y: [I64](index) val #### Returns * ([I64](index) val , [I64](index) val) ### rem\_unsafe ``` fun box rem_unsafe( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### neg\_unsafe ``` fun box neg_unsafe() : I64 val ``` #### Returns * [I64](index) val ### op\_and ``` fun box op_and( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### op\_or ``` fun box op_or( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### op\_xor ``` fun box op_xor( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### op\_not ``` fun box op_not() : I64 val ``` #### Returns * [I64](index) val ### add ``` fun box add( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### sub ``` fun box sub( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### mul ``` fun box mul( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### div ``` fun box div( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### divrem ``` fun box divrem( y: I64 val) : (I64 val , I64 val) ``` #### Parameters * y: [I64](index) val #### Returns * ([I64](index) val , [I64](index) val) ### rem ``` fun box rem( y: I64 val) : I64 val ``` #### Parameters * y: [I64](index) val #### Returns * [I64](index) val ### neg ``` fun box neg() : I64 val ``` #### Returns * [I64](index) val ### eq ``` fun box eq( y: I64 val) : Bool val ``` #### Parameters * y: [I64](index) val #### Returns * [Bool](builtin-bool) val ### ne ``` fun box ne( y: I64 val) : Bool val ``` #### Parameters * y: [I64](index) val #### Returns * [Bool](builtin-bool) val ### lt ``` fun box lt( y: I64 val) : Bool val ``` #### Parameters * y: [I64](index) val #### Returns * [Bool](builtin-bool) val ### le ``` fun box le( y: I64 val) : Bool val ``` #### Parameters * y: [I64](index) val #### Returns * [Bool](builtin-bool) val ### ge ``` fun box ge( y: I64 val) : Bool val ``` #### Parameters * y: [I64](index) val #### Returns * [Bool](builtin-bool) val ### gt ``` fun box gt( y: I64 val) : Bool val ``` #### Parameters * y: [I64](index) val #### Returns * [Bool](builtin-bool) val ### hash64 ``` fun box hash64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### i8 ``` fun box i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 ``` fun box i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 ``` fun box i32() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64 ``` fun box i64() : I64 val ``` #### Returns * [I64](index) val ### i128 ``` fun box i128() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong ``` fun box ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize ``` fun box isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8 ``` fun box u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 ``` fun box u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 ``` fun box u32() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64 ``` fun box u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 ``` fun box u128() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong ``` fun box ulong() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize ``` fun box usize() : USize val ``` #### Returns * [USize](builtin-usize) val ### f32 ``` fun box f32() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64 ``` fun box f64() : F64 val ``` #### Returns * [F64](builtin-f64) val ### i8\_unsafe ``` fun box i8_unsafe() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16\_unsafe ``` fun box i16_unsafe() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32\_unsafe ``` fun box i32_unsafe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64\_unsafe ``` fun box i64_unsafe() : I64 val ``` #### Returns * [I64](index) val ### i128\_unsafe ``` fun box i128_unsafe() : I128 val ``` #### Returns * [I128](builtin-i128) val ### ilong\_unsafe ``` fun box ilong_unsafe() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize\_unsafe ``` fun box isize_unsafe() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8\_unsafe ``` fun box u8_unsafe() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16\_unsafe ``` fun box u16_unsafe() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32\_unsafe ``` fun box u32_unsafe() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64\_unsafe ``` fun box u64_unsafe() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128\_unsafe ``` fun box u128_unsafe() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong\_unsafe ``` fun box ulong_unsafe() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize\_unsafe ``` fun box usize_unsafe() : USize val ``` #### Returns * [USize](builtin-usize) val ### f32\_unsafe ``` fun box f32_unsafe() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64\_unsafe ``` fun box f64_unsafe() : F64 val ``` #### Returns * [F64](builtin-f64) val ### compare ``` fun box compare( that: I64 val) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [I64](index) val #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val) pony Builtin package Builtin package =============== The builtin package is home to the following standard library members: 1. Types the compiler needs to know exist, such as None. 2. Types with "magic" internal workings that must be supplied directly by the compiler, such as U32. 3. Any types needed by others in builtin. The public types that are defined in this package will always be in scope for every Pony source file. For details on specific packages, see their individual entity entries. Public Types ------------ * [primitive U8](builtin-u8) * [primitive U16](builtin-u16) * [primitive U32](builtin-u32) * [primitive U64](builtin-u64) * [primitive ULong](builtin-ulong) * [primitive USize](builtin-usize) * [primitive U128](builtin-u128) * [type Unsigned](builtin-unsigned) * [interface Stringable](builtin-stringable) * [class String](builtin-string) * [class StringBytes](builtin-stringbytes) * [class StringRunes](builtin-stringrunes) * [interface InputNotify](builtin-inputnotify) * [interface InputStream](builtin-inputstream) * [actor Stdin](builtin-stdin) * [type ByteSeq](builtin-byteseq) * [interface ByteSeqIter](builtin-byteseqiter) * [interface OutStream](builtin-outstream) * [actor StdStream](builtin-stdstream) * [interface SourceLoc](builtin-sourceloc) * [primitive I8](builtin-i8) * [primitive I16](builtin-i16) * [primitive I32](builtin-i32) * [primitive I64](builtin-i64) * [primitive ILong](builtin-ilong) * [primitive ISize](builtin-isize) * [primitive I128](builtin-i128) * [type Signed](builtin-signed) * [interface Seq](builtin-seq) * [struct RuntimeOptions](builtin-runtimeoptions) * [trait Real](builtin-real) * [trait Integer](builtin-integer) * [trait SignedInteger](builtin-signedinteger) * [trait UnsignedInteger](builtin-unsignedinteger) * [trait FloatingPoint](builtin-floatingpoint) * [type Number](builtin-number) * [type Int](builtin-int) * [interface ReadSeq](builtin-readseq) * [interface ReadElement](builtin-readelement) * [struct Pointer](builtin-pointer) * [primitive Platform](builtin-platform) * [struct NullablePointer](builtin-nullablepointer) * [primitive None](builtin-none) * [interface Iterator](builtin-iterator) * [primitive F32](builtin-f32) * [primitive F64](builtin-f64) * [type Float](builtin-float) * [class Env](builtin-env) * [primitive DoNotOptimise](builtin-donotoptimise) * [interface DisposableActor](builtin-disposableactor) * [primitive Less](builtin-less) * [primitive Equal](builtin-equal) * [primitive Greater](builtin-greater) * [type Compare](builtin-compare) * [interface HasEq](builtin-haseq) * [interface Equatable](builtin-equatable) * [interface Comparable](builtin-comparable) * [primitive Bool](builtin-bool) * [type AsioEventID](builtin-asioeventid) * [interface AsioEventNotify](builtin-asioeventnotify) * [primitive AsioEvent](builtin-asioevent) * [class Array](builtin-array) * [class ArrayKeys](builtin-arraykeys) * [class ArrayValues](builtin-arrayvalues) * [class ArrayPairs](builtin-arraypairs) * [interface Any](builtin-any) * [primitive AmbientAuth](builtin-ambientauth)
programming_docs
pony EnvVars EnvVars ======= [[Source]](https://stdlib.ponylang.io/src/cli/env_vars/#L3) ``` primitive val EnvVars ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/cli/env_vars/#L3) ``` new val create() : EnvVars val^ ``` #### Returns * [EnvVars](index) val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/cli/env_vars/#L4) Turns an array of strings that look like environment variables, ie. key=value, into a map of string to string. Can optionally filter for keys matching a 'prefix', and will squash resulting keys to lowercase iff 'squash' is true. So: = becomes: {KEY, VALUE} or {key, VALUE} ``` fun box apply( envs: (Array[String val] box | None val), prefix: String val = "", squash: Bool val = false) : HashMap[String val, String val, HashEq[String val] val] val ``` #### Parameters * envs: ([Array](builtin-array)[[String](builtin-string) val] box | [None](builtin-none) val) * prefix: [String](builtin-string) val = "" * squash: [Bool](builtin-bool) val = false #### Returns * [HashMap](collections-hashmap)[[String](builtin-string) val, [String](builtin-string) val, [HashEq](collections-hasheq)[[String](builtin-string) val] val] val ### eq [[Source]](https://stdlib.ponylang.io/src/cli/env_vars/#L4) ``` fun box eq( that: EnvVars val) : Bool val ``` #### Parameters * that: [EnvVars](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/cli/env_vars/#L4) ``` fun box ne( that: EnvVars val) : Bool val ``` #### Parameters * that: [EnvVars](index) val #### Returns * [Bool](builtin-bool) val pony TimerNotify TimerNotify =========== [[Source]](https://stdlib.ponylang.io/src/time/timer_notify/#L1) Notifications for timer. ``` interface ref TimerNotify ``` Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/time/timer_notify/#L5) Called with the the number of times the timer has fired since this was last called. Usually, the value of `count` will be 1. If it is not 1, it means that the timer isn't firing on schedule. For example, if your timer is set to fire every 10 milliseconds, and `count` is 2, that means it has been between 20-29 milliseconds since the last time your timer fired. Non 1 values for a timer are rare and indicate a system under heavy load. Return true to reschedule the timer (if it has an interval), or false to cancel the timer (even if it has an interval). ``` fun ref apply( timer: Timer ref, count: U64 val) : Bool val ``` #### Parameters * timer: [Timer](time-timer) ref * count: [U64](builtin-u64) val #### Returns * [Bool](builtin-bool) val ### cancel [[Source]](https://stdlib.ponylang.io/src/time/timer_notify/#L21) Called if the timer is cancelled. This is also called if the notifier returns false from its `apply` method. ``` fun ref cancel( timer: Timer ref) : None val ``` #### Parameters * timer: [Timer](time-timer) ref #### Returns * [None](builtin-none) val pony AsioEvent AsioEvent ========= [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L6) Functions for asynchronous event notification. ``` primitive val AsioEvent ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L6) ``` new val create() : AsioEvent val^ ``` #### Returns * [AsioEvent](index) val^ Public Functions ---------------- ### none [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L10) An empty event. ``` fun box none() : Pointer[AsioEvent val] tag ``` #### Returns * [Pointer](builtin-pointer)[[AsioEvent](index) val] tag ### readable [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L16) Returns true if the flags contain the readable flag. ``` fun box readable( flags: U32 val) : Bool val ``` #### Parameters * flags: [U32](builtin-u32) val #### Returns * [Bool](builtin-bool) val ### writeable [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L22) Returns true if the flags contain the writeable flag. ``` fun box writeable( flags: U32 val) : Bool val ``` #### Parameters * flags: [U32](builtin-u32) val #### Returns * [Bool](builtin-bool) val ### disposable [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L28) Returns true if the event should be disposed of. ``` fun box disposable( flags: U32 val) : Bool val ``` #### Parameters * flags: [U32](builtin-u32) val #### Returns * [Bool](builtin-bool) val ### oneshotable [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L34) Returns true if the flags contain the oneshot flag. ``` fun box oneshotable( flags: U32 val) : Bool val ``` #### Parameters * flags: [U32](builtin-u32) val #### Returns * [Bool](builtin-bool) val ### dispose [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L40) ``` fun box dispose() : U32 val ``` #### Returns * [U32](builtin-u32) val ### read [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L42) ``` fun box read() : U32 val ``` #### Returns * [U32](builtin-u32) val ### write [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L44) ``` fun box write() : U32 val ``` #### Returns * [U32](builtin-u32) val ### timer [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L46) ``` fun box timer() : U32 val ``` #### Returns * [U32](builtin-u32) val ### signal [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L48) ``` fun box signal() : U32 val ``` #### Returns * [U32](builtin-u32) val ### read\_write [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L50) ``` fun box read_write() : U32 val ``` #### Returns * [U32](builtin-u32) val ### oneshot [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L52) ``` fun box oneshot() : U32 val ``` #### Returns * [U32](builtin-u32) val ### read\_write\_oneshot [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L54) ``` fun box read_write_oneshot() : U32 val ``` #### Returns * [U32](builtin-u32) val ### eq [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L10) ``` fun box eq( that: AsioEvent val) : Bool val ``` #### Parameters * that: [AsioEvent](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/builtin/asio_event/#L10) ``` fun box ne( that: AsioEvent val) : Bool val ``` #### Parameters * that: [AsioEvent](index) val #### Returns * [Bool](builtin-bool) val pony List[A: A] List[A: A] ========== [[Source]](https://stdlib.ponylang.io/src/collections-persistent/list/#L1) A persistent list with functional transformations. Usage ----- ``` use "collections/persistent" actor Main new create(env: Env) => try let l1 = Lists[U32]([2; 4; 6; 8]) // List(2, 4, 6, 8) let empty = Lists[U32].empty() // List() // prepend() returns a new List, leaving the // old list unchanged let l2 = empty.prepend(3) // List(3) let l3 = l2.prepend(2) // List(2, 3) let l4 = l3.prepend(1) // List(1, 2, 3) let l4_head = l4.head() // 1 let l4_tail = l4.tail() // List(2, 3) l4_head == 1 Lists[U32].eq(l4, Lists[U32]([1; 2; 3]))? Lists[U32].eq(l4_tail, Lists[U32]([2; 3]))? let doubled = l4.map[U32]({(x) => x * 2 }) Lists[U32].eq(doubled, Lists[U32]([2; 4; 6]))? end ``` ``` type List[A: A] is (Cons[A] val | Nil[A] val) ``` #### Type Alias For * ([Cons](collections-persistent-cons)[A] val | [Nil](collections-persistent-nil)[A] val) pony DebugOut DebugOut ======== [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L19) ``` primitive val DebugOut ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L19) ``` new val create() : DebugOut val^ ``` #### Returns * [DebugOut](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L20) ``` fun box eq( that: DebugOut val) : Bool val ``` #### Parameters * that: [DebugOut](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/debug/debug/#L20) ``` fun box ne( that: DebugOut val) : Bool val ``` #### Parameters * that: [DebugOut](index) val #### Returns * [Bool](builtin-bool) val pony ITest ITest ===== [[Source]](https://stdlib.ponylang.io/src/ponytest/test_helper/#L1) ``` interface ref ITest ``` Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/ponytest/test_helper/#L2) ``` fun box apply() : None val ? ``` #### Returns * [None](builtin-none) val ? pony HashEq64[A: (Hashable64 #read & Equatable[A] #read)] HashEq64[A: ([Hashable64](collections-hashable64) #read & [Equatable](builtin-equatable)[A] #read)] =================================================================================================== [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L70) ``` primitive val HashEq64[A: (Hashable64 #read & Equatable[A] #read)] is HashFunction64[A] val ``` #### Implements * [HashFunction64](collections-hashfunction64)[A] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L70) ``` new val create() : HashEq64[A] val^ ``` #### Returns * [HashEq64](index)[A] val^ Public Functions ---------------- ### hash64 [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L72) Use the hash function from the type parameter. ``` fun box hash64( x: box->A) : U64 val ``` #### Parameters * x: box->A #### Returns * [U64](builtin-u64) val ### eq [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L78) Use the structural equality function from the type parameter. ``` fun box eq( x: box->A, y: box->A) : Bool val ``` #### Parameters * x: box->A * y: box->A #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/collections/hashable/#L72) ``` fun box ne( that: HashEq64[A] val) : Bool val ``` #### Parameters * that: [HashEq64](index)[A] val #### Returns * [Bool](builtin-bool) val pony RingBuffer[A: A] RingBuffer[A: A] ================ [[Source]](https://stdlib.ponylang.io/src/collections/ring_buffer/#L1) A ring buffer. ``` class ref RingBuffer[A: A] ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/ring_buffer/#L9) Create a ring buffer with a fixed size. The size will be rounded up to the next power of 2. ``` new ref create( len: USize val) : RingBuffer[A] ref^ ``` #### Parameters * len: [USize](builtin-usize) val #### Returns * [RingBuffer](index)[A] ref^ Public Functions ---------------- ### head [[Source]](https://stdlib.ponylang.io/src/collections/ring_buffer/#L18) The first read that will succeed. If nothing has been written to the ring, this will raise an error. ``` fun box head() : USize val ? ``` #### Returns * [USize](builtin-usize) val ? ### size [[Source]](https://stdlib.ponylang.io/src/collections/ring_buffer/#L33) The number of elements that have been added to the ring. ``` fun box size() : USize val ``` #### Returns * [USize](builtin-usize) val ### space [[Source]](https://stdlib.ponylang.io/src/collections/ring_buffer/#L39) The available space in the ring. ``` fun box space() : USize val ``` #### Returns * [USize](builtin-usize) val ### apply [[Source]](https://stdlib.ponylang.io/src/collections/ring_buffer/#L45) Get the i-th element from the ring. If the i-th element has not yet been added or is no longer available, this will raise an error. ``` fun box apply( i: USize val) : this->A ? ``` #### Parameters * i: [USize](builtin-usize) val #### Returns * this->A ? ### push [[Source]](https://stdlib.ponylang.io/src/collections/ring_buffer/#L56) Add an element to the ring. If the ring is full, this will drop the oldest element in the ring. Returns true if an element was dropped. ``` fun ref push( value: A) : Bool val ``` #### Parameters * value: A #### Returns * [Bool](builtin-bool) val ### clear [[Source]](https://stdlib.ponylang.io/src/collections/ring_buffer/#L73) Clear the queue. ``` fun ref clear() : None val ``` #### Returns * [None](builtin-none) val pony FileSync FileSync ======== [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L36) ``` primitive val FileSync ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L36) ``` new val create() : FileSync val^ ``` #### Returns * [FileSync](index) val^ Public Functions ---------------- ### value [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L37) ``` fun box value() : U32 val ``` #### Returns * [U32](builtin-u32) val ### eq [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L37) ``` fun box eq( that: FileSync val) : Bool val ``` #### Parameters * that: [FileSync](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L37) ``` fun box ne( that: FileSync val) : Bool val ``` #### Parameters * that: [FileSync](index) val #### Returns * [Bool](builtin-bool) val pony Package Package ======= No package doc string provided for term. Public Types ------------ * [interface ReadlineNotify](term-readlinenotify) * [class Readline](term-readline) * [actor ANSITerm](term-ansiterm) * [interface ANSINotify](term-ansinotify) * [primitive ANSI](term-ansi) pony CapRights CapRights ========= [[Source]](https://stdlib.ponylang.io/src/capsicum/cap_rights/#L3) ``` type CapRights is CapRights0 ref ``` #### Type Alias For * [CapRights0](capsicum-caprights0) ref pony CreateFile CreateFile ========== [[Source]](https://stdlib.ponylang.io/src/files/file/#L49) Open a File for read/write, creating if it doesn't exist, preserving the contents if it does exist. ``` primitive val CreateFile ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file/#L49) ``` new val create() : CreateFile val^ ``` #### Returns * [CreateFile](index) val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/files/file/#L54) ``` fun box apply( from: FilePath val) : (File ref | FileOK val | FileError val | FileEOF val | FileBadFileNumber val | FileExists val | FilePermissionDenied val) ``` #### Parameters * from: [FilePath](files-filepath) val #### Returns * ([File](files-file) ref | [FileOK](files-fileok) val | [FileError](files-fileerror) val | [FileEOF](files-fileeof) val | [FileBadFileNumber](files-filebadfilenumber) val | [FileExists](files-fileexists) val | [FilePermissionDenied](files-filepermissiondenied) val) ### eq [[Source]](https://stdlib.ponylang.io/src/files/file/#L54) ``` fun box eq( that: CreateFile val) : Bool val ``` #### Parameters * that: [CreateFile](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/file/#L54) ``` fun box ne( that: CreateFile val) : Bool val ``` #### Parameters * that: [CreateFile](index) val #### Returns * [Bool](builtin-bool) val pony ReadSeq[A: A] ReadSeq[A: A] ============= [[Source]](https://stdlib.ponylang.io/src/builtin/read_seq/#L1) The readable interface of a sequence. ``` interface box ReadSeq[A: A] ``` Public Functions ---------------- ### size [[Source]](https://stdlib.ponylang.io/src/builtin/read_seq/#L5) Returns the number of elements in the sequence. ``` fun box size() : USize val ``` #### Returns * [USize](builtin-usize) val ### apply [[Source]](https://stdlib.ponylang.io/src/builtin/read_seq/#L10) Returns the i-th element of the sequence. Raises an error if the index is out of bounds. Note that this returns this->A, not A. ``` fun box apply( i: USize val) : this->A ? ``` #### Parameters * i: [USize](builtin-usize) val #### Returns * this->A ? ### values [[Source]](https://stdlib.ponylang.io/src/builtin/read_seq/#L16) Returns an iterator over the elements of the sequence. Note that this iterates over this->A, not A. ``` fun box values() : Iterator[this->A] ref^ ``` #### Returns * [Iterator](builtin-iterator)[this->A] ref^ pony I128 I128 ==== [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L664) ``` primitive val I128 is SignedInteger[I128 val, U128 val] val ``` #### Implements * [SignedInteger](builtin-signedinteger)[[I128](index) val, [U128](builtin-u128) val] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L665) ``` new val create( value: I128 val) : I128 val^ ``` #### Parameters * value: [I128](index) val #### Returns * [I128](index) val^ ### from[A: (([I8](builtin-i8) val | [I16](builtin-i16) val | [I32](builtin-i32) val | [I64](builtin-i64) val | [I128](index) val | [ILong](builtin-ilong) val | [ISize](builtin-isize) val | [U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val | [F32](builtin-f32) val | [F64](builtin-f64) val) & [Real](builtin-real)[A] val)] [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L666) ``` new val from[A: ((I8 val | I16 val | I32 val | I64 val | I128 val | ILong val | ISize val | U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val | F32 val | F64 val) & Real[A] val)]( a: A) : I128 val^ ``` #### Parameters * a: A #### Returns * [I128](index) val^ ### min\_value [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L668) ``` new val min_value() : I128 val^ ``` #### Returns * [I128](index) val^ ### max\_value [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L669) ``` new val max_value() : I128 val^ ``` #### Returns * [I128](index) val^ Public Functions ---------------- ### abs [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L671) ``` fun box abs() : U128 val ``` #### Returns * [U128](builtin-u128) val ### bit\_reverse [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L672) ``` fun box bit_reverse() : I128 val ``` #### Returns * [I128](index) val ### bswap [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L673) ``` fun box bswap() : I128 val ``` #### Returns * [I128](index) val ### popcount [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L674) ``` fun box popcount() : U128 val ``` #### Returns * [U128](builtin-u128) val ### clz [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L675) ``` fun box clz() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ctz [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L676) ``` fun box ctz() : U128 val ``` #### Returns * [U128](builtin-u128) val ### clz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L678) Unsafe operation. If this is 0, the result is undefined. ``` fun box clz_unsafe() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ctz\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L685) Unsafe operation. If this is 0, the result is undefined. ``` fun box ctz_unsafe() : U128 val ``` #### Returns * [U128](builtin-u128) val ### bitwidth [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L692) ``` fun box bitwidth() : U128 val ``` #### Returns * [U128](builtin-u128) val ### bytewidth [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L694) ``` fun box bytewidth() : USize val ``` #### Returns * [USize](builtin-usize) val ### min [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L696) ``` fun box min( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### max [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L697) ``` fun box max( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### fld [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L699) ``` fun box fld( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### fld\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L701) ``` fun box fld_unsafe( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### mod [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L704) ``` fun box mod( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### mod\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L707) ``` fun box mod_unsafe( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### hash [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L710) ``` fun box hash() : USize val ``` #### Returns * [USize](builtin-usize) val ### hash64 [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L711) ``` fun box hash64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### string [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L713) ``` fun box string() : String iso^ ``` #### Returns * [String](builtin-string) iso^ ### mul [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L716) ``` fun box mul( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### divrem [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L719) ``` fun box divrem( y: I128 val) : (I128 val , I128 val) ``` #### Parameters * y: [I128](index) val #### Returns * ([I128](index) val , [I128](index) val) ### div [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L746) ``` fun box div( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### rem [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L754) ``` fun box rem( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### mul\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L762) Unsafe operation. If the operation overflows, the result is undefined. ``` fun box mul_unsafe( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### divrem\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L773) Unsafe operation. If y is 0, the result is undefined. If the operation overflows, the result is undefined. ``` fun box divrem_unsafe( y: I128 val) : (I128 val , I128 val) ``` #### Parameters * y: [I128](index) val #### Returns * ([I128](index) val , [I128](index) val) ### div\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L785) Unsafe operation. If y is 0, the result is undefined. If the operation overflows, the result is undefined. ``` fun box div_unsafe( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### rem\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L797) Unsafe operation. If y is 0, the result is undefined. If the operation overflows, the result is undefined. ``` fun box rem_unsafe( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### f32 [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L809) ``` fun box f32() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64 [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L812) ``` fun box f64() : F64 val ``` #### Returns * [F64](builtin-f64) val ### f32\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L819) Unsafe operation. If the value doesn't fit in the destination type, the result is undefined. ``` fun box f32_unsafe() : F32 val ``` #### Returns * [F32](builtin-f32) val ### f64\_unsafe [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L826) Unsafe operation. If the value doesn't fit in the destination type, the result is undefined. ``` fun box f64_unsafe() : F64 val ``` #### Returns * [F64](builtin-f64) val ### addc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L833) ``` fun box addc( y: I128 val) : (I128 val , Bool val) ``` #### Parameters * y: [I128](index) val #### Returns * ([I128](index) val , [Bool](builtin-bool) val) ### subc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L847) ``` fun box subc( y: I128 val) : (I128 val , Bool val) ``` #### Parameters * y: [I128](index) val #### Returns * ([I128](index) val , [Bool](builtin-bool) val) ### mulc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L861) ``` fun box mulc( y: I128 val) : (I128 val , Bool val) ``` #### Parameters * y: [I128](index) val #### Returns * ([I128](index) val , [Bool](builtin-bool) val) ### divc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L869) ``` fun box divc( y: I128 val) : (I128 val , Bool val) ``` #### Parameters * y: [I128](index) val #### Returns * ([I128](index) val , [Bool](builtin-bool) val) ### remc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L872) ``` fun box remc( y: I128 val) : (I128 val , Bool val) ``` #### Parameters * y: [I128](index) val #### Returns * ([I128](index) val , [Bool](builtin-bool) val) ### fldc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L875) ``` fun box fldc( y: I128 val) : (I128 val , Bool val) ``` #### Parameters * y: [I128](index) val #### Returns * ([I128](index) val , [Bool](builtin-bool) val) ### modc [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L878) ``` fun box modc( y: I128 val) : (I128 val , Bool val) ``` #### Parameters * y: [I128](index) val #### Returns * ([I128](index) val , [Bool](builtin-bool) val) ### add\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L881) ``` fun box add_partial( y: I128 val) : I128 val ? ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ? ### sub\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L884) ``` fun box sub_partial( y: I128 val) : I128 val ? ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ? ### mul\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L887) ``` fun box mul_partial( y: I128 val) : I128 val ? ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ? ### div\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L890) ``` fun box div_partial( y: I128 val) : I128 val ? ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ? ### rem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L893) ``` fun box rem_partial( y: I128 val) : I128 val ? ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ? ### divrem\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L896) ``` fun box divrem_partial( y: I128 val) : (I128 val , I128 val) ? ``` #### Parameters * y: [I128](index) val #### Returns * ([I128](index) val , [I128](index) val) ? ### fld\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L899) ``` fun box fld_partial( y: I128 val) : I128 val ? ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ? ### mod\_partial [[Source]](https://stdlib.ponylang.io/src/builtin/signed/#L902) ``` fun box mod_partial( y: I128 val) : I128 val ? ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ? ### shl ``` fun box shl( y: U128 val) : I128 val ``` #### Parameters * y: [U128](builtin-u128) val #### Returns * [I128](index) val ### shr ``` fun box shr( y: U128 val) : I128 val ``` #### Parameters * y: [U128](builtin-u128) val #### Returns * [I128](index) val ### shl\_unsafe ``` fun box shl_unsafe( y: U128 val) : I128 val ``` #### Parameters * y: [U128](builtin-u128) val #### Returns * [I128](index) val ### shr\_unsafe ``` fun box shr_unsafe( y: U128 val) : I128 val ``` #### Parameters * y: [U128](builtin-u128) val #### Returns * [I128](index) val ### add\_unsafe ``` fun box add_unsafe( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### sub\_unsafe ``` fun box sub_unsafe( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### neg\_unsafe ``` fun box neg_unsafe() : I128 val ``` #### Returns * [I128](index) val ### op\_and ``` fun box op_and( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### op\_or ``` fun box op_or( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### op\_xor ``` fun box op_xor( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### op\_not ``` fun box op_not() : I128 val ``` #### Returns * [I128](index) val ### add ``` fun box add( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### sub ``` fun box sub( y: I128 val) : I128 val ``` #### Parameters * y: [I128](index) val #### Returns * [I128](index) val ### neg ``` fun box neg() : I128 val ``` #### Returns * [I128](index) val ### eq ``` fun box eq( y: I128 val) : Bool val ``` #### Parameters * y: [I128](index) val #### Returns * [Bool](builtin-bool) val ### ne ``` fun box ne( y: I128 val) : Bool val ``` #### Parameters * y: [I128](index) val #### Returns * [Bool](builtin-bool) val ### lt ``` fun box lt( y: I128 val) : Bool val ``` #### Parameters * y: [I128](index) val #### Returns * [Bool](builtin-bool) val ### le ``` fun box le( y: I128 val) : Bool val ``` #### Parameters * y: [I128](index) val #### Returns * [Bool](builtin-bool) val ### ge ``` fun box ge( y: I128 val) : Bool val ``` #### Parameters * y: [I128](index) val #### Returns * [Bool](builtin-bool) val ### gt ``` fun box gt( y: I128 val) : Bool val ``` #### Parameters * y: [I128](index) val #### Returns * [Bool](builtin-bool) val ### i8 ``` fun box i8() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16 ``` fun box i16() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32 ``` fun box i32() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64 ``` fun box i64() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128 ``` fun box i128() : I128 val ``` #### Returns * [I128](index) val ### ilong ``` fun box ilong() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize ``` fun box isize() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8 ``` fun box u8() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16 ``` fun box u16() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32 ``` fun box u32() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64 ``` fun box u64() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128 ``` fun box u128() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong ``` fun box ulong() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize ``` fun box usize() : USize val ``` #### Returns * [USize](builtin-usize) val ### i8\_unsafe ``` fun box i8_unsafe() : I8 val ``` #### Returns * [I8](builtin-i8) val ### i16\_unsafe ``` fun box i16_unsafe() : I16 val ``` #### Returns * [I16](builtin-i16) val ### i32\_unsafe ``` fun box i32_unsafe() : I32 val ``` #### Returns * [I32](builtin-i32) val ### i64\_unsafe ``` fun box i64_unsafe() : I64 val ``` #### Returns * [I64](builtin-i64) val ### i128\_unsafe ``` fun box i128_unsafe() : I128 val ``` #### Returns * [I128](index) val ### ilong\_unsafe ``` fun box ilong_unsafe() : ILong val ``` #### Returns * [ILong](builtin-ilong) val ### isize\_unsafe ``` fun box isize_unsafe() : ISize val ``` #### Returns * [ISize](builtin-isize) val ### u8\_unsafe ``` fun box u8_unsafe() : U8 val ``` #### Returns * [U8](builtin-u8) val ### u16\_unsafe ``` fun box u16_unsafe() : U16 val ``` #### Returns * [U16](builtin-u16) val ### u32\_unsafe ``` fun box u32_unsafe() : U32 val ``` #### Returns * [U32](builtin-u32) val ### u64\_unsafe ``` fun box u64_unsafe() : U64 val ``` #### Returns * [U64](builtin-u64) val ### u128\_unsafe ``` fun box u128_unsafe() : U128 val ``` #### Returns * [U128](builtin-u128) val ### ulong\_unsafe ``` fun box ulong_unsafe() : ULong val ``` #### Returns * [ULong](builtin-ulong) val ### usize\_unsafe ``` fun box usize_unsafe() : USize val ``` #### Returns * [USize](builtin-usize) val ### compare ``` fun box compare( that: I128 val) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [I128](index) val #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val)
programming_docs
pony JsonArray JsonArray ========= [[Source]](https://stdlib.ponylang.io/src/json/json_type/#L8) ``` class ref JsonArray ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/json/json_type/#L14) Create an array with zero elements, but space for len elements. ``` new ref create( len: USize val = 0) : JsonArray ref^ ``` #### Parameters * len: [USize](builtin-usize) val = 0 #### Returns * [JsonArray](index) ref^ ### from\_array [[Source]](https://stdlib.ponylang.io/src/json/json_type/#L20) Create a Json array from an actual array. ``` new ref from_array( data': Array[(F64 val | I64 val | Bool val | None val | String val | JsonArray ref | JsonObject ref)] ref) : JsonArray ref^ ``` #### Parameters * data': [Array](builtin-array)[([F64](builtin-f64) val | [I64](builtin-i64) val | [Bool](builtin-bool) val | [None](builtin-none) val | [String](builtin-string) val | [JsonArray](index) ref | [JsonObject](json-jsonobject) ref)] ref #### Returns * [JsonArray](index) ref^ Public fields ------------- ### var data: [Array](builtin-array)[([F64](builtin-f64) val | [I64](builtin-i64) val | [Bool](builtin-bool) val | [None](builtin-none) val | [String](builtin-string) val | [JsonArray](index) ref | [JsonObject](json-jsonobject) ref)] ref [[Source]](https://stdlib.ponylang.io/src/json/json_type/#L9) The actual array containing JSON structures. Public Functions ---------------- ### string [[Source]](https://stdlib.ponylang.io/src/json/json_type/#L26) Generate string representation of this array. ``` fun box string( indent: String val = "", pretty_print: Bool val = false) : String val ``` #### Parameters * indent: [String](builtin-string) val = "" * pretty\_print: [Bool](builtin-bool) val = false #### Returns * [String](builtin-string) val pony StartProcessAuth StartProcessAuth ================ [[Source]](https://stdlib.ponylang.io/src/process/auth/#L1) ``` primitive val StartProcessAuth ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/process/auth/#L2) ``` new val create( from: AmbientAuth val) : StartProcessAuth val^ ``` #### Parameters * from: [AmbientAuth](builtin-ambientauth) val #### Returns * [StartProcessAuth](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/process/auth/#L2) ``` fun box eq( that: StartProcessAuth val) : Bool val ``` #### Parameters * that: [StartProcessAuth](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/process/auth/#L2) ``` fun box ne( that: StartProcessAuth val) : Bool val ``` #### Parameters * that: [StartProcessAuth](index) val #### Returns * [Bool](builtin-bool) val pony NullablePointer[A: A] NullablePointer[A: A] ===================== [[Source]](https://stdlib.ponylang.io/src/builtin/nullable_pointer/#L1) A NullablePointer[A] is used to encode a possibly-null type. It should *only* be used for structs that need to be passed to and from the C FFI. An optional type for anything that isn't a struct should be encoded as a union type, for example (A | None). ``` struct ref NullablePointer[A: A] ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/builtin/nullable_pointer/#L9) This re-encodes the type of `that` from A to NullablePointer[A], allowing `that` to be assigned to a field or variable of type NullablePointer[A]. It doesn't allocate a wrapper object: there is no containing object for `that`. ``` new ref create( that: A) : NullablePointer[A] ref^ ``` #### Parameters * that: A #### Returns * [NullablePointer](index)[A] ref^ ### none [[Source]](https://stdlib.ponylang.io/src/builtin/nullable_pointer/#L17) This returns a null pointer typed as a NullablePointer[A]. ``` new ref none() : NullablePointer[A] ref^ ``` #### Returns * [NullablePointer](index)[A] ref^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/builtin/nullable_pointer/#L23) This re-encodes the type of `this` from NullablePointer[A] to A, allowing `this` to be assigned to a field of variable of type A. If `this` is a null pointer, an error is raised. ``` fun box apply() : this->A ? ``` #### Returns * this->A ? ### is\_none [[Source]](https://stdlib.ponylang.io/src/builtin/nullable_pointer/#L31) Returns true if `this` is null (ie apply would raise an error). ``` fun box is_none() : Bool val ``` #### Returns * [Bool](builtin-bool) val pony MapValues[K: Any #share, V: Any #share, H: HashFunction[K] val] MapValues[K: [Any](builtin-any) #share, V: [Any](builtin-any) #share, H: [HashFunction](collections-hashfunction)[K] val] ========================================================================================================================= [[Source]](https://stdlib.ponylang.io/src/collections-persistent/map/#L145) ``` class ref MapValues[K: Any #share, V: Any #share, H: HashFunction[K] val] ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections-persistent/map/#L148) ``` new ref create( m: HashMap[K, V, H] val) : MapValues[K, V, H] ref^ ``` #### Parameters * m: [HashMap](collections-persistent-hashmap)[K, V, H] val #### Returns * [MapValues](index)[K, V, H] ref^ Public Functions ---------------- ### has\_next [[Source]](https://stdlib.ponylang.io/src/collections-persistent/map/#L150) ``` fun box has_next() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### next [[Source]](https://stdlib.ponylang.io/src/collections-persistent/map/#L152) ``` fun ref next() : val->V ? ``` #### Returns * val->V ? pony IniError IniError ======== [[Source]](https://stdlib.ponylang.io/src/ini/ini/#L34) ``` type IniError is (IniIncompleteSection val | IniNoDelimiter val) ``` #### Type Alias For * ([IniIncompleteSection](ini-iniincompletesection) val | [IniNoDelimiter](ini-ininodelimiter) val) pony Flag[A: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Integer[A] val)] Flag[A: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Integer](builtin-integer)[A] val)] ===================================================================================================================================================================================================================================== [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L1) A flag should be a primitive with a value method that returns the bits that represent the flag. This allows a flag to encode a single bit, or any combination of bits. ``` interface val Flag[A: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Integer[A] val)] ``` Public Functions ---------------- ### value [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L7) ``` fun box value() : A ``` #### Returns * A pony MinHeapPriority[A: Comparable[A] #read] MinHeapPriority[A: [Comparable](builtin-comparable)[A] #read] ============================================================= [[Source]](https://stdlib.ponylang.io/src/collections/heap/#L139) ``` primitive val MinHeapPriority[A: Comparable[A] #read] is _BinaryHeapPriority[A] val ``` #### Implements * \_BinaryHeapPriority[A] val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/heap/#L139) ``` new val create() : MinHeapPriority[A] val^ ``` #### Returns * [MinHeapPriority](index)[A] val^ Public Functions ---------------- ### apply [[Source]](https://stdlib.ponylang.io/src/collections/heap/#L140) ``` fun box apply( x: A, y: A) : Bool val ``` #### Parameters * x: A * y: A #### Returns * [Bool](builtin-bool) val ### eq [[Source]](https://stdlib.ponylang.io/src/collections/heap/#L140) ``` fun box eq( that: MinHeapPriority[A] val) : Bool val ``` #### Parameters * that: [MinHeapPriority](index)[A] val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/collections/heap/#L140) ``` fun box ne( that: MinHeapPriority[A] val) : Bool val ``` #### Parameters * that: [MinHeapPriority](index)[A] val #### Returns * [Bool](builtin-bool) val pony File File ==== [[Source]](https://stdlib.ponylang.io/src/files/file/#L78) Operations on a file. ``` class ref File ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file/#L101) Attempt to open for read/write, creating if it doesn't exist, preserving the contents if it does exist. Set errno according to result. ``` new ref create( from: FilePath val) : File ref^ ``` #### Parameters * from: [FilePath](files-filepath) val #### Returns * [File](index) ref^ ### open [[Source]](https://stdlib.ponylang.io/src/files/file/#L141) Open for read only. Set \_errno according to result. ``` new ref open( from: FilePath val) : File ref^ ``` #### Parameters * from: [FilePath](files-filepath) val #### Returns * [File](index) ref^ Public fields ------------- ### let path: [FilePath](files-filepath) val [[Source]](https://stdlib.ponylang.io/src/files/file/#L82) This is the filesystem path locating this file on the file system and an object capability granting access to operate on this file. ### let writeable: [Bool](builtin-bool) val [[Source]](https://stdlib.ponylang.io/src/files/file/#L88) `true` if the underlying file descriptor has been opened as writeable. Public Functions ---------------- ### errno [[Source]](https://stdlib.ponylang.io/src/files/file/#L192) Returns the last error code set for this File ``` fun box errno() : (FileOK val | FileError val | FileEOF val | FileBadFileNumber val | FileExists val | FilePermissionDenied val) ``` #### Returns * ([FileOK](files-fileok) val | [FileError](files-fileerror) val | [FileEOF](files-fileeof) val | [FileBadFileNumber](files-filebadfilenumber) val | [FileExists](files-fileexists) val | [FilePermissionDenied](files-filepermissiondenied) val) ### clear\_errno [[Source]](https://stdlib.ponylang.io/src/files/file/#L198) Clears the last error code set for this File. Clears the error indicator for the stream. ``` fun ref clear_errno() : None val ``` #### Returns * [None](builtin-none) val ### valid [[Source]](https://stdlib.ponylang.io/src/files/file/#L219) Returns true if the file is currently open. ``` fun box valid() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### read [[Source]](https://stdlib.ponylang.io/src/files/file/#L226) Returns up to len bytes. ``` fun ref read( len: USize val) : Array[U8 val] iso^ ``` #### Parameters * len: [USize](builtin-usize) val #### Returns * [Array](builtin-array)[[U8](builtin-u8) val] iso^ ### read\_string [[Source]](https://stdlib.ponylang.io/src/files/file/#L252) Returns up to len bytes. The resulting string may have internal null characters. ``` fun ref read_string( len: USize val) : String iso^ ``` #### Parameters * len: [USize](builtin-usize) val #### Returns * [String](builtin-string) iso^ ### print [[Source]](https://stdlib.ponylang.io/src/files/file/#L277) Same as write, buts adds a newline. ``` fun ref print( data: (String box | Array[U8 val] box)) : Bool val ``` #### Parameters * data: ([String](builtin-string) box | [Array](builtin-array)[[U8](builtin-u8) val] box) #### Returns * [Bool](builtin-bool) val ### printv [[Source]](https://stdlib.ponylang.io/src/files/file/#L286) Print an iterable collection of ByteSeqs. ``` fun ref printv( data: ByteSeqIter box) : Bool val ``` #### Parameters * data: [ByteSeqIter](builtin-byteseqiter) box #### Returns * [Bool](builtin-bool) val ### write [[Source]](https://stdlib.ponylang.io/src/files/file/#L297) Returns false if the file wasn't opened with write permission. Returns false and closes the file if not all the bytes were written. ``` fun ref write( data: (String box | Array[U8 val] box)) : Bool val ``` #### Parameters * data: ([String](builtin-string) box | [Array](builtin-array)[[U8](builtin-u8) val] box) #### Returns * [Bool](builtin-bool) val ### writev [[Source]](https://stdlib.ponylang.io/src/files/file/#L306) Write an iterable collection of ByteSeqs. ``` fun ref writev( data: ByteSeqIter box) : Bool val ``` #### Parameters * data: [ByteSeqIter](builtin-byteseqiter) box #### Returns * [Bool](builtin-bool) val ### queue [[Source]](https://stdlib.ponylang.io/src/files/file/#L316) Queue data to be written NOTE: Queue'd data will always be written before normal print/write requested data ``` fun ref queue( data: (String box | Array[U8 val] box)) : None val ``` #### Parameters * data: ([String](builtin-string) box | [Array](builtin-array)[[U8](builtin-u8) val] box) #### Returns * [None](builtin-none) val ### queuev [[Source]](https://stdlib.ponylang.io/src/files/file/#L325) Queue an iterable collection of ByteSeqs to be written NOTE: Queue'd data will always be written before normal print/write requested data ``` fun ref queuev( data: ByteSeqIter box) : None val ``` #### Parameters * data: [ByteSeqIter](builtin-byteseqiter) box #### Returns * [None](builtin-none) val ### flush [[Source]](https://stdlib.ponylang.io/src/files/file/#L335) Flush any queued data ``` fun ref flush() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### position [[Source]](https://stdlib.ponylang.io/src/files/file/#L432) Return the current cursor position in the file. ``` fun ref position() : USize val ``` #### Returns * [USize](builtin-usize) val ### size [[Source]](https://stdlib.ponylang.io/src/files/file/#L457) Return the total length of the file. ``` fun ref size() : USize val ``` #### Returns * [USize](builtin-usize) val ### seek\_start [[Source]](https://stdlib.ponylang.io/src/files/file/#L467) Set the cursor position relative to the start of the file. ``` fun ref seek_start( offset: USize val) : None val ``` #### Parameters * offset: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### seek\_end [[Source]](https://stdlib.ponylang.io/src/files/file/#L475) Set the cursor position relative to the end of the file. ``` fun ref seek_end( offset: USize val) : None val ``` #### Parameters * offset: [USize](builtin-usize) val #### Returns * [None](builtin-none) val ### seek [[Source]](https://stdlib.ponylang.io/src/files/file/#L483) Move the cursor position. ``` fun ref seek( offset: ISize val) : None val ``` #### Parameters * offset: [ISize](builtin-isize) val #### Returns * [None](builtin-none) val ### sync [[Source]](https://stdlib.ponylang.io/src/files/file/#L491) Sync the file contents to physical storage. ``` fun ref sync() : None val ``` #### Returns * [None](builtin-none) val ### datasync [[Source]](https://stdlib.ponylang.io/src/files/file/#L511) Sync the file contents to physical storage. ``` fun ref datasync() : None val ``` #### Returns * [None](builtin-none) val ### set\_length [[Source]](https://stdlib.ponylang.io/src/files/file/#L530) Change the file size. If it is made larger, the new contents are undefined. ``` fun ref set_length( len: USize val) : Bool val ``` #### Parameters * len: [USize](builtin-usize) val #### Returns * [Bool](builtin-bool) val ### info [[Source]](https://stdlib.ponylang.io/src/files/file/#L560) Return a FileInfo for this directory. Raise an error if the fd is invalid or if we don't have FileStat permission. ``` fun box info() : FileInfo val ? ``` #### Returns * [FileInfo](files-fileinfo) val ? ### chmod [[Source]](https://stdlib.ponylang.io/src/files/file/#L567) Set the FileMode for this directory. ``` fun box chmod( mode: FileMode box) : Bool val ``` #### Parameters * mode: [FileMode](files-filemode) box #### Returns * [Bool](builtin-bool) val ### chown [[Source]](https://stdlib.ponylang.io/src/files/file/#L573) Set the owner and group for this directory. Does nothing on Windows. ``` fun box chown( uid: U32 val, gid: U32 val) : Bool val ``` #### Parameters * uid: [U32](builtin-u32) val * gid: [U32](builtin-u32) val #### Returns * [Bool](builtin-bool) val ### touch [[Source]](https://stdlib.ponylang.io/src/files/file/#L579) Set the last access and modification times of the directory to now. ``` fun box touch() : Bool val ``` #### Returns * [Bool](builtin-bool) val ### set\_time [[Source]](https://stdlib.ponylang.io/src/files/file/#L585) Set the last access and modification times of the directory to the given values. ``` fun box set_time( atime: (I64 val , I64 val), mtime: (I64 val , I64 val)) : Bool val ``` #### Parameters * atime: ([I64](builtin-i64) val , [I64](builtin-i64) val) * mtime: ([I64](builtin-i64) val , [I64](builtin-i64) val) #### Returns * [Bool](builtin-bool) val ### lines [[Source]](https://stdlib.ponylang.io/src/files/file/#L592) Returns an iterator for reading lines from the file. ``` fun ref lines() : FileLines ref ``` #### Returns * [FileLines](files-filelines) ref ### dispose [[Source]](https://stdlib.ponylang.io/src/files/file/#L598) Close the file. Future operations will do nothing. ``` fun ref dispose() : None val ``` #### Returns * [None](builtin-none) val pony FormatOctalBare FormatOctalBare =============== [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L9) ``` primitive val FormatOctalBare is FormatSpec val ``` #### Implements * [FormatSpec](format-formatspec) val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L9) ``` new val create() : FormatOctalBare val^ ``` #### Returns * [FormatOctalBare](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L10) ``` fun box eq( that: FormatOctalBare val) : Bool val ``` #### Parameters * that: [FormatOctalBare](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L10) ``` fun box ne( that: FormatOctalBare val) : Bool val ``` #### Parameters * that: [FormatOctalBare](index) val #### Returns * [Bool](builtin-bool) val pony TCPListenAuth TCPListenAuth ============= [[Source]](https://stdlib.ponylang.io/src/net/auth/#L17) ``` primitive val TCPListenAuth ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/net/auth/#L18) ``` new val create( from: (AmbientAuth val | NetAuth val | TCPAuth val)) : TCPListenAuth val^ ``` #### Parameters * from: ([AmbientAuth](builtin-ambientauth) val | [NetAuth](net-netauth) val | [TCPAuth](net-tcpauth) val) #### Returns * [TCPListenAuth](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/net/auth/#L18) ``` fun box eq( that: TCPListenAuth val) : Bool val ``` #### Parameters * that: [TCPListenAuth](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/net/auth/#L18) ``` fun box ne( that: TCPListenAuth val) : Bool val ``` #### Parameters * that: [TCPListenAuth](index) val #### Returns * [Bool](builtin-bool) val pony FileMkdir FileMkdir ========= [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L18) ``` primitive val FileMkdir ``` Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L18) ``` new val create() : FileMkdir val^ ``` #### Returns * [FileMkdir](index) val^ Public Functions ---------------- ### value [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L19) ``` fun box value() : U32 val ``` #### Returns * [U32](builtin-u32) val ### eq [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L19) ``` fun box eq( that: FileMkdir val) : Bool val ``` #### Parameters * that: [FileMkdir](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/files/file_caps/#L19) ``` fun box ne( that: FileMkdir val) : Bool val ``` #### Parameters * that: [FileMkdir](index) val #### Returns * [Bool](builtin-bool) val
programming_docs
pony Flags[A: Flag[B] val, optional B: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Integer[B] val)] Flags[A: [Flag](collections-flag)[B] val, optional B: (([U8](builtin-u8) val | [U16](builtin-u16) val | [U32](builtin-u32) val | [U64](builtin-u64) val | [U128](builtin-u128) val | [ULong](builtin-ulong) val | [USize](builtin-usize) val) & [Integer](builtin-integer)[B] val)] =================================================================================================================================================================================================================================================================================== [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L9) Flags is a set of flags. The flags that are recognised should be passed as a union type for type parameter A. For example: primitive SSE fun value(): U64 => 1 primitive AVX fun value(): U64 => 2 primitive RDTSCP fun value(): U64 => 4 type Features is Flags[(SSE | AVX | RDTSCP)] Type parameter B is the unlying field used to store the flags. ``` class ref Flags[A: Flag[B] val, optional B: ((U8 val | U16 val | U32 val | U64 val | U128 val | ULong val | USize val) & Integer[B] val)] is Comparable[Flags[A, B] box] ref ``` #### Implements * [Comparable](builtin-comparable)[[Flags](index)[A, B] box] ref Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L9) ``` new iso create() : Flags[A, B] iso^ ``` #### Returns * [Flags](index)[A, B] iso^ Public Functions ---------------- ### value [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L30) Returns the bit encoding of the set flags. ``` fun box value() : B ``` #### Returns * B ### apply [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L36) Returns true if the flag is set. ``` fun box apply( flag: A) : Bool val ``` #### Parameters * flag: A #### Returns * [Bool](builtin-bool) val ### all [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L42) Sets all bits, including undefined flags. ``` fun ref all() : None val ``` #### Returns * [None](builtin-none) val ### clear [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L48) Unsets all flags. ``` fun ref clear() : None val ``` #### Returns * [None](builtin-none) val ### set [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L54) Sets the flag. ``` fun ref set( flag: A) : None val ``` #### Parameters * flag: A #### Returns * [None](builtin-none) val ### unset [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L60) Unsets the flag. ``` fun ref unset( flag: A) : None val ``` #### Parameters * flag: A #### Returns * [None](builtin-none) val ### flip [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L66) Sets the flag if it is unset, unsets the flag if it is set. ``` fun ref flip( flag: A) : None val ``` #### Parameters * flag: A #### Returns * [None](builtin-none) val ### union [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L72) The union of this and that. ``` fun ref union( that: Flags[A, B] box) : None val ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [None](builtin-none) val ### intersect [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L78) The intersection of this and that. ``` fun ref intersect( that: Flags[A, B] box) : None val ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [None](builtin-none) val ### difference [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L84) The symmetric difference of this and that. ``` fun ref difference( that: Flags[A, B] box) : None val ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [None](builtin-none) val ### remove [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L90) Unset flags that are set in that. ``` fun ref remove( that: Flags[A, B] box) : None val ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [None](builtin-none) val ### add [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L96) This with the flag set. ``` fun box add( flag: A) : Flags[A, B] iso^ ``` #### Parameters * flag: A #### Returns * [Flags](index)[A, B] iso^ ### sub [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L104) This with the flag unset. ``` fun box sub( flag: A) : Flags[A, B] iso^ ``` #### Parameters * flag: A #### Returns * [Flags](index)[A, B] iso^ ### op\_or [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L112) The union of this and that. ``` fun box op_or( that: Flags[A, B] box) : Flags[A, B] iso^ ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [Flags](index)[A, B] iso^ ### op\_and [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L120) The intersection of this and that. ``` fun box op_and( that: Flags[A, B] box) : Flags[A, B] iso^ ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [Flags](index)[A, B] iso^ ### op\_xor [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L128) The symmetric difference of this and that. ``` fun box op_xor( that: Flags[A, B] box) : Flags[A, B] iso^ ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [Flags](index)[A, B] iso^ ### without [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L136) The flags in this that are not in that. ``` fun box without( that: Flags[A, B] box) : Flags[A, B] iso^ ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [Flags](index)[A, B] iso^ ### clone [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L144) Create a clone. ``` fun box clone() : Flags[A, B] iso^ ``` #### Returns * [Flags](index)[A, B] iso^ ### eq [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L152) Returns true if this has the same flags set as that. ``` fun box eq( that: Flags[A, B] box) : Bool val ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [Bool](builtin-bool) val ### lt [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L158) Returns true if the flags set on this are a strict subset of the flags set on that. Flags is only partially ordered, so lt is not the opposite of ge. ``` fun box lt( that: Flags[A, B] box) : Bool val ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [Bool](builtin-bool) val ### le [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L165) Returns true if the flags set on this are a subset of the flags set on that or they are the same. Flags is only partially ordered, so le is not the opposite of te. ``` fun box le( that: Flags[A, B] box) : Bool val ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [Bool](builtin-bool) val ### gt [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L173) Returns true if the flags set on this are a struct superset of the flags set on that. Flags is only partially ordered, so gt is not the opposite of le. ``` fun box gt( that: Flags[A, B] box) : Bool val ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [Bool](builtin-bool) val ### ge [[Source]](https://stdlib.ponylang.io/src/collections/flag/#L181) Returns true if the flags set on this are a superset of the flags set on that or they are the same. Flags is only partially ordered, so ge is not the opposite of lt. ``` fun box ge( that: Flags[A, B] box) : Bool val ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [Bool](builtin-bool) val ### compare [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L28) ``` fun box compare( that: Flags[A, B] box) : (Less val | Equal val | Greater val) ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * ([Less](builtin-less) val | [Equal](builtin-equal) val | [Greater](builtin-greater) val) ### ne [[Source]](https://stdlib.ponylang.io/src/builtin/compare/#L20) ``` fun box ne( that: Flags[A, B] box) : Bool val ``` #### Parameters * that: [Flags](index)[A, B] box #### Returns * [Bool](builtin-bool) val pony FormatFloat FormatFloat =========== [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L34) ``` type FormatFloat is (FormatDefault val | FormatExp val | FormatExpLarge val | FormatFix val | FormatFixLarge val | FormatGeneral val | FormatGeneralLarge val) ``` #### Type Alias For * ([FormatDefault](format-formatdefault) val | [FormatExp](format-formatexp) val | [FormatExpLarge](format-formatexplarge) val | [FormatFix](format-formatfix) val | [FormatFixLarge](format-formatfixlarge) val | [FormatGeneral](format-formatgeneral) val | [FormatGeneralLarge](format-formatgenerallarge) val) pony FormatBinaryBare FormatBinaryBare ================ [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L7) ``` primitive val FormatBinaryBare is FormatSpec val ``` #### Implements * [FormatSpec](format-formatspec) val Constructors ------------ ### create [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L7) ``` new val create() : FormatBinaryBare val^ ``` #### Returns * [FormatBinaryBare](index) val^ Public Functions ---------------- ### eq [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L8) ``` fun box eq( that: FormatBinaryBare val) : Bool val ``` #### Parameters * that: [FormatBinaryBare](index) val #### Returns * [Bool](builtin-bool) val ### ne [[Source]](https://stdlib.ponylang.io/src/format/format_spec/#L8) ``` fun box ne( that: FormatBinaryBare val) : Bool val ``` #### Parameters * that: [FormatBinaryBare](index) val #### Returns * [Bool](builtin-bool) val leaflet Leaflet API reference Leaflet API reference ===================== Map --- The central class of the API — it is used to create a map on a page and manipulate it. ### Usage example ``` // initialize the map on the "map" div with a given center and zoom var map = L.map('map', { center: [51.505, -0.09], zoom: 13 }); ``` ### Creation | Factory | Description | | --- | --- | | `L.map(<String> *id*, <Map options> *options?*)` | Instantiates a map object given the DOM ID of a `<div>` element and optionally an object literal with `Map options`. | | `L.map(<HTMLElement> *el*, <Map options> *options?*)` | Instantiates a map object given an instance of a `<div>` HTML element and optionally an object literal with `Map options`. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `preferCanvas` | `Boolean` | `false` | Whether [`Path`](#path)s should be rendered on a [`Canvas`](#canvas) renderer. By default, all [`Path`](#path)s are rendered in a [`SVG`](#svg) renderer. | #### Control options | Option | Type | Default | Description | | --- | --- | --- | --- | | `attributionControl` | `Boolean` | `true` | Whether a [attribution control](#control-attribution) is added to the map by default. | | `zoomControl` | `Boolean` | `true` | Whether a [zoom control](#control-zoom) is added to the map by default. | #### Interaction Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `closePopupOnClick` | `Boolean` | `true` | Set it to `false` if you don't want popups to close when user clicks the map. | | `zoomSnap` | `Number` | `1` | Forces the map's zoom level to always be a multiple of this, particularly right after a [`fitBounds()`](#map-fitbounds) or a pinch-zoom. By default, the zoom level snaps to the nearest integer; lower values (e.g. `0.5` or `0.1`) allow for greater granularity. A value of `0` means the zoom level will not be snapped after `fitBounds` or a pinch-zoom. | | `zoomDelta` | `Number` | `1` | Controls how much the map's zoom level will change after a [`zoomIn()`](#map-zoomin), [`zoomOut()`](#map-zoomout), pressing `+` or `-` on the keyboard, or using the [zoom controls](#control-zoom). Values smaller than `1` (e.g. `0.5`) allow for greater granularity. | | `trackResize` | `Boolean` | `true` | Whether the map automatically handles browser window resize to update itself. | | `boxZoom` | `Boolean` | `true` | Whether the map can be zoomed to a rectangular area specified by dragging the mouse while pressing the shift key. | | `doubleClickZoom` | `Boolean|String` | `true` | Whether the map can be zoomed in by double clicking on it and zoomed out by double clicking while holding shift. If passed `'center'`, double-click zoom will zoom to the center of the view regardless of where the mouse was. | | `dragging` | `Boolean` | `true` | Whether the map is draggable with mouse/touch or not. | #### Map State Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `crs` | `[CRS](#crs)` | `L.CRS.EPSG3857` | The [Coordinate Reference System](#crs) to use. Don't change this if you're not sure what it means. | | `center` | `[LatLng](#latlng)` | `undefined` | Initial geographic center of the map | | `zoom` | `Number` | `undefined` | Initial map zoom level | | `minZoom` | `Number` | `*` | Minimum zoom level of the map. If not specified and at least one [`GridLayer`](#gridlayer) or [`TileLayer`](#tilelayer) is in the map, the lowest of their `minZoom` options will be used instead. | | `maxZoom` | `Number` | `*` | Maximum zoom level of the map. If not specified and at least one [`GridLayer`](#gridlayer) or [`TileLayer`](#tilelayer) is in the map, the highest of their `maxZoom` options will be used instead. | | `layers` | `Layer[]` | `[]` | Array of layers that will be added to the map initially | | `maxBounds` | `[LatLngBounds](#latlngbounds)` | `null` | When this option is set, the map restricts the view to the given geographical bounds, bouncing the user back if the user tries to pan outside the view. To set the restriction dynamically, use [`setMaxBounds`](#map-setmaxbounds) method. | | `renderer` | `[Renderer](#renderer)` | `*` | The default method for drawing vector layers on the map. [`L.SVG`](#svg) or [`L.Canvas`](#canvas) by default depending on browser support. | #### Animation Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `zoomAnimation` | `Boolean` | `true` | Whether the map zoom animation is enabled. By default it's enabled in all browsers that support CSS3 Transitions except Android. | | `zoomAnimationThreshold` | `Number` | `4` | Won't animate zoom if the zoom difference exceeds this value. | | `fadeAnimation` | `Boolean` | `true` | Whether the tile fade animation is enabled. By default it's enabled in all browsers that support CSS3 Transitions except Android. | | `markerZoomAnimation` | `Boolean` | `true` | Whether markers animate their zoom with the zoom animation, if disabled they will disappear for the length of the animation. By default it's enabled in all browsers that support CSS3 Transitions except Android. | | `transform3DLimit` | `Number` | `2^23` | Defines the maximum size of a CSS translation transform. The default value should not be changed unless a web browser positions layers in the wrong place after doing a large `panBy`. | #### Panning Inertia Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `inertia` | `Boolean` | `*` | If enabled, panning of the map will have an inertia effect where the map builds momentum while dragging and continues moving in the same direction for some time. Feels especially nice on touch devices. Enabled by default. | | `inertiaDeceleration` | `Number` | `3000` | The rate with which the inertial movement slows down, in pixels/second². | | `inertiaMaxSpeed` | `Number` | `Infinity` | Max speed of the inertial movement, in pixels/second. | | `easeLinearity` | `Number` | `0.2` | | | `worldCopyJump` | `Boolean` | `false` | With this option enabled, the map tracks when you pan to another "copy" of the world and seamlessly jumps to the original one so that all overlays like markers and vector layers are still visible. | | `maxBoundsViscosity` | `Number` | `0.0` | If `maxBounds` is set, this option will control how solid the bounds are when dragging the map around. The default value of `0.0` allows the user to drag outside the bounds at normal speed, higher values will slow down map dragging outside bounds, and `1.0` makes the bounds fully solid, preventing the user from dragging outside the bounds. | #### Keyboard Navigation Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `keyboard` | `Boolean` | `true` | Makes the map focusable and allows users to navigate the map with keyboard arrows and `+`/`-` keys. | | `keyboardPanDelta` | `Number` | `80` | Amount of pixels to pan when pressing an arrow key. | #### Mouse wheel options | Option | Type | Default | Description | | --- | --- | --- | --- | | `scrollWheelZoom` | `Boolean|String` | `true` | Whether the map can be zoomed by using the mouse wheel. If passed `'center'`, it will zoom to the center of the view regardless of where the mouse was. | | `wheelDebounceTime` | `Number` | `40` | Limits the rate at which a wheel can fire (in milliseconds). By default user can't zoom via wheel more often than once per 40 ms. | | `wheelPxPerZoomLevel` | `Number` | `60` | How many scroll pixels (as reported by [L.DomEvent.getWheelDelta](#domevent-getwheeldelta)) mean a change of one full zoom level. Smaller values will make wheel-zooming faster (and vice versa). | #### Touch interaction options | Option | Type | Default | Description | | --- | --- | --- | --- | | `tapHold` | `Boolean` | | Enables simulation of `contextmenu` event, default is `true` for mobile Safari. | | `tapTolerance` | `Number` | `15` | The max number of pixels a user can shift his finger during touch for it to be considered a valid tap. | | `touchZoom` | `Boolean|String` | `*` | Whether the map can be zoomed by touch-dragging with two fingers. If passed `'center'`, it will zoom to the center of the view regardless of where the touch events (fingers) were. Enabled for touch-capable web browsers. | | `bounceAtZoomLimits` | `Boolean` | `true` | Set it to false if you don't want the map to zoom beyond min/max zoom and then bounce back when pinch-zooming. | ### Events #### Layer events | Event | Data | Description | | --- | --- | --- | | `baselayerchange` | `[LayersControlEvent](#layerscontrolevent)` | Fired when the base layer is changed through the [layers control](#control-layers). | | `overlayadd` | `[LayersControlEvent](#layerscontrolevent)` | Fired when an overlay is selected through the [layers control](#control-layers). | | `overlayremove` | `[LayersControlEvent](#layerscontrolevent)` | Fired when an overlay is deselected through the [layers control](#control-layers). | | `layeradd` | `[LayerEvent](#layerevent)` | Fired when a new layer is added to the map. | | `layerremove` | `[LayerEvent](#layerevent)` | Fired when some layer is removed from the map | #### Map state change events | Event | Data | Description | | --- | --- | --- | | `zoomlevelschange` | `[Event](#event)` | Fired when the number of zoomlevels on the map is changed due to adding or removing a layer. | | `resize` | `[ResizeEvent](#resizeevent)` | Fired when the map is resized. | | `unload` | `[Event](#event)` | Fired when the map is destroyed with [remove](#map-remove) method. | | `viewreset` | `[Event](#event)` | Fired when the map needs to redraw its content (this usually happens on map zoom or load). Very useful for creating custom overlays. | | `load` | `[Event](#event)` | Fired when the map is initialized (when its center and zoom are set for the first time). | | `zoomstart` | `[Event](#event)` | Fired when the map zoom is about to change (e.g. before zoom animation). | | `movestart` | `[Event](#event)` | Fired when the view of the map starts changing (e.g. user starts dragging the map). | | `zoom` | `[Event](#event)` | Fired repeatedly during any change in zoom level, including zoom and fly animations. | | `move` | `[Event](#event)` | Fired repeatedly during any movement of the map, including pan and fly animations. | | `zoomend` | `[Event](#event)` | Fired when the map zoom changed, after any animations. | | `moveend` | `[Event](#event)` | Fired when the center of the map stops changing (e.g. user stopped dragging the map or after non-centered zoom). | #### Popup events | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup is opened in the map | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup in the map is closed | | `autopanstart` | `[Event](#event)` | Fired when the map starts autopanning when opening a popup. | #### Tooltip events | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip is opened in the map. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip in the map is closed. | #### Location events | Event | Data | Description | | --- | --- | --- | | `locationerror` | `[ErrorEvent](#errorevent)` | Fired when geolocation (using the [`locate`](#map-locate) method) failed. | | `locationfound` | `[LocationEvent](#locationevent)` | Fired when geolocation (using the [`locate`](#map-locate) method) went successfully. | #### Interaction events | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the map. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the map. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the map. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button on the map. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the map. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the map. | | `mousemove` | `[MouseEvent](#mouseevent)` | Fired while the mouse moves over the map. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the right mouse button on the map, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | | `keypress` | `[KeyboardEvent](#keyboardevent)` | Fired when the user presses a key from the keyboard that produces a character value while the map is focused. | | `keydown` | `[KeyboardEvent](#keyboardevent)` | Fired when the user presses a key from the keyboard while the map is focused. Unlike the `keypress` event, the `keydown` event is fired for keys that produce a character value and for keys that do not produce a character value. | | `keyup` | `[KeyboardEvent](#keyboardevent)` | Fired when the user releases a key from the keyboard while the map is focused. | | `preclick` | `[MouseEvent](#mouseevent)` | Fired before mouse click on the map (sometimes useful when you want something to happen on click before any existing click handlers start running). | #### Other Events | Event | Data | Description | | --- | --- | --- | | `zoomanim` | `[ZoomAnimEvent](#zoomanimevent)` | Fired at least once per zoom animation. For continuous zoom, like pinch zooming, fired once per frame during zoom. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `getRenderer(<[Path](#path)> *layer*)` | `[Renderer](#renderer)` | Returns the instance of [`Renderer`](#renderer) that should be used to render the given [`Path`](#path). It will ensure that the `renderer` options of the map and paths are respected, and that the renderers do exist on the map. | #### Methods for Layers and Controls | Method | Returns | Description | | --- | --- | --- | | `addControl(<[Control](#control)> *control*)` | `this` | Adds the given control to the map | | `removeControl(<[Control](#control)> *control*)` | `this` | Removes the given control from the map | | `addLayer(<[Layer](#layer)> *layer*)` | `this` | Adds the given layer to the map | | `removeLayer(<[Layer](#layer)> *layer*)` | `this` | Removes the given layer from the map. | | `hasLayer(<[Layer](#layer)> *layer*)` | `Boolean` | Returns `true` if the given layer is currently added to the map | | `eachLayer(<Function> *fn*, <Object> *context?*)` | `this` | Iterates over the layers of the map, optionally specifying context of the iterator function. ``` map.eachLayer(function(layer){ layer.bindPopup('Hello'); }); ``` | | `openPopup(<[Popup](#popup)> *popup*)` | `this` | Opens the specified popup while closing the previously opened (to make sure only one is opened at one time for usability). | | `openPopup(<String|HTMLElement> *content*, <[LatLng](#latlng)> *latlng*, <[Popup options](#popup-option)> *options?*)` | `this` | Creates a popup with the specified content and options and opens it in the given point on a map. | | `closePopup(<[Popup](#popup)> *popup?*)` | `this` | Closes the popup previously opened with [openPopup](#map-openpopup) (or the given one). | | `openTooltip(<[Tooltip](#tooltip)> *tooltip*)` | `this` | Opens the specified tooltip. | | `openTooltip(<String|HTMLElement> *content*, <[LatLng](#latlng)> *latlng*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Creates a tooltip with the specified content and options and open it. | | `closeTooltip(<[Tooltip](#tooltip)> *tooltip*)` | `this` | Closes the tooltip given as parameter. | #### Methods for modifying map state | Method | Returns | Description | | --- | --- | --- | | `setView(<[LatLng](#latlng)> *center*, <Number> *zoom*, <[Zoom/pan options](#zoom/pan-options)> *options?*)` | `this` | Sets the view of the map (geographical center and zoom) with the given animation options. | | `setZoom(<Number> *zoom*, <[Zoom/pan options](#zoom/pan-options)> *options?*)` | `this` | Sets the zoom of the map. | | `zoomIn(<Number> *delta?*, <[Zoom options](#zoom-options)> *options?*)` | `this` | Increases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default). | | `zoomOut(<Number> *delta?*, <[Zoom options](#zoom-options)> *options?*)` | `this` | Decreases the zoom of the map by `delta` ([`zoomDelta`](#map-zoomdelta) by default). | | `setZoomAround(<[LatLng](#latlng)> *latlng*, <Number> *zoom*, <[Zoom options](#zoom-options)> *options*)` | `this` | Zooms the map while keeping a specified geographical point on the map stationary (e.g. used internally for scroll zoom and double-click zoom). | | `setZoomAround(<[Point](#point)> *offset*, <Number> *zoom*, <[Zoom options](#zoom-options)> *options*)` | `this` | Zooms the map while keeping a specified pixel on the map (relative to the top-left corner) stationary. | | `fitBounds(<[LatLngBounds](#latlngbounds)> *bounds*, <[fitBounds options](#fitbounds-options)> *options?*)` | `this` | Sets a map view that contains the given geographical bounds with the maximum zoom level possible. | | `fitWorld(<[fitBounds options](#fitbounds-options)> *options?*)` | `this` | Sets a map view that mostly contains the whole world with the maximum zoom level possible. | | `panTo(<[LatLng](#latlng)> *latlng*, <[Pan options](#pan-options)> *options?*)` | `this` | Pans the map to a given center. | | `panBy(<[Point](#point)> *offset*, <[Pan options](#pan-options)> *options?*)` | `this` | Pans the map by a given number of pixels (animated). | | `flyTo(<[LatLng](#latlng)> *latlng*, <Number> *zoom?*, <[Zoom/pan options](#zoom/pan-options)> *options?*)` | `this` | Sets the view of the map (geographical center and zoom) performing a smooth pan-zoom animation. | | `flyToBounds(<[LatLngBounds](#latlngbounds)> *bounds*, <[fitBounds options](#fitbounds-options)> *options?*)` | `this` | Sets the view of the map with a smooth animation like [`flyTo`](#map-flyto), but takes a bounds parameter like [`fitBounds`](#map-fitbounds). | | `setMaxBounds(<[LatLngBounds](#latlngbounds)> *bounds*)` | `this` | Restricts the map view to the given bounds (see the [maxBounds](#map-maxbounds) option). | | `setMinZoom(<Number> *zoom*)` | `this` | Sets the lower limit for the available zoom levels (see the [minZoom](#map-minzoom) option). | | `setMaxZoom(<Number> *zoom*)` | `this` | Sets the upper limit for the available zoom levels (see the [maxZoom](#map-maxzoom) option). | | `panInsideBounds(<[LatLngBounds](#latlngbounds)> *bounds*, <[Pan options](#pan-options)> *options?*)` | `this` | Pans the map to the closest view that would lie inside the given bounds (if it's not already), controlling the animation using the options specific, if any. | | `panInside(<[LatLng](#latlng)> *latlng*, <[padding options](#padding-options)> *options?*)` | `this` | Pans the map the minimum amount to make the `latlng` visible. Use padding options to fit the display to more restricted bounds. If `latlng` is already within the (optionally padded) display bounds, the map will not be panned. | | `invalidateSize(<[Zoom/pan options](#zoom/pan-options)> *options*)` | `this` | Checks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically, also animating pan by default. If `options.pan` is `false`, panning will not occur. If `options.debounceMoveend` is `true`, it will delay `moveend` event so that it doesn't happen often even if the method is called many times in a row. | | `invalidateSize(<Boolean> *animate*)` | `this` | Checks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically, also animating pan by default. | | `stop()` | `this` | Stops the currently running `panTo` or `flyTo` animation, if any. | #### Geolocation methods | Method | Returns | Description | | --- | --- | --- | | `locate(<[Locate options](#locate-options)> *options?*)` | `this` | Tries to locate the user using the Geolocation API, firing a [`locationfound`](#map-locationfound) event with location data on success or a [`locationerror`](#map-locationerror) event on failure, and optionally sets the map view to the user's location with respect to detection accuracy (or to the world view if geolocation failed). Note that, if your page doesn't use HTTPS, this method will fail in modern browsers ([Chrome 50 and newer](https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins)) See [`Locate options`](#locate-options) for more details. | | `stopLocate()` | `this` | Stops watching location previously initiated by `map.locate({watch: true})` and aborts resetting the map view if map.locate was called with `{setView: true}`. | #### Other Methods | Method | Returns | Description | | --- | --- | --- | | `addHandler(<String> *name*, <Function> *HandlerClass*)` | `this` | Adds a new [`Handler`](#handler) to the map, given its name and constructor function. | | `remove()` | `this` | Destroys the map and clears all related event listeners. | | `createPane(<String> *name*, <HTMLElement> *container?*)` | `HTMLElement` | Creates a new [map pane](#map-pane) with the given name if it doesn't exist already, then returns it. The pane is created as a child of `container`, or as a child of the main map pane if not set. | | `getPane(<String|HTMLElement> *pane*)` | `HTMLElement` | Returns a [map pane](#map-pane), given its name or its HTML element (its identity). | | `getPanes()` | `Object` | Returns a plain object containing the names of all [panes](#map-pane) as keys and the panes as values. | | `getContainer()` | `HTMLElement` | Returns the HTML element that contains the map. | | `whenReady(<Function> *fn*, <Object> *context?*)` | `this` | Runs the given function `fn` when the map gets initialized with a view (center and zoom) and at least one layer, or immediately if it's already initialized, optionally passing a function context. | #### Methods for Getting Map State | Method | Returns | Description | | --- | --- | --- | | `getCenter()` | `[LatLng](#latlng)` | Returns the geographical center of the map view | | `getZoom()` | `Number` | Returns the current zoom level of the map view | | `getBounds()` | `[LatLngBounds](#latlngbounds)` | Returns the geographical bounds visible in the current map view | | `getMinZoom()` | `Number` | Returns the minimum zoom level of the map (if set in the `minZoom` option of the map or of any layers), or `0` by default. | | `getMaxZoom()` | `Number` | Returns the maximum zoom level of the map (if set in the `maxZoom` option of the map or of any layers). | | `getBoundsZoom(<[LatLngBounds](#latlngbounds)> *bounds*, <Boolean> *inside?*, <[Point](#point)> *padding?*)` | `Number` | Returns the maximum zoom level on which the given bounds fit to the map view in its entirety. If `inside` (optional) is set to `true`, the method instead returns the minimum zoom level on which the map view fits into the given bounds in its entirety. | | `getSize()` | `[Point](#point)` | Returns the current size of the map container (in pixels). | | `getPixelBounds()` | `[Bounds](#bounds)` | Returns the bounds of the current map view in projected pixel coordinates (sometimes useful in layer and overlay implementations). | | `getPixelOrigin()` | `[Point](#point)` | Returns the projected pixel coordinates of the top left point of the map layer (useful in custom layer and overlay implementations). | | `getPixelWorldBounds(<Number> *zoom?*)` | `[Bounds](#bounds)` | Returns the world's bounds in pixel coordinates for zoom level `zoom`. If `zoom` is omitted, the map's current zoom level is used. | #### Conversion Methods | Method | Returns | Description | | --- | --- | --- | | `getZoomScale(<Number> *toZoom*, <Number> *fromZoom*)` | `Number` | Returns the scale factor to be applied to a map transition from zoom level `fromZoom` to `toZoom`. Used internally to help with zoom animations. | | `getScaleZoom(<Number> *scale*, <Number> *fromZoom*)` | `Number` | Returns the zoom level that the map would end up at, if it is at `fromZoom` level and everything is scaled by a factor of `scale`. Inverse of [`getZoomScale`](#map-getZoomScale). | | `project(<[LatLng](#latlng)> *latlng*, <Number> *zoom*)` | `[Point](#point)` | Projects a geographical coordinate [`LatLng`](#latlng) according to the projection of the map's CRS, then scales it according to `zoom` and the CRS's [`Transformation`](#transformation). The result is pixel coordinate relative to the CRS origin. | | `unproject(<[Point](#point)> *point*, <Number> *zoom*)` | `[LatLng](#latlng)` | Inverse of [`project`](#map-project). | | `layerPointToLatLng(<[Point](#point)> *point*)` | `[LatLng](#latlng)` | Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin), returns the corresponding geographical coordinate (for the current zoom level). | | `latLngToLayerPoint(<[LatLng](#latlng)> *latlng*)` | `[Point](#point)` | Given a geographical coordinate, returns the corresponding pixel coordinate relative to the [origin pixel](#map-getpixelorigin). | | `wrapLatLng(<[LatLng](#latlng)> *latlng*)` | `[LatLng](#latlng)` | Returns a [`LatLng`](#latlng) where `lat` and `lng` has been wrapped according to the map's CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds. By default this means longitude is wrapped around the dateline so its value is between -180 and +180 degrees. | | `wrapLatLngBounds(<[LatLngBounds](#latlngbounds)> *bounds*)` | `[LatLngBounds](#latlngbounds)` | Returns a [`LatLngBounds`](#latlngbounds) with the same size as the given one, ensuring that its center is within the CRS's bounds. By default this means the center longitude is wrapped around the dateline so its value is between -180 and +180 degrees, and the majority of the bounds overlaps the CRS's bounds. | | `distance(<[LatLng](#latlng)> *latlng1*, <[LatLng](#latlng)> *latlng2*)` | `Number` | Returns the distance between two geographical coordinates according to the map's CRS. By default this measures distance in meters. | | `containerPointToLayerPoint(<[Point](#point)> *point*)` | `[Point](#point)` | Given a pixel coordinate relative to the map container, returns the corresponding pixel coordinate relative to the [origin pixel](#map-getpixelorigin). | | `layerPointToContainerPoint(<[Point](#point)> *point*)` | `[Point](#point)` | Given a pixel coordinate relative to the [origin pixel](#map-getpixelorigin), returns the corresponding pixel coordinate relative to the map container. | | `containerPointToLatLng(<[Point](#point)> *point*)` | `[LatLng](#latlng)` | Given a pixel coordinate relative to the map container, returns the corresponding geographical coordinate (for the current zoom level). | | `latLngToContainerPoint(<[LatLng](#latlng)> *latlng*)` | `[Point](#point)` | Given a geographical coordinate, returns the corresponding pixel coordinate relative to the map container. | | `mouseEventToContainerPoint(<[MouseEvent](#mouseevent)> *ev*)` | `[Point](#point)` | Given a MouseEvent object, returns the pixel coordinate relative to the map container where the event took place. | | `mouseEventToLayerPoint(<[MouseEvent](#mouseevent)> *ev*)` | `[Point](#point)` | Given a MouseEvent object, returns the pixel coordinate relative to the [origin pixel](#map-getpixelorigin) where the event took place. | | `mouseEventToLatLng(<[MouseEvent](#mouseevent)> *ev*)` | `[LatLng](#latlng)` | Given a MouseEvent object, returns geographical coordinate where the event took place. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | ### Properties #### Controls | Property | Type | Description | | --- | --- | --- | | `zoomControl` | `[Control.Zoom](#control-zoom)` | The default zoom control (only available if the [`zoomControl` option](#map-zoomcontrol) was `true` when creating the map). | #### Handlers | Property | Type | Description | | --- | --- | --- | | `boxZoom` | `[Handler](#handler)` | Box (shift-drag with mouse) zoom handler. | | `doubleClickZoom` | `[Handler](#handler)` | Double click zoom handler. | | `dragging` | `[Handler](#handler)` | Map dragging handler (by both mouse and touch). | | `keyboard` | `[Handler](#handler)` | Keyboard navigation handler. | | `scrollWheelZoom` | `[Handler](#handler)` | Scroll wheel zoom handler. | | `tapHold` | `[Handler](#handler)` | Long tap handler to simulate `contextmenu` event (useful in mobile Safari). | | `touchZoom` | `[Handler](#handler)` | Touch zoom handler. | ### Map panes Panes are DOM elements used to control the ordering of layers on the map. You can access panes with [`map.getPane`](#map-getpane) or [`map.getPanes`](#map-getpanes) methods. New panes can be created with the [`map.createPane`](#map-createpane) method. Every map has the following default panes that differ only in zIndex. | Pane | Type | Z-index | Description | | --- | --- | --- | --- | | `mapPane` | `HTMLElement` | `'auto'` | Pane that contains all other map panes | | `tilePane` | `HTMLElement` | `200` | Pane for [`GridLayer`](#gridlayer)s and [`TileLayer`](#tilelayer)s | | `overlayPane` | `HTMLElement` | `400` | Pane for vectors ([`Path`](#path)s, like [`Polyline`](#polyline)s and [`Polygon`](#polygon)s), [`ImageOverlay`](#imageoverlay)s and [`VideoOverlay`](#videooverlay)s | | `shadowPane` | `HTMLElement` | `500` | Pane for overlay shadows (e.g. [`Marker`](#marker) shadows) | | `markerPane` | `HTMLElement` | `600` | Pane for [`Icon`](#icon)s of [`Marker`](#marker)s | | `tooltipPane` | `HTMLElement` | `650` | Pane for [`Tooltip`](#tooltip)s. | | `popupPane` | `HTMLElement` | `700` | Pane for [`Popup`](#popup)s. | ### Locate options Some of the geolocation methods for [`Map`](#map) take in an `options` parameter. This is a plain javascript object with the following optional components: | Option | Type | Default | Description | | --- | --- | --- | --- | | `watch` | `Boolean` | `false` | If `true`, starts continuous watching of location changes (instead of detecting it once) using W3C `watchPosition` method. You can later stop watching using `map.stopLocate()` method. | | `setView` | `Boolean` | `false` | If `true`, automatically sets the map view to the user location with respect to detection accuracy, or to world view if geolocation failed. | | `maxZoom` | `Number` | `Infinity` | The maximum zoom for automatic view setting when using `setView` option. | | `timeout` | `Number` | `10000` | Number of milliseconds to wait for a response from geolocation before firing a `locationerror` event. | | `maximumAge` | `Number` | `0` | Maximum age of detected location. If less than this amount of milliseconds passed since last geolocation response, `locate` will return a cached location. | | `enableHighAccuracy` | `Boolean` | `false` | Enables high accuracy, see [description in the W3C spec](https://w3c.github.io/geolocation-api/#enablehighaccuracy-member). | ### Zoom options Some of the [`Map`](#map) methods which modify the zoom level take in an `options` parameter. This is a plain javascript object with the following optional components: | Option | Type | Default | Description | | --- | --- | --- | --- | | `animate` | `Boolean` | | If not specified, zoom animation will happen if the zoom origin is inside the current view. If `true`, the map will attempt animating zoom disregarding where zoom origin is. Setting `false` will make it always reset the view completely without animation. | ### Pan options Some of the [`Map`](#map) methods which modify the center of the map take in an `options` parameter. This is a plain javascript object with the following optional components: | Option | Type | Default | Description | | --- | --- | --- | --- | | `animate` | `Boolean` | | If `true`, panning will always be animated if possible. If `false`, it will not animate panning, either resetting the map view if panning more than a screen away, or just setting a new offset for the map pane (except for `panBy` which always does the latter). | | `duration` | `Number` | `0.25` | Duration of animated panning, in seconds. | | `easeLinearity` | `Number` | `0.25` | The curvature factor of panning animation easing (third parameter of the [Cubic Bezier curve](https://cubic-bezier.com/)). 1.0 means linear animation, and the smaller this number, the more bowed the curve. | | `noMoveStart` | `Boolean` | `false` | If `true`, panning won't fire `movestart` event on start (used internally for panning inertia). | ### Zoom/pan options Options inherited from [Zoom options](#zoom-options) | Option | Type | Default | Description | | --- | --- | --- | --- | | `animate` | `Boolean` | | If not specified, zoom animation will happen if the zoom origin is inside the current view. If `true`, the map will attempt animating zoom disregarding where zoom origin is. Setting `false` will make it always reset the view completely without animation. | Options inherited from [Pan options](#pan-options) | Option | Type | Default | Description | | --- | --- | --- | --- | | `duration` | `Number` | `0.25` | Duration of animated panning, in seconds. | | `easeLinearity` | `Number` | `0.25` | The curvature factor of panning animation easing (third parameter of the [Cubic Bezier curve](https://cubic-bezier.com/)). 1.0 means linear animation, and the smaller this number, the more bowed the curve. | | `noMoveStart` | `Boolean` | `false` | If `true`, panning won't fire `movestart` event on start (used internally for panning inertia). | ### Padding options | Option | Type | Default | Description | | --- | --- | --- | --- | | `paddingTopLeft` | `[Point](#point)` | `[0, 0]` | Sets the amount of padding in the top left corner of a map container that shouldn't be accounted for when setting the view to fit bounds. Useful if you have some control overlays on the map like a sidebar and you don't want them to obscure objects you're zooming to. | | `paddingBottomRight` | `[Point](#point)` | `[0, 0]` | The same for the bottom right corner of the map. | | `padding` | `[Point](#point)` | `[0, 0]` | Equivalent of setting both top left and bottom right padding to the same value. | ### FitBounds options | Option | Type | Default | Description | | --- | --- | --- | --- | | `maxZoom` | `Number` | `null` | The maximum possible zoom to use. | Options inherited from [Zoom options](#zoom-options) | Option | Type | Default | Description | | --- | --- | --- | --- | | `animate` | `Boolean` | | If not specified, zoom animation will happen if the zoom origin is inside the current view. If `true`, the map will attempt animating zoom disregarding where zoom origin is. Setting `false` will make it always reset the view completely without animation. | Options inherited from [Pan options](#pan-options) | Option | Type | Default | Description | | --- | --- | --- | --- | | `duration` | `Number` | `0.25` | Duration of animated panning, in seconds. | | `easeLinearity` | `Number` | `0.25` | The curvature factor of panning animation easing (third parameter of the [Cubic Bezier curve](https://cubic-bezier.com/)). 1.0 means linear animation, and the smaller this number, the more bowed the curve. | | `noMoveStart` | `Boolean` | `false` | If `true`, panning won't fire `movestart` event on start (used internally for panning inertia). | Options inherited from [Padding options](#padding-options) | Option | Type | Default | Description | | --- | --- | --- | --- | | `paddingTopLeft` | `[Point](#point)` | `[0, 0]` | Sets the amount of padding in the top left corner of a map container that shouldn't be accounted for when setting the view to fit bounds. Useful if you have some control overlays on the map like a sidebar and you don't want them to obscure objects you're zooming to. | | `paddingBottomRight` | `[Point](#point)` | `[0, 0]` | The same for the bottom right corner of the map. | | `padding` | `[Point](#point)` | `[0, 0]` | Equivalent of setting both top left and bottom right padding to the same value. | Marker ------ L.Marker is used to display clickable/draggable icons on the map. Extends [`Layer`](#layer). ### Usage example ``` L.marker([50.5, 30.5]).addTo(map); ``` ### Creation | Factory | Description | | --- | --- | | `L.marker(<[LatLng](#latlng)> *latlng*, <[Marker options](#marker-option)> *options?*)` | Instantiates a Marker object given a geographical point and optionally an options object. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `icon` | `[Icon](#icon)` | `*` | Icon instance to use for rendering the marker. See [Icon documentation](#icon) for details on how to customize the marker icon. If not specified, a common instance of [`L.Icon.Default`](#icon-default) is used. | | `keyboard` | `Boolean` | `true` | Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. | | `title` | `String` | `''` | Text for the browser tooltip that appear on marker hover (no tooltip by default). [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled). | | `alt` | `String` | `'Marker'` | Text for the `alt` attribute of the icon image. [Useful for accessibility](https://leafletjs.com/examples/accessibility/#markers-must-be-labelled). | | `zIndexOffset` | `Number` | `0` | By default, marker images zIndex is set automatically based on its latitude. Use this option if you want to put the marker on top of all others (or below), specifying a high value like `1000` (or high negative value, respectively). | | `opacity` | `Number` | `1.0` | The opacity of the marker. | | `riseOnHover` | `Boolean` | `false` | If `true`, the marker will get on top of others when you hover the mouse over it. | | `riseOffset` | `Number` | `250` | The z-index offset used for the `riseOnHover` feature. | | `pane` | `String` | `'markerPane'` | `Map pane` where the markers icon will be added. | | `shadowPane` | `String` | `'shadowPane'` | `Map pane` where the markers shadow will be added. | | `bubblingMouseEvents` | `Boolean` | `false` | When `true`, a mouse event on this marker will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | | `autoPanOnFocus` | `Boolean` | `true` | When `true`, the map will pan whenever the marker is focused (via e.g. pressing `tab` on the keyboard) to ensure the marker is visible within the map's bounds | #### Draggable marker options | Option | Type | Default | Description | | --- | --- | --- | --- | | `draggable` | `Boolean` | `false` | Whether the marker is draggable with mouse/touch or not. | | `autoPan` | `Boolean` | `false` | Whether to pan the map when dragging this marker near its edge or not. | | `autoPanPadding` | `[Point](#point)` | `Point(50, 50)` | Distance (in pixels to the left/right and to the top/bottom) of the map edge to start panning the map. | | `autoPanSpeed` | `Number` | `10` | Number of pixels the map should pan by. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `true` | If `false`, the layer will not emit mouse events and will act as a part of the underlying map. | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events | Event | Data | Description | | --- | --- | --- | | `move` | `[Event](#event)` | Fired when the marker is moved via [`setLatLng`](#marker-setlatlng) or by [dragging](#marker-dragging). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`. | #### Dragging events | Event | Data | Description | | --- | --- | --- | | `dragstart` | `[Event](#event)` | Fired when the user starts dragging the marker. | | `movestart` | `[Event](#event)` | Fired when the marker starts moving (because of dragging). | | `drag` | `[Event](#event)` | Fired repeatedly while the user drags the marker. | | `dragend` | `[DragEndEvent](#dragendevent)` | Fired when the user stops dragging the marker. | | `moveend` | `[Event](#event)` | Fired when the marker stops moving (because of dragging). | Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods In addition to [shared layer methods](#layer) like `addTo()` and `remove()` and [popup methods](#popup) like bindPopup() you can also use the following methods: | Method | Returns | Description | | --- | --- | --- | | `getLatLng()` | `[LatLng](#latlng)` | Returns the current geographical position of the marker. | | `setLatLng(<[LatLng](#latlng)> *latlng*)` | `this` | Changes the marker position to the given point. | | `setZIndexOffset(<Number> *offset*)` | `this` | Changes the [zIndex offset](#marker-zindexoffset) of the marker. | | `getIcon()` | `[Icon](#icon)` | Returns the current icon used by the marker | | `setIcon(<[Icon](#icon)> *icon*)` | `this` | Changes the marker icon. | | `setOpacity(<Number> *opacity*)` | `this` | Changes the opacity of the marker. | #### Other methods | Method | Returns | Description | | --- | --- | --- | | `toGeoJSON(<Number|false> *precision?*)` | `Object` | Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the marker (as a GeoJSON [`Point`](#point) Feature). | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | ### Properties #### Interaction handlers Interaction handlers are properties of a marker instance that allow you to control interaction behavior in runtime, enabling or disabling certain features such as dragging (see [`Handler`](#handler) methods). Example: ``` marker.dragging.disable(); ``` | Property | Type | Description | | --- | --- | --- | | `dragging` | `[Handler](#handler)` | Marker dragging handler (by both mouse and touch). Only valid when the marker is on the map (Otherwise set [`marker.options.draggable`](#marker-draggable)). | DivOverlay ---------- Base model for L.Popup and L.Tooltip. Inherit from it for custom overlays like plugins. ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `false` | If true, the popup/tooltip will listen to the mouse events. | | `offset` | `[Point](#point)` | `Point(0, 0)` | The offset of the overlay position. | | `className` | `String` | `''` | A custom CSS class name to assign to the overlay. | | `pane` | `String` | `undefined` | `Map pane` where the overlay will be added. | | `content` | `String|HTMLElement|Function` | `''` | Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this layer will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events #### DivOverlay events | Event | Data | Description | | --- | --- | --- | | `contentupdate` | `[Event](#event)` | Fired when the content of the overlay is updated | Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `openOn(<[Map](#map)> *map*)` | `this` | Adds the overlay to the map. Alternative to `map.openPopup(popup)`/`.openTooltip(tooltip)`. | | `close()` | `this` | Closes the overlay. Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)` and `layer.closePopup()`/`.closeTooltip()`. | | `toggle(<[Layer](#layer)> *layer?*)` | `this` | Opens or closes the overlay bound to layer depending on its current state. Argument may be omitted only for overlay bound to layer. Alternative to `layer.togglePopup()`/`.toggleTooltip()`. | | `getLatLng()` | `[LatLng](#latlng)` | Returns the geographical point of the overlay. | | `setLatLng(<[LatLng](#latlng)> *latlng*)` | `this` | Sets the geographical point where the overlay will open. | | `getContent()` | `String|HTMLElement` | Returns the content of the overlay. | | `setContent(<String|HTMLElement|Function> *htmlContent*)` | `this` | Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay. | | `getElement()` | `String|HTMLElement` | Returns the HTML container of the overlay. | | `update()` | `null` | Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded. | | `isOpen()` | `Boolean` | Returns `true` when the overlay is visible on the map. | | `bringToFront()` | `this` | Brings this overlay in front of other overlays (in the same map pane). | | `bringToBack()` | `this` | Brings this overlay to the back of other overlays (in the same map pane). | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Popup ----- Used to open popups in certain places of the map. Use [Map.openPopup](#map-openpopup) to open popups while making sure that only one popup is open at one time (recommended for usability), or use [Map.addLayer](#map-addlayer) to open as many as you want. ### Usage example If you want to just bind a popup to marker click and then open it, it's really easy: ``` marker.bindPopup(popupContent).openPopup(); ``` Path overlays like polylines also have a `bindPopup` method. A popup can be also standalone: ``` var popup = L.popup() .setLatLng(latlng) .setContent('<p>Hello world!<br />This is a nice popup.</p>') .openOn(map); ``` or ``` var popup = L.popup(latlng, {content: '<p>Hello world!<br />This is a nice popup.</p>') .openOn(map); ``` ### Creation | Factory | Description | | --- | --- | | `L.popup(<[Popup options](#popup-option)> *options?*, <[Layer](#layer)> *source?*)` | Instantiates a [`Popup`](#popup) object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the popup with a reference to the Layer to which it refers. | | `L.popup(<[LatLng](#latlng)> *latlng*, <[Popup options](#popup-option)> *options?*)` | Instantiates a [`Popup`](#popup) object given `latlng` where the popup will open and an optional `options` object that describes its appearance and location. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'popupPane'` | `Map pane` where the popup will be added. | | `offset` | `[Point](#point)` | `Point(0, 7)` | The offset of the popup position. | | `maxWidth` | `Number` | `300` | Max width of the popup, in pixels. | | `minWidth` | `Number` | `50` | Min width of the popup, in pixels. | | `maxHeight` | `Number` | `null` | If set, creates a scrollable container of the given height inside a popup if its content exceeds it. The scrollable container can be styled using the `leaflet-popup-scrolled` CSS class selector. | | `autoPan` | `Boolean` | `true` | Set it to `false` if you don't want the map to do panning animation to fit the opened popup. | | `autoPanPaddingTopLeft` | `[Point](#point)` | `null` | The margin between the popup and the top left corner of the map view after autopanning was performed. | | `autoPanPaddingBottomRight` | `[Point](#point)` | `null` | The margin between the popup and the bottom right corner of the map view after autopanning was performed. | | `autoPanPadding` | `[Point](#point)` | `Point(5, 5)` | Equivalent of setting both top left and bottom right autopan padding to the same value. | | `keepInView` | `Boolean` | `false` | Set it to `true` if you want to prevent users from panning the popup off of the screen while it is open. | | `closeButton` | `Boolean` | `true` | Controls the presence of a close button in the popup. | | `autoClose` | `Boolean` | `true` | Set it to `false` if you want to override the default behavior of the popup closing when another popup is opened. | | `closeOnEscapeKey` | `Boolean` | `true` | Set it to `false` if you want to override the default behavior of the ESC key for closing of the popup. | | `closeOnClick` | `Boolean` | `*` | Set it if you want to override the default behavior of the popup closing when user clicks on the map. Defaults to the map's [`closePopupOnClick`](#map-closepopuponclick) option. | | `className` | `String` | `''` | A custom CSS class name to assign to the popup. | Options inherited from [DivOverlay](#divoverlay) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `false` | If true, the popup/tooltip will listen to the mouse events. | | `content` | `String|HTMLElement|Function` | `''` | Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this layer will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events DivOverlay events inherited from [DivOverlay](#divoverlay) | Event | Data | Description | | --- | --- | --- | | `contentupdate` | `[Event](#event)` | Fired when the content of the overlay is updated | Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `openOn(<[Map](#map)> *map*)` | `this` | Alternative to `map.openPopup(popup)`. Adds the popup to the map and closes the previous one. | Methods inherited from [DivOverlay](#divoverlay) | Method | Returns | Description | | --- | --- | --- | | `close()` | `this` | Closes the overlay. Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)` and `layer.closePopup()`/`.closeTooltip()`. | | `toggle(<[Layer](#layer)> *layer?*)` | `this` | Opens or closes the overlay bound to layer depending on its current state. Argument may be omitted only for overlay bound to layer. Alternative to `layer.togglePopup()`/`.toggleTooltip()`. | | `getLatLng()` | `[LatLng](#latlng)` | Returns the geographical point of the overlay. | | `setLatLng(<[LatLng](#latlng)> *latlng*)` | `this` | Sets the geographical point where the overlay will open. | | `getContent()` | `String|HTMLElement` | Returns the content of the overlay. | | `setContent(<String|HTMLElement|Function> *htmlContent*)` | `this` | Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay. | | `getElement()` | `String|HTMLElement` | Returns the HTML container of the overlay. | | `update()` | `null` | Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded. | | `isOpen()` | `Boolean` | Returns `true` when the overlay is visible on the map. | | `bringToFront()` | `this` | Brings this overlay in front of other overlays (in the same map pane). | | `bringToBack()` | `this` | Brings this overlay to the back of other overlays (in the same map pane). | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Tooltip ------- Used to display small texts on top of map layers. ### Usage example If you want to just bind a tooltip to marker: ``` marker.bindTooltip("my tooltip text").openTooltip(); ``` Path overlays like polylines also have a `bindTooltip` method. A tooltip can be also standalone: ``` var tooltip = L.tooltip() .setLatLng(latlng) .setContent('Hello world!<br />This is a nice tooltip.') .addTo(map); ``` or ``` var tooltip = L.tooltip(latlng, {content: 'Hello world!<br />This is a nice tooltip.'}) .addTo(map); ``` Note about tooltip offset. Leaflet takes two options in consideration for computing tooltip offsetting: * the `offset` Tooltip option: it defaults to [0, 0], and it's specific to one tooltip. Add a positive x offset to move the tooltip to the right, and a positive y offset to move it to the bottom. Negatives will move to the left and top. * the `tooltipAnchor` Icon option: this will only be considered for Marker. You should adapt this value if you use a custom icon. ### Creation | Factory | Description | | --- | --- | | `L.tooltip(<[Tooltip options](#tooltip-option)> *options?*, <[Layer](#layer)> *source?*)` | Instantiates a [`Tooltip`](#tooltip) object given an optional `options` object that describes its appearance and location and an optional `source` object that is used to tag the tooltip with a reference to the Layer to which it refers. | | `L.tooltip(<[LatLng](#latlng)> *latlng*, <[Tooltip options](#tooltip-option)> *options?*)` | Instantiates a [`Tooltip`](#tooltip) object given `latlng` where the tooltip will open and an optional `options` object that describes its appearance and location. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'tooltipPane'` | `Map pane` where the tooltip will be added. | | `offset` | `[Point](#point)` | `Point(0, 0)` | Optional offset of the tooltip position. | | `direction` | `String` | `'auto'` | Direction where to open the tooltip. Possible values are: `right`, `left`, `top`, `bottom`, `center`, `auto`. `auto` will dynamically switch between `right` and `left` according to the tooltip position on the map. | | `permanent` | `Boolean` | `false` | Whether to open the tooltip permanently or only on mouseover. | | `sticky` | `Boolean` | `false` | If true, the tooltip will follow the mouse instead of being fixed at the feature center. | | `opacity` | `Number` | `0.9` | Tooltip container opacity. | Options inherited from [DivOverlay](#divoverlay) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `false` | If true, the popup/tooltip will listen to the mouse events. | | `className` | `String` | `''` | A custom CSS class name to assign to the overlay. | | `content` | `String|HTMLElement|Function` | `''` | Sets the HTML content of the overlay while initializing. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this layer will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events DivOverlay events inherited from [DivOverlay](#divoverlay) | Event | Data | Description | | --- | --- | --- | | `contentupdate` | `[Event](#event)` | Fired when the content of the overlay is updated | Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods Methods inherited from [DivOverlay](#divoverlay) | Method | Returns | Description | | --- | --- | --- | | `openOn(<[Map](#map)> *map*)` | `this` | Adds the overlay to the map. Alternative to `map.openPopup(popup)`/`.openTooltip(tooltip)`. | | `close()` | `this` | Closes the overlay. Alternative to `map.closePopup(popup)`/`.closeTooltip(tooltip)` and `layer.closePopup()`/`.closeTooltip()`. | | `toggle(<[Layer](#layer)> *layer?*)` | `this` | Opens or closes the overlay bound to layer depending on its current state. Argument may be omitted only for overlay bound to layer. Alternative to `layer.togglePopup()`/`.toggleTooltip()`. | | `getLatLng()` | `[LatLng](#latlng)` | Returns the geographical point of the overlay. | | `setLatLng(<[LatLng](#latlng)> *latlng*)` | `this` | Sets the geographical point where the overlay will open. | | `getContent()` | `String|HTMLElement` | Returns the content of the overlay. | | `setContent(<String|HTMLElement|Function> *htmlContent*)` | `this` | Sets the HTML content of the overlay. If a function is passed the source layer will be passed to the function. The function should return a `String` or `HTMLElement` to be used in the overlay. | | `getElement()` | `String|HTMLElement` | Returns the HTML container of the overlay. | | `update()` | `null` | Updates the overlay content, layout and position. Useful for updating the overlay after something inside changed, e.g. image loaded. | | `isOpen()` | `Boolean` | Returns `true` when the overlay is visible on the map. | | `bringToFront()` | `this` | Brings this overlay in front of other overlays (in the same map pane). | | `bringToBack()` | `this` | Brings this overlay to the back of other overlays (in the same map pane). | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | TileLayer --------- Used to load and display tile layers on the map. Note that most tile servers require attribution, which you can set under [`Layer`](#layer). Extends [`GridLayer`](#gridlayer). ### Usage example ``` L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}', {foo: 'bar', attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map); ``` #### URL template A string of the following form: ``` 'https://{s}.somedomain.com/blabla/{z}/{x}/{y}{r}.png' ``` `{s}` means one of the available subdomains (used sequentially to help with browser parallel requests per domain limitation; subdomain values are specified in options; `a`, `b` or `c` by default, can be omitted), `{z}` — zoom level, `{x}` and `{y}` — tile coordinates. `{r}` can be used to add "@2x" to the URL to load retina tiles. You can use custom keys in the template, which will be [evaluated](#util-template) from TileLayer options, like this: ``` L.tileLayer('https://{s}.somedomain.com/{foo}/{z}/{x}/{y}.png', {foo: 'bar'}); ``` ### Creation #### Extension methods | Factory | Description | | --- | --- | | `L.tilelayer(<String> *urlTemplate*, <[TileLayer options](#tilelayer-option)> *options?*)` | Instantiates a tile layer object given a `URL template` and optionally an options object. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `minZoom` | `Number` | `0` | The minimum zoom level down to which this layer will be displayed (inclusive). | | `maxZoom` | `Number` | `18` | The maximum zoom level up to which this layer will be displayed (inclusive). | | `subdomains` | `String|String[]` | `'abc'` | Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings. | | `errorTileUrl` | `String` | `''` | URL to the tile image to show in place of the tile that failed to load. | | `zoomOffset` | `Number` | `0` | The zoom number used in tile URLs will be offset with this value. | | `tms` | `Boolean` | `false` | If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services). | | `zoomReverse` | `Boolean` | `false` | If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`) | | `detectRetina` | `Boolean` | `false` | If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution. | | `crossOrigin` | `Boolean|String` | `false` | Whether the crossOrigin attribute will be added to the tiles. If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data. Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. | | `referrerPolicy` | `Boolean|String` | `false` | Whether the referrerPolicy attribute will be added to the tiles. If a String is provided, all tiles will have their referrerPolicy attribute set to the String provided. This may be needed if your map's rendering context has a strict default but your tile provider expects a valid referrer (e.g. to validate an API token). Refer to [HTMLImageElement.referrerPolicy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/referrerPolicy) for valid String values. | Options inherited from [GridLayer](#gridlayer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `tileSize` | `Number|Point` | `256` | Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise. | | `opacity` | `Number` | `1.0` | Opacity of the tiles. Can be used in the `createTile()` function. | | `updateWhenIdle` | `Boolean` | `(depends)` | Load new tiles only when panning ends. `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation. `false` otherwise in order to display new tiles *during* panning, since it is easy to pan outside the [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers. | | `updateWhenZooming` | `Boolean` | `true` | By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends. | | `updateInterval` | `Number` | `200` | Tiles will not update more than once every `updateInterval` milliseconds when panning. | | `zIndex` | `Number` | `1` | The explicit zIndex of the tile layer. | | `bounds` | `[LatLngBounds](#latlngbounds)` | `undefined` | If set, tiles will only be loaded inside the set [`LatLngBounds`](#latlngbounds). | | `maxNativeZoom` | `Number` | `undefined` | Maximum zoom number the tile source has available. If it is specified, the tiles on all zoom levels higher than `maxNativeZoom` will be loaded from `maxNativeZoom` level and auto-scaled. | | `minNativeZoom` | `Number` | `undefined` | Minimum zoom number the tile source has available. If it is specified, the tiles on all zoom levels lower than `minNativeZoom` will be loaded from `minNativeZoom` level and auto-scaled. | | `noWrap` | `Boolean` | `false` | Whether the layer is wrapped around the antimeridian. If `true`, the GridLayer will only be displayed once at low zoom levels. Has no effect when the [map CRS](#map-crs) doesn't wrap around. Can be used in combination with [`bounds`](#gridlayer-bounds) to prevent requesting tiles outside the CRS limits. | | `pane` | `String` | `'tilePane'` | `Map pane` where the grid layer will be added. | | `className` | `String` | `''` | A custom class name to assign to the tile layer. Empty by default. | | `keepBuffer` | `Number` | `2` | When panning the map, keep this many rows and columns of tiles before unloading them. | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events #### Extension methods | Event | Data | Description | | --- | --- | --- | | `tileabort` | `[TileEvent](#tileevent)` | Fired when a tile was loading but is now not wanted. | Events inherited from [GridLayer](#gridlayer) | Event | Data | Description | | --- | --- | --- | | `loading` | `[Event](#event)` | Fired when the grid layer starts loading tiles. | | `tileunload` | `[TileEvent](#tileevent)` | Fired when a tile is removed (e.g. when a tile goes off the screen). | | `tileloadstart` | `[TileEvent](#tileevent)` | Fired when a tile is requested and starts loading. | | `tileerror` | `[TileErrorEvent](#tileerrorevent)` | Fired when there is an error loading a tile. | | `tileload` | `[TileEvent](#tileevent)` | Fired when a tile loads. | | `load` | `[Event](#event)` | Fired when the grid layer loaded all visible tiles. | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `setUrl(<String> *url*, <Boolean> *noRedraw?*)` | `this` | Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`). If the URL does not change, the layer will not be redrawn unless the noRedraw parameter is set to false. | | `createTile(<Object> *coords*, <Function> *done?*)` | `HTMLElement` | Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile) to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done` callback is called when the tile has been loaded. | #### Extension methods Layers extending [`TileLayer`](#tilelayer) might reimplement the following method. | Method | Returns | Description | | --- | --- | --- | | `getTileUrl(<Object> *coords*)` | `String` | Called only internally, returns the URL for a tile given its coordinates. Classes extending [`TileLayer`](#tilelayer) can override this function to provide custom tile URL naming schemes. | Methods inherited from [GridLayer](#gridlayer) | Method | Returns | Description | | --- | --- | --- | | `bringToFront()` | `this` | Brings the tile layer to the top of all tile layers. | | `bringToBack()` | `this` | Brings the tile layer to the bottom of all tile layers. | | `getContainer()` | `HTMLElement` | Returns the HTML element that contains the tiles for this layer. | | `setOpacity(<Number> *opacity*)` | `this` | Changes the [opacity](#gridlayer-opacity) of the grid layer. | | `setZIndex(<Number> *zIndex*)` | `this` | Changes the [zIndex](#gridlayer-zindex) of the grid layer. | | `isLoading()` | `Boolean` | Returns `true` if any tile in the grid layer has not finished loading. | | `redraw()` | `this` | Causes the layer to clear all the tiles and request them again. | | `getTileSize()` | `[Point](#point)` | Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | TileLayer.WMS ------------- Used to display [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services as tile layers on the map. Extends [`TileLayer`](#tilelayer). ### Usage example ``` var nexrad = L.tileLayer.wms("http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi", { layers: 'nexrad-n0r-900913', format: 'image/png', transparent: true, attribution: "Weather data © 2012 IEM Nexrad" }); ``` ### Creation | Factory | Description | | --- | --- | | `L.tileLayer.wms(<String> *baseUrl*, <[TileLayer.WMS options](#tilelayer-wms-option)> *options*)` | Instantiates a WMS tile layer object given a base URL of the WMS service and a WMS parameters/options object. | ### Options If any custom options not documented here are used, they will be sent to the WMS server as extra parameters in each request URL. This can be useful for [non-standard vendor WMS parameters](https://docs.geoserver.org/stable/en/user/services/wms/vendor.html). | Option | Type | Default | Description | | --- | --- | --- | --- | | `layers` | `String` | `''` | **(required)** Comma-separated list of WMS layers to show. | | `styles` | `String` | `''` | Comma-separated list of WMS styles. | | `format` | `String` | `'image/jpeg'` | WMS image format (use `'image/png'` for layers with transparency). | | `transparent` | `Boolean` | `false` | If `true`, the WMS service will return images with transparency. | | `version` | `String` | `'1.1.1'` | Version of the WMS service to use | | `crs` | `[CRS](#crs)` | `null` | Coordinate Reference System to use for the WMS requests, defaults to map CRS. Don't change this if you're not sure what it means. | | `uppercase` | `Boolean` | `false` | If `true`, WMS request parameter keys will be uppercase. | Options inherited from [TileLayer](#tilelayer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `minZoom` | `Number` | `0` | The minimum zoom level down to which this layer will be displayed (inclusive). | | `maxZoom` | `Number` | `18` | The maximum zoom level up to which this layer will be displayed (inclusive). | | `subdomains` | `String|String[]` | `'abc'` | Subdomains of the tile service. Can be passed in the form of one string (where each letter is a subdomain name) or an array of strings. | | `errorTileUrl` | `String` | `''` | URL to the tile image to show in place of the tile that failed to load. | | `zoomOffset` | `Number` | `0` | The zoom number used in tile URLs will be offset with this value. | | `tms` | `Boolean` | `false` | If `true`, inverses Y axis numbering for tiles (turn this on for [TMS](https://en.wikipedia.org/wiki/Tile_Map_Service) services). | | `zoomReverse` | `Boolean` | `false` | If set to true, the zoom number used in tile URLs will be reversed (`maxZoom - zoom` instead of `zoom`) | | `detectRetina` | `Boolean` | `false` | If `true` and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution. | | `crossOrigin` | `Boolean|String` | `false` | Whether the crossOrigin attribute will be added to the tiles. If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data. Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. | | `referrerPolicy` | `Boolean|String` | `false` | Whether the referrerPolicy attribute will be added to the tiles. If a String is provided, all tiles will have their referrerPolicy attribute set to the String provided. This may be needed if your map's rendering context has a strict default but your tile provider expects a valid referrer (e.g. to validate an API token). Refer to [HTMLImageElement.referrerPolicy](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/referrerPolicy) for valid String values. | Options inherited from [GridLayer](#gridlayer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `tileSize` | `Number|Point` | `256` | Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise. | | `opacity` | `Number` | `1.0` | Opacity of the tiles. Can be used in the `createTile()` function. | | `updateWhenIdle` | `Boolean` | `(depends)` | Load new tiles only when panning ends. `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation. `false` otherwise in order to display new tiles *during* panning, since it is easy to pan outside the [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers. | | `updateWhenZooming` | `Boolean` | `true` | By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends. | | `updateInterval` | `Number` | `200` | Tiles will not update more than once every `updateInterval` milliseconds when panning. | | `zIndex` | `Number` | `1` | The explicit zIndex of the tile layer. | | `bounds` | `[LatLngBounds](#latlngbounds)` | `undefined` | If set, tiles will only be loaded inside the set [`LatLngBounds`](#latlngbounds). | | `maxNativeZoom` | `Number` | `undefined` | Maximum zoom number the tile source has available. If it is specified, the tiles on all zoom levels higher than `maxNativeZoom` will be loaded from `maxNativeZoom` level and auto-scaled. | | `minNativeZoom` | `Number` | `undefined` | Minimum zoom number the tile source has available. If it is specified, the tiles on all zoom levels lower than `minNativeZoom` will be loaded from `minNativeZoom` level and auto-scaled. | | `noWrap` | `Boolean` | `false` | Whether the layer is wrapped around the antimeridian. If `true`, the GridLayer will only be displayed once at low zoom levels. Has no effect when the [map CRS](#map-crs) doesn't wrap around. Can be used in combination with [`bounds`](#gridlayer-bounds) to prevent requesting tiles outside the CRS limits. | | `pane` | `String` | `'tilePane'` | `Map pane` where the grid layer will be added. | | `className` | `String` | `''` | A custom class name to assign to the tile layer. Empty by default. | | `keepBuffer` | `Number` | `2` | When panning the map, keep this many rows and columns of tiles before unloading them. | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events Extension methods inherited from [TileLayer](#tilelayer) | Event | Data | Description | | --- | --- | --- | | `tileabort` | `[TileEvent](#tileevent)` | Fired when a tile was loading but is now not wanted. | Events inherited from [GridLayer](#gridlayer) | Event | Data | Description | | --- | --- | --- | | `loading` | `[Event](#event)` | Fired when the grid layer starts loading tiles. | | `tileunload` | `[TileEvent](#tileevent)` | Fired when a tile is removed (e.g. when a tile goes off the screen). | | `tileloadstart` | `[TileEvent](#tileevent)` | Fired when a tile is requested and starts loading. | | `tileerror` | `[TileErrorEvent](#tileerrorevent)` | Fired when there is an error loading a tile. | | `tileload` | `[TileEvent](#tileevent)` | Fired when a tile loads. | | `load` | `[Event](#event)` | Fired when the grid layer loaded all visible tiles. | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `setParams(<Object> *params*, <Boolean> *noRedraw?*)` | `this` | Merges an object with the new parameters and re-requests tiles on the current screen (unless `noRedraw` was set to true). | Methods inherited from [TileLayer](#tilelayer) | Method | Returns | Description | | --- | --- | --- | | `setUrl(<String> *url*, <Boolean> *noRedraw?*)` | `this` | Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`). If the URL does not change, the layer will not be redrawn unless the noRedraw parameter is set to false. | | `createTile(<Object> *coords*, <Function> *done?*)` | `HTMLElement` | Called only internally, overrides GridLayer's [`createTile()`](#gridlayer-createtile) to return an `<img>` HTML element with the appropriate image URL given `coords`. The `done` callback is called when the tile has been loaded. | Methods inherited from [GridLayer](#gridlayer) | Method | Returns | Description | | --- | --- | --- | | `bringToFront()` | `this` | Brings the tile layer to the top of all tile layers. | | `bringToBack()` | `this` | Brings the tile layer to the bottom of all tile layers. | | `getContainer()` | `HTMLElement` | Returns the HTML element that contains the tiles for this layer. | | `setOpacity(<Number> *opacity*)` | `this` | Changes the [opacity](#gridlayer-opacity) of the grid layer. | | `setZIndex(<Number> *zIndex*)` | `this` | Changes the [zIndex](#gridlayer-zindex) of the grid layer. | | `isLoading()` | `Boolean` | Returns `true` if any tile in the grid layer has not finished loading. | | `redraw()` | `this` | Causes the layer to clear all the tiles and request them again. | | `getTileSize()` | `[Point](#point)` | Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | ImageOverlay ------------ Used to load and display a single image over specific bounds of the map. Extends [`Layer`](#layer). ### Usage example ``` var imageUrl = 'https://maps.lib.utexas.edu/maps/historical/newark_nj_1922.jpg', imageBounds = [[40.712216, -74.22655], [40.773941, -74.12544]]; L.imageOverlay(imageUrl, imageBounds).addTo(map); ``` ### Creation | Factory | Description | | --- | --- | | `L.imageOverlay(<String> *imageUrl*, <[LatLngBounds](#latlngbounds)> *bounds*, <[ImageOverlay options](#imageoverlay-option)> *options?*)` | Instantiates an image overlay object given the URL of the image and the geographical bounds it is tied to. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `opacity` | `Number` | `1.0` | The opacity of the image overlay. | | `alt` | `String` | `''` | Text for the `alt` attribute of the image (useful for accessibility). | | `interactive` | `Boolean` | `false` | If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered. | | `crossOrigin` | `Boolean|String` | `false` | Whether the crossOrigin attribute will be added to the image. If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. | | `errorOverlayUrl` | `String` | `''` | URL to the overlay image to show in place of the overlay that failed to load. | | `zIndex` | `Number` | `1` | The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer. | | `className` | `String` | `''` | A custom class name to assign to the image. Empty by default. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this layer will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events | Event | Data | Description | | --- | --- | --- | | `load` | `[Event](#event)` | Fired when the ImageOverlay layer has loaded its image | | `error` | `[Event](#event)` | Fired when the ImageOverlay layer fails to load its image | Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `setOpacity(<Number> *opacity*)` | `this` | Sets the opacity of the overlay. | | `bringToFront()` | `this` | Brings the layer to the top of all overlays. | | `bringToBack()` | `this` | Brings the layer to the bottom of all overlays. | | `setUrl(<String> *url*)` | `this` | Changes the URL of the image. | | `setBounds(<[LatLngBounds](#latlngbounds)> *bounds*)` | `this` | Update the bounds that this ImageOverlay covers | | `setZIndex(<Number> *value*)` | `this` | Changes the [zIndex](#imageoverlay-zindex) of the image overlay. | | `getBounds()` | `[LatLngBounds](#latlngbounds)` | Get the bounds that this ImageOverlay covers | | `getElement()` | `HTMLElement` | Returns the instance of [`HTMLImageElement`](https://developer.mozilla.org/docs/Web/API/HTMLImageElement) used by this overlay. | | `getCenter()` | `[LatLng](#latlng)` | Returns the center of the ImageOverlay. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | VideoOverlay ------------ Used to load and display a video player over specific bounds of the map. Extends [`ImageOverlay`](#imageoverlay). A video overlay uses the [`<video>`](https://developer.mozilla.org/docs/Web/HTML/Element/video) HTML5 element. ### Usage example ``` var videoUrl = 'https://www.mapbox.com/bites/00188/patricia_nasa.webm', videoBounds = [[ 32, -130], [ 13, -100]]; L.videoOverlay(videoUrl, videoBounds ).addTo(map); ``` ### Creation | Factory | Description | | --- | --- | | `L.videoOverlay(<String|Array|HTMLVideoElement> *video*, <[LatLngBounds](#latlngbounds)> *bounds*, <[VideoOverlay options](#videooverlay-option)> *options?*)` | Instantiates an image overlay object given the URL of the video (or array of URLs, or even a video element) and the geographical bounds it is tied to. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `autoplay` | `Boolean` | `true` | Whether the video starts playing automatically when loaded. On some browsers autoplay will only work with `muted: true` | | `loop` | `Boolean` | `true` | Whether the video will loop back to the beginning when played. | | `keepAspectRatio` | `Boolean` | `true` | Whether the video will save aspect ratio after the projection. Relevant for supported browsers. See [browser compatibility](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) | | `muted` | `Boolean` | `false` | Whether the video starts on mute when loaded. | | `playsInline` | `Boolean` | `true` | Mobile browsers will play the video right where it is instead of open it up in fullscreen mode. | Options inherited from [ImageOverlay](#imageoverlay) | Option | Type | Default | Description | | --- | --- | --- | --- | | `opacity` | `Number` | `1.0` | The opacity of the image overlay. | | `alt` | `String` | `''` | Text for the `alt` attribute of the image (useful for accessibility). | | `interactive` | `Boolean` | `false` | If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered. | | `crossOrigin` | `Boolean|String` | `false` | Whether the crossOrigin attribute will be added to the image. If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. | | `errorOverlayUrl` | `String` | `''` | URL to the overlay image to show in place of the overlay that failed to load. | | `zIndex` | `Number` | `1` | The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer. | | `className` | `String` | `''` | A custom class name to assign to the image. Empty by default. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this layer will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events | Event | Data | Description | | --- | --- | --- | | `load` | `[Event](#event)` | Fired when the video has finished loading the first frame | Events inherited from [ImageOverlay](#imageoverlay) | Event | Data | Description | | --- | --- | --- | | `error` | `[Event](#event)` | Fired when the ImageOverlay layer fails to load its image | Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `getElement()` | `HTMLVideoElement` | Returns the instance of [`HTMLVideoElement`](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement) used by this overlay. | Methods inherited from [ImageOverlay](#imageoverlay) | Method | Returns | Description | | --- | --- | --- | | `setOpacity(<Number> *opacity*)` | `this` | Sets the opacity of the overlay. | | `bringToFront()` | `this` | Brings the layer to the top of all overlays. | | `bringToBack()` | `this` | Brings the layer to the bottom of all overlays. | | `setUrl(<String> *url*)` | `this` | Changes the URL of the image. | | `setBounds(<[LatLngBounds](#latlngbounds)> *bounds*)` | `this` | Update the bounds that this ImageOverlay covers | | `setZIndex(<Number> *value*)` | `this` | Changes the [zIndex](#imageoverlay-zindex) of the image overlay. | | `getBounds()` | `[LatLngBounds](#latlngbounds)` | Get the bounds that this ImageOverlay covers | | `getCenter()` | `[LatLng](#latlng)` | Returns the center of the ImageOverlay. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | SVGOverlay ---------- Used to load, display and provide DOM access to an SVG file over specific bounds of the map. Extends [`ImageOverlay`](#imageoverlay). An SVG overlay uses the [`<svg>`](https://developer.mozilla.org/docs/Web/SVG/Element/svg) element. ### Usage example ``` var svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svgElement.setAttribute('xmlns', "http://www.w3.org/2000/svg"); svgElement.setAttribute('viewBox', "0 0 200 200"); svgElement.innerHTML = '<rect width="200" height="200"/><rect x="75" y="23" width="50" height="50" style="fill:red"/><rect x="75" y="123" width="50" height="50" style="fill:#0013ff"/>'; var svgElementBounds = [ [ 32, -130 ], [ 13, -100 ] ]; L.svgOverlay(svgElement, svgElementBounds).addTo(map); ``` ### Creation | Factory | Description | | --- | --- | | `L.svgOverlay(<String|SVGElement> *svg*, <[LatLngBounds](#latlngbounds)> *bounds*, <SVGOverlay options> *options?*)` | Instantiates an image overlay object given an SVG element and the geographical bounds it is tied to. A viewBox attribute is required on the SVG element to zoom in and out properly. | ### Options Options inherited from [ImageOverlay](#imageoverlay) | Option | Type | Default | Description | | --- | --- | --- | --- | | `opacity` | `Number` | `1.0` | The opacity of the image overlay. | | `alt` | `String` | `''` | Text for the `alt` attribute of the image (useful for accessibility). | | `interactive` | `Boolean` | `false` | If `true`, the image overlay will emit [mouse events](#interactive-layer) when clicked or hovered. | | `crossOrigin` | `Boolean|String` | `false` | Whether the crossOrigin attribute will be added to the image. If a String is provided, the image will have its crossOrigin attribute set to the String provided. This is needed if you want to access image pixel data. Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. | | `errorOverlayUrl` | `String` | `''` | URL to the overlay image to show in place of the overlay that failed to load. | | `zIndex` | `Number` | `1` | The explicit [zIndex](https://developer.mozilla.org/docs/Web/CSS/CSS_Positioning/Understanding_z_index) of the overlay layer. | | `className` | `String` | `''` | A custom class name to assign to the image. Empty by default. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this layer will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events Events inherited from [ImageOverlay](#imageoverlay) | Event | Data | Description | | --- | --- | --- | | `load` | `[Event](#event)` | Fired when the ImageOverlay layer has loaded its image | | `error` | `[Event](#event)` | Fired when the ImageOverlay layer fails to load its image | Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `getElement()` | `SVGElement` | Returns the instance of [`SVGElement`](https://developer.mozilla.org/docs/Web/API/SVGElement) used by this overlay. | Methods inherited from [ImageOverlay](#imageoverlay) | Method | Returns | Description | | --- | --- | --- | | `setOpacity(<Number> *opacity*)` | `this` | Sets the opacity of the overlay. | | `bringToFront()` | `this` | Brings the layer to the top of all overlays. | | `bringToBack()` | `this` | Brings the layer to the bottom of all overlays. | | `setUrl(<String> *url*)` | `this` | Changes the URL of the image. | | `setBounds(<[LatLngBounds](#latlngbounds)> *bounds*)` | `this` | Update the bounds that this ImageOverlay covers | | `setZIndex(<Number> *value*)` | `this` | Changes the [zIndex](#imageoverlay-zindex) of the image overlay. | | `getBounds()` | `[LatLngBounds](#latlngbounds)` | Get the bounds that this ImageOverlay covers | | `getCenter()` | `[LatLng](#latlng)` | Returns the center of the ImageOverlay. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Path ---- An abstract class that contains options and constants shared between vector overlays (Polygon, Polyline, Circle). Do not use it directly. Extends [`Layer`](#layer). ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `stroke` | `Boolean` | `true` | Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles. | | `color` | `String` | `'#3388ff'` | Stroke color | | `weight` | `Number` | `3` | Stroke width in pixels | | `opacity` | `Number` | `1.0` | Stroke opacity | | `lineCap` | `String` | `'round'` | A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke. | | `lineJoin` | `String` | `'round'` | A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke. | | `dashArray` | `String` | `null` | A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `dashOffset` | `String` | `null` | A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `fill` | `Boolean` | `depends` | Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles. | | `fillColor` | `String` | `*` | Fill color. Defaults to the value of the [`color`](#path-color) option | | `fillOpacity` | `Number` | `0.2` | Fill opacity. | | `fillRule` | `String` | `'evenodd'` | A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined. | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this path will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | | `renderer` | `[Renderer](#renderer)` | | Use this specific instance of [`Renderer`](#renderer) for this path. Takes precedence over the map's [default renderer](#map-renderer). | | `className` | `String` | `null` | Custom class name set on an element. Only for SVG renderer. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `true` | If `false`, the layer will not emit mouse events and will act as a part of the underlying map. | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `redraw()` | `this` | Redraws the layer. Sometimes useful after you changed the coordinates that the path uses. | | `setStyle(<[Path options](#path-option)> *style*)` | `this` | Changes the appearance of a Path based on the options in the [`Path options`](#path-option) object. | | `bringToFront()` | `this` | Brings the layer to the top of all path layers. | | `bringToBack()` | `this` | Brings the layer to the bottom of all path layers. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Polyline -------- A class for drawing polyline overlays on a map. Extends [`Path`](#path). ### Usage example ``` // create a red polyline from an array of LatLng points var latlngs = [ [45.51, -122.68], [37.77, -122.43], [34.04, -118.2] ]; var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map); // zoom the map to the polyline map.fitBounds(polyline.getBounds()); ``` You can also pass a multi-dimensional array to represent a `MultiPolyline` shape: ``` // create a red polyline from an array of arrays of LatLng points var latlngs = [ [[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]], [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]] ]; ``` ### Creation | Factory | Description | | --- | --- | | `L.polyline(<LatLng[]> *latlngs*, <[Polyline options](#polyline-option)> *options?*)` | Instantiates a polyline object given an array of geographical points and optionally an options object. You can create a [`Polyline`](#polyline) object with multiple separate lines (`MultiPolyline`) by passing an array of arrays of geographic points. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `smoothFactor` | `Number` | `1.0` | How much to simplify the polyline on each zoom level. More means better performance and smoother look, and less means more accurate representation. | | `noClip` | `Boolean` | `false` | Disable polyline clipping. | Options inherited from [Path](#path) | Option | Type | Default | Description | | --- | --- | --- | --- | | `stroke` | `Boolean` | `true` | Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles. | | `color` | `String` | `'#3388ff'` | Stroke color | | `weight` | `Number` | `3` | Stroke width in pixels | | `opacity` | `Number` | `1.0` | Stroke opacity | | `lineCap` | `String` | `'round'` | A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke. | | `lineJoin` | `String` | `'round'` | A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke. | | `dashArray` | `String` | `null` | A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `dashOffset` | `String` | `null` | A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `fill` | `Boolean` | `depends` | Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles. | | `fillColor` | `String` | `*` | Fill color. Defaults to the value of the [`color`](#path-color) option | | `fillOpacity` | `Number` | `0.2` | Fill opacity. | | `fillRule` | `String` | `'evenodd'` | A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined. | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this path will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | | `renderer` | `[Renderer](#renderer)` | | Use this specific instance of [`Renderer`](#renderer) for this path. Takes precedence over the map's [default renderer](#map-renderer). | | `className` | `String` | `null` | Custom class name set on an element. Only for SVG renderer. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `true` | If `false`, the layer will not emit mouse events and will act as a part of the underlying map. | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `toGeoJSON(<Number|false> *precision?*)` | `Object` | Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` Feature). | | `getLatLngs()` | `LatLng[]` | Returns an array of the points in the path, or nested arrays of points in case of multi-polyline. | | `setLatLngs(<LatLng[]> *latlngs*)` | `this` | Replaces all the points in the polyline with the given array of geographical points. | | `isEmpty()` | `Boolean` | Returns `true` if the Polyline has no LatLngs. | | `closestLayerPoint(<[Point](#point)> *p*)` | `[Point](#point)` | Returns the point closest to `p` on the Polyline. | | `getCenter()` | `[LatLng](#latlng)` | Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline. | | `getBounds()` | `[LatLngBounds](#latlngbounds)` | Returns the [`LatLngBounds`](#latlngbounds) of the path. | | `addLatLng(<[LatLng](#latlng)> *latlng*, <LatLng[]> *latlngs?*)` | `this` | Adds a given point to the polyline. By default, adds to the first ring of the polyline in case of a multi-polyline, but can be overridden by passing a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)). | Methods inherited from [Path](#path) | Method | Returns | Description | | --- | --- | --- | | `redraw()` | `this` | Redraws the layer. Sometimes useful after you changed the coordinates that the path uses. | | `setStyle(<[Path options](#path-option)> *style*)` | `this` | Changes the appearance of a Path based on the options in the [`Path options`](#path-option) object. | | `bringToFront()` | `this` | Brings the layer to the top of all path layers. | | `bringToBack()` | `this` | Brings the layer to the bottom of all path layers. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Polygon ------- A class for drawing polygon overlays on a map. Extends [`Polyline`](#polyline). Note that points you pass when creating a polygon shouldn't have an additional last point equal to the first one — it's better to filter out such points. ### Usage example ``` // create a red polygon from an array of LatLng points var latlngs = [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]]; var polygon = L.polygon(latlngs, {color: 'red'}).addTo(map); // zoom the map to the polygon map.fitBounds(polygon.getBounds()); ``` You can also pass an array of arrays of latlngs, with the first array representing the outer shape and the other arrays representing holes in the outer shape: ``` var latlngs = [ [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole ]; ``` Additionally, you can pass a multi-dimensional array to represent a MultiPolygon shape. ``` var latlngs = [ [ // first polygon [[37, -109.05],[41, -109.03],[41, -102.05],[37, -102.04]], // outer ring [[37.29, -108.58],[40.71, -108.58],[40.71, -102.50],[37.29, -102.50]] // hole ], [ // second polygon [[41, -111.03],[45, -111.04],[45, -104.05],[41, -104.05]] ] ]; ``` ### Creation | Factory | Description | | --- | --- | | `L.polygon(<LatLng[]> *latlngs*, <[Polyline options](#polyline-option)> *options?*)` | | ### Options Options inherited from [Polyline](#polyline) | Option | Type | Default | Description | | --- | --- | --- | --- | | `smoothFactor` | `Number` | `1.0` | How much to simplify the polyline on each zoom level. More means better performance and smoother look, and less means more accurate representation. | | `noClip` | `Boolean` | `false` | Disable polyline clipping. | Options inherited from [Path](#path) | Option | Type | Default | Description | | --- | --- | --- | --- | | `stroke` | `Boolean` | `true` | Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles. | | `color` | `String` | `'#3388ff'` | Stroke color | | `weight` | `Number` | `3` | Stroke width in pixels | | `opacity` | `Number` | `1.0` | Stroke opacity | | `lineCap` | `String` | `'round'` | A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke. | | `lineJoin` | `String` | `'round'` | A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke. | | `dashArray` | `String` | `null` | A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `dashOffset` | `String` | `null` | A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `fill` | `Boolean` | `depends` | Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles. | | `fillColor` | `String` | `*` | Fill color. Defaults to the value of the [`color`](#path-color) option | | `fillOpacity` | `Number` | `0.2` | Fill opacity. | | `fillRule` | `String` | `'evenodd'` | A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined. | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this path will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | | `renderer` | `[Renderer](#renderer)` | | Use this specific instance of [`Renderer`](#renderer) for this path. Takes precedence over the map's [default renderer](#map-renderer). | | `className` | `String` | `null` | Custom class name set on an element. Only for SVG renderer. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `true` | If `false`, the layer will not emit mouse events and will act as a part of the underlying map. | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `toGeoJSON(<Number|false> *precision?*)` | `Object` | Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON [`Polygon`](#polygon) or `MultiPolygon` Feature). | | `getCenter()` | `[LatLng](#latlng)` | Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the Polygon. | Methods inherited from [Polyline](#polyline) | Method | Returns | Description | | --- | --- | --- | | `getLatLngs()` | `LatLng[]` | Returns an array of the points in the path, or nested arrays of points in case of multi-polyline. | | `setLatLngs(<LatLng[]> *latlngs*)` | `this` | Replaces all the points in the polyline with the given array of geographical points. | | `isEmpty()` | `Boolean` | Returns `true` if the Polyline has no LatLngs. | | `closestLayerPoint(<[Point](#point)> *p*)` | `[Point](#point)` | Returns the point closest to `p` on the Polyline. | | `getBounds()` | `[LatLngBounds](#latlngbounds)` | Returns the [`LatLngBounds`](#latlngbounds) of the path. | | `addLatLng(<[LatLng](#latlng)> *latlng*, <LatLng[]> *latlngs?*)` | `this` | Adds a given point to the polyline. By default, adds to the first ring of the polyline in case of a multi-polyline, but can be overridden by passing a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)). | Methods inherited from [Path](#path) | Method | Returns | Description | | --- | --- | --- | | `redraw()` | `this` | Redraws the layer. Sometimes useful after you changed the coordinates that the path uses. | | `setStyle(<[Path options](#path-option)> *style*)` | `this` | Changes the appearance of a Path based on the options in the [`Path options`](#path-option) object. | | `bringToFront()` | `this` | Brings the layer to the top of all path layers. | | `bringToBack()` | `this` | Brings the layer to the bottom of all path layers. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Rectangle --------- A class for drawing rectangle overlays on a map. Extends [`Polygon`](#polygon). ### Usage example ``` // define rectangle geographical bounds var bounds = [[54.559322, -5.767822], [56.1210604, -3.021240]]; // create an orange rectangle L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map); // zoom the map to the rectangle bounds map.fitBounds(bounds); ``` ### Creation | Factory | Description | | --- | --- | | `L.rectangle(<[LatLngBounds](#latlngbounds)> *latLngBounds*, <[Polyline options](#polyline-option)> *options?*)` | | ### Options Options inherited from [Polyline](#polyline) | Option | Type | Default | Description | | --- | --- | --- | --- | | `smoothFactor` | `Number` | `1.0` | How much to simplify the polyline on each zoom level. More means better performance and smoother look, and less means more accurate representation. | | `noClip` | `Boolean` | `false` | Disable polyline clipping. | Options inherited from [Path](#path) | Option | Type | Default | Description | | --- | --- | --- | --- | | `stroke` | `Boolean` | `true` | Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles. | | `color` | `String` | `'#3388ff'` | Stroke color | | `weight` | `Number` | `3` | Stroke width in pixels | | `opacity` | `Number` | `1.0` | Stroke opacity | | `lineCap` | `String` | `'round'` | A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke. | | `lineJoin` | `String` | `'round'` | A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke. | | `dashArray` | `String` | `null` | A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `dashOffset` | `String` | `null` | A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `fill` | `Boolean` | `depends` | Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles. | | `fillColor` | `String` | `*` | Fill color. Defaults to the value of the [`color`](#path-color) option | | `fillOpacity` | `Number` | `0.2` | Fill opacity. | | `fillRule` | `String` | `'evenodd'` | A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined. | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this path will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | | `renderer` | `[Renderer](#renderer)` | | Use this specific instance of [`Renderer`](#renderer) for this path. Takes precedence over the map's [default renderer](#map-renderer). | | `className` | `String` | `null` | Custom class name set on an element. Only for SVG renderer. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `true` | If `false`, the layer will not emit mouse events and will act as a part of the underlying map. | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `setBounds(<[LatLngBounds](#latlngbounds)> *latLngBounds*)` | `this` | Redraws the rectangle with the passed bounds. | Methods inherited from [Polygon](#polygon) | Method | Returns | Description | | --- | --- | --- | | `toGeoJSON(<Number|false> *precision?*)` | `Object` | Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the polygon (as a GeoJSON [`Polygon`](#polygon) or `MultiPolygon` Feature). | | `getCenter()` | `[LatLng](#latlng)` | Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the Polygon. | Methods inherited from [Polyline](#polyline) | Method | Returns | Description | | --- | --- | --- | | `getLatLngs()` | `LatLng[]` | Returns an array of the points in the path, or nested arrays of points in case of multi-polyline. | | `setLatLngs(<LatLng[]> *latlngs*)` | `this` | Replaces all the points in the polyline with the given array of geographical points. | | `isEmpty()` | `Boolean` | Returns `true` if the Polyline has no LatLngs. | | `closestLayerPoint(<[Point](#point)> *p*)` | `[Point](#point)` | Returns the point closest to `p` on the Polyline. | | `getBounds()` | `[LatLngBounds](#latlngbounds)` | Returns the [`LatLngBounds`](#latlngbounds) of the path. | | `addLatLng(<[LatLng](#latlng)> *latlng*, <LatLng[]> *latlngs?*)` | `this` | Adds a given point to the polyline. By default, adds to the first ring of the polyline in case of a multi-polyline, but can be overridden by passing a specific ring as a LatLng array (that you can earlier access with [`getLatLngs`](#polyline-getlatlngs)). | Methods inherited from [Path](#path) | Method | Returns | Description | | --- | --- | --- | | `redraw()` | `this` | Redraws the layer. Sometimes useful after you changed the coordinates that the path uses. | | `setStyle(<[Path options](#path-option)> *style*)` | `this` | Changes the appearance of a Path based on the options in the [`Path options`](#path-option) object. | | `bringToFront()` | `this` | Brings the layer to the top of all path layers. | | `bringToBack()` | `this` | Brings the layer to the bottom of all path layers. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Circle ------ A class for drawing circle overlays on a map. Extends [`CircleMarker`](#circlemarker). It's an approximation and starts to diverge from a real circle closer to poles (due to projection distortion). ### Usage example ``` L.circle([50.5, 30.5], {radius: 200}).addTo(map); ``` ### Creation | Factory | Description | | --- | --- | | `L.circle(<[LatLng](#latlng)> *latlng*, <[Circle options](#circle-option)> *options?*)` | Instantiates a circle object given a geographical point, and an options object which contains the circle radius. | | `L.circle(<[LatLng](#latlng)> *latlng*, <Number> *radius*, <[Circle options](#circle-option)> *options?*)` | Obsolete way of instantiating a circle, for compatibility with 0.7.x code. Do not use in new applications or plugins. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `radius` | `Number` | | Radius of the circle, in meters. | Options inherited from [Path](#path) | Option | Type | Default | Description | | --- | --- | --- | --- | | `stroke` | `Boolean` | `true` | Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles. | | `color` | `String` | `'#3388ff'` | Stroke color | | `weight` | `Number` | `3` | Stroke width in pixels | | `opacity` | `Number` | `1.0` | Stroke opacity | | `lineCap` | `String` | `'round'` | A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke. | | `lineJoin` | `String` | `'round'` | A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke. | | `dashArray` | `String` | `null` | A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `dashOffset` | `String` | `null` | A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `fill` | `Boolean` | `depends` | Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles. | | `fillColor` | `String` | `*` | Fill color. Defaults to the value of the [`color`](#path-color) option | | `fillOpacity` | `Number` | `0.2` | Fill opacity. | | `fillRule` | `String` | `'evenodd'` | A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined. | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this path will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | | `renderer` | `[Renderer](#renderer)` | | Use this specific instance of [`Renderer`](#renderer) for this path. Takes precedence over the map's [default renderer](#map-renderer). | | `className` | `String` | `null` | Custom class name set on an element. Only for SVG renderer. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `true` | If `false`, the layer will not emit mouse events and will act as a part of the underlying map. | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events Events inherited from [CircleMarker](#circlemarker) | Event | Data | Description | | --- | --- | --- | | `move` | `[Event](#event)` | Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`. | Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `setRadius(<Number> *radius*)` | `this` | Sets the radius of a circle. Units are in meters. | | `getRadius()` | `Number` | Returns the current radius of a circle. Units are in meters. | | `getBounds()` | `[LatLngBounds](#latlngbounds)` | Returns the [`LatLngBounds`](#latlngbounds) of the path. | Methods inherited from [CircleMarker](#circlemarker) | Method | Returns | Description | | --- | --- | --- | | `toGeoJSON(<Number|false> *precision?*)` | `Object` | Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON [`Point`](#point) Feature). | | `setLatLng(<[LatLng](#latlng)> *latLng*)` | `this` | Sets the position of a circle marker to a new location. | | `getLatLng()` | `[LatLng](#latlng)` | Returns the current geographical position of the circle marker | Methods inherited from [Path](#path) | Method | Returns | Description | | --- | --- | --- | | `redraw()` | `this` | Redraws the layer. Sometimes useful after you changed the coordinates that the path uses. | | `setStyle(<[Path options](#path-option)> *style*)` | `this` | Changes the appearance of a Path based on the options in the [`Path options`](#path-option) object. | | `bringToFront()` | `this` | Brings the layer to the top of all path layers. | | `bringToBack()` | `this` | Brings the layer to the bottom of all path layers. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | CircleMarker ------------ A circle of a fixed size with radius specified in pixels. Extends [`Path`](#path). ### Creation | Factory | Description | | --- | --- | | `L.circleMarker(<[LatLng](#latlng)> *latlng*, <[CircleMarker options](#circlemarker-option)> *options?*)` | Instantiates a circle marker object given a geographical point, and an optional options object. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `radius` | `Number` | `10` | Radius of the circle marker, in pixels | Options inherited from [Path](#path) | Option | Type | Default | Description | | --- | --- | --- | --- | | `stroke` | `Boolean` | `true` | Whether to draw stroke along the path. Set it to `false` to disable borders on polygons or circles. | | `color` | `String` | `'#3388ff'` | Stroke color | | `weight` | `Number` | `3` | Stroke width in pixels | | `opacity` | `Number` | `1.0` | Stroke opacity | | `lineCap` | `String` | `'round'` | A string that defines [shape to be used at the end](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linecap) of the stroke. | | `lineJoin` | `String` | `'round'` | A string that defines [shape to be used at the corners](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-linejoin) of the stroke. | | `dashArray` | `String` | `null` | A string that defines the stroke [dash pattern](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dasharray). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `dashOffset` | `String` | `null` | A string that defines the [distance into the dash pattern to start the dash](https://developer.mozilla.org/docs/Web/SVG/Attribute/stroke-dashoffset). Doesn't work on [`Canvas`](#canvas)-powered layers in [some old browsers](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash#Browser_compatibility). | | `fill` | `Boolean` | `depends` | Whether to fill the path with color. Set it to `false` to disable filling on polygons or circles. | | `fillColor` | `String` | `*` | Fill color. Defaults to the value of the [`color`](#path-color) option | | `fillOpacity` | `Number` | `0.2` | Fill opacity. | | `fillRule` | `String` | `'evenodd'` | A string that defines [how the inside of a shape](https://developer.mozilla.org/docs/Web/SVG/Attribute/fill-rule) is determined. | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this path will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | | `renderer` | `[Renderer](#renderer)` | | Use this specific instance of [`Renderer`](#renderer) for this path. Takes precedence over the map's [default renderer](#map-renderer). | | `className` | `String` | `null` | Custom class name set on an element. Only for SVG renderer. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `true` | If `false`, the layer will not emit mouse events and will act as a part of the underlying map. | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events | Event | Data | Description | | --- | --- | --- | | `move` | `[Event](#event)` | Fired when the marker is moved via [`setLatLng`](#circlemarker-setlatlng). Old and new coordinates are included in event arguments as `oldLatLng`, `latlng`. | Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `toGeoJSON(<Number|false> *precision?*)` | `Object` | Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the circle marker (as a GeoJSON [`Point`](#point) Feature). | | `setLatLng(<[LatLng](#latlng)> *latLng*)` | `this` | Sets the position of a circle marker to a new location. | | `getLatLng()` | `[LatLng](#latlng)` | Returns the current geographical position of the circle marker | | `setRadius(<Number> *radius*)` | `this` | Sets the radius of a circle marker. Units are in pixels. | | `getRadius()` | `Number` | Returns the current radius of the circle | Methods inherited from [Path](#path) | Method | Returns | Description | | --- | --- | --- | | `redraw()` | `this` | Redraws the layer. Sometimes useful after you changed the coordinates that the path uses. | | `setStyle(<[Path options](#path-option)> *style*)` | `this` | Changes the appearance of a Path based on the options in the [`Path options`](#path-option) object. | | `bringToFront()` | `this` | Brings the layer to the top of all path layers. | | `bringToBack()` | `this` | Brings the layer to the bottom of all path layers. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | SVG --- VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility with old versions of Internet Explorer. Allows vector layers to be displayed with [SVG](https://developer.mozilla.org/docs/Web/SVG). Inherits [`Renderer`](#renderer). Due to [technical limitations](https://caniuse.com/svg), SVG is not available in all web browsers, notably Android 2.x and 3.x. Although SVG is not available on IE7 and IE8, these browsers support [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language) (a now deprecated technology), and the SVG renderer will fall back to VML in this case. ### Usage example Use SVG by default for all paths in the map: ``` var map = L.map('map', { renderer: L.svg() }); ``` Use a SVG renderer with extra padding for specific vector geometries: ``` var map = L.map('map'); var myRenderer = L.svg({ padding: 0.5 }); var line = L.polyline( coordinates, { renderer: myRenderer } ); var circle = L.circle( center, { renderer: myRenderer } ); ``` ### Creation | Factory | Description | | --- | --- | | `L.svg(<[Renderer options](#renderer-option)> *options?*)` | Creates a SVG renderer with the given options. | ### Options Options inherited from [Renderer](#renderer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `padding` | `Number` | `0.1` | How much to extend the clip area around the map view (relative to its size) e.g. 0.1 would be 10% of map view in each direction | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events Events inherited from [Renderer](#renderer) | Event | Data | Description | | --- | --- | --- | | `update` | `[Event](#event)` | Fired when the renderer updates its bounds, center and zoom, for example when its map has moved | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | ### Functions There are several static functions which can be called without instantiating L.SVG: | Function | Returns | Description | | --- | --- | --- | | `create(<String> *name*)` | `SVGElement` | Returns a instance of [SVGElement](https://developer.mozilla.org/docs/Web/API/SVGElement), corresponding to the class name passed. For example, using 'line' will return an instance of [SVGLineElement](https://developer.mozilla.org/docs/Web/API/SVGLineElement). | | `pointsToPath(<Point[]> *rings*, <Boolean> *closed*)` | `String` | Generates a SVG path string for multiple rings, with each ring turning into "M..L..L.." instructions | Canvas ------ Allows vector layers to be displayed with [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API). Inherits [`Renderer`](#renderer). Due to [technical limitations](https://caniuse.com/canvas), Canvas is not available in all web browsers, notably IE8, and overlapping geometries might not display properly in some edge cases. ### Usage example Use Canvas by default for all paths in the map: ``` var map = L.map('map', { renderer: L.canvas() }); ``` Use a Canvas renderer with extra padding for specific vector geometries: ``` var map = L.map('map'); var myRenderer = L.canvas({ padding: 0.5 }); var line = L.polyline( coordinates, { renderer: myRenderer } ); var circle = L.circle( center, { renderer: myRenderer } ); ``` ### Creation | Factory | Description | | --- | --- | | `L.canvas(<[Renderer options](#renderer-option)> *options?*)` | Creates a Canvas renderer with the given options. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `tolerance` | `Number` | `0` | How much to extend the click tolerance around a path/object on the map. | Options inherited from [Renderer](#renderer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `padding` | `Number` | `0.1` | How much to extend the clip area around the map view (relative to its size) e.g. 0.1 would be 10% of map view in each direction | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events Events inherited from [Renderer](#renderer) | Event | Data | Description | | --- | --- | --- | | `update` | `[Event](#event)` | Fired when the renderer updates its bounds, center and zoom, for example when its map has moved | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | LayerGroup ---------- Used to group several layers and handle them as one. If you add it to the map, any layers added or removed from the group will be added/removed on the map as well. Extends [`Layer`](#layer). ### Usage example ``` L.layerGroup([marker1, marker2]) .addLayer(polyline) .addTo(map); ``` ### Creation | Factory | Description | | --- | --- | | `L.layerGroup(<Layer[]> *layers?*, <Object> *options?*)` | Create a layer group, optionally given an initial set of layers and an `options` object. | ### Options Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `true` | If `false`, the layer will not emit mouse events and will act as a part of the underlying map. | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this layer will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `toGeoJSON(<Number|false> *precision?*)` | `Object` | Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`). | | `addLayer(<[Layer](#layer)> *layer*)` | `this` | Adds the given layer to the group. | | `removeLayer(<[Layer](#layer)> *layer*)` | `this` | Removes the given layer from the group. | | `removeLayer(<Number> *id*)` | `this` | Removes the layer with the given internal ID from the group. | | `hasLayer(<[Layer](#layer)> *layer*)` | `Boolean` | Returns `true` if the given layer is currently added to the group. | | `hasLayer(<Number> *id*)` | `Boolean` | Returns `true` if the given internal ID is currently added to the group. | | `clearLayers()` | `this` | Removes all the layers from the group. | | `invoke(<String> *methodName*, *…*)` | `this` | Calls `methodName` on every layer contained in this group, passing any additional parameters. Has no effect if the layers contained do not implement `methodName`. | | `eachLayer(<Function> *fn*, <Object> *context?*)` | `this` | Iterates over the layers of the group, optionally specifying context of the iterator function. ``` group.eachLayer(function (layer) { layer.bindPopup('Hello'); }); ``` | | `getLayer(<Number> *id*)` | `[Layer](#layer)` | Returns the layer with the given internal ID. | | `getLayers()` | `Layer[]` | Returns an array of all the layers added to the group. | | `setZIndex(<Number> *zIndex*)` | `this` | Calls `setZIndex` on every layer contained in this group, passing the z-index. | | `getLayerId(<[Layer](#layer)> *layer*)` | `Number` | Returns the internal ID for a layer | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | FeatureGroup ------------ Extended [`LayerGroup`](#layergroup) that makes it easier to do the same thing to all its member layers: * [`bindPopup`](#layer-bindpopup) binds a popup to all of the layers at once (likewise with [`bindTooltip`](#layer-bindtooltip)) * Events are propagated to the [`FeatureGroup`](#featuregroup), so if the group has an event handler, it will handle events from any of the layers. This includes mouse events and custom events. * Has `layeradd` and `layerremove` events ### Usage example ``` L.featureGroup([marker1, marker2, polyline]) .bindPopup('Hello world!') .on('click', function() { alert('Clicked on a member of the group!'); }) .addTo(map); ``` ### Creation | Factory | Description | | --- | --- | | `L.featureGroup(<Layer[]> *layers?*, <Object> *options?*)` | Create a feature group, optionally given an initial set of layers and an `options` object. | ### Options Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `true` | If `false`, the layer will not emit mouse events and will act as a part of the underlying map. | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this layer will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events | Event | Data | Description | | --- | --- | --- | | `layeradd` | `[LayerEvent](#layerevent)` | Fired when a layer is added to this [`FeatureGroup`](#featuregroup) | | `layerremove` | `[LayerEvent](#layerevent)` | Fired when a layer is removed from this [`FeatureGroup`](#featuregroup) | Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `setStyle(<[Path options](#path-option)> *style*)` | `this` | Sets the given path options to each layer of the group that has a `setStyle` method. | | `bringToFront()` | `this` | Brings the layer group to the top of all other layers | | `bringToBack()` | `this` | Brings the layer group to the back of all other layers | | `getBounds()` | `[LatLngBounds](#latlngbounds)` | Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children). | Methods inherited from [LayerGroup](#layergroup) | Method | Returns | Description | | --- | --- | --- | | `toGeoJSON(<Number|false> *precision?*)` | `Object` | Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`). | | `addLayer(<[Layer](#layer)> *layer*)` | `this` | Adds the given layer to the group. | | `removeLayer(<[Layer](#layer)> *layer*)` | `this` | Removes the given layer from the group. | | `removeLayer(<Number> *id*)` | `this` | Removes the layer with the given internal ID from the group. | | `hasLayer(<[Layer](#layer)> *layer*)` | `Boolean` | Returns `true` if the given layer is currently added to the group. | | `hasLayer(<Number> *id*)` | `Boolean` | Returns `true` if the given internal ID is currently added to the group. | | `clearLayers()` | `this` | Removes all the layers from the group. | | `invoke(<String> *methodName*, *…*)` | `this` | Calls `methodName` on every layer contained in this group, passing any additional parameters. Has no effect if the layers contained do not implement `methodName`. | | `eachLayer(<Function> *fn*, <Object> *context?*)` | `this` | Iterates over the layers of the group, optionally specifying context of the iterator function. ``` group.eachLayer(function (layer) { layer.bindPopup('Hello'); }); ``` | | `getLayer(<Number> *id*)` | `[Layer](#layer)` | Returns the layer with the given internal ID. | | `getLayers()` | `Layer[]` | Returns an array of all the layers added to the group. | | `setZIndex(<Number> *zIndex*)` | `this` | Calls `setZIndex` on every layer contained in this group, passing the z-index. | | `getLayerId(<[Layer](#layer)> *layer*)` | `Number` | Returns the internal ID for a layer | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | GeoJSON ------- Represents a GeoJSON object or an array of GeoJSON objects. Allows you to parse GeoJSON data and display it on the map. Extends [`FeatureGroup`](#featuregroup). ### Usage example ``` L.geoJSON(data, { style: function (feature) { return {color: feature.properties.color}; } }).bindPopup(function (layer) { return layer.feature.properties.description; }).addTo(map); ``` ### Creation | Factory | Description | | --- | --- | | `L.geoJSON(<Object> *geojson?*, <[GeoJSON options](#geojson-option)> *options?*)` | Creates a GeoJSON layer. Optionally accepts an object in [GeoJSON format](https://tools.ietf.org/html/rfc7946) to display on the map (you can alternatively add it later with `addData` method) and an `options` object. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `pointToLayer` | `Function` | `*` | A `Function` defining how GeoJSON points spawn Leaflet layers. It is internally called when data is added, passing the GeoJSON point feature and its [`LatLng`](#latlng). The default is to spawn a default [`Marker`](#marker): ``` function(geoJsonPoint, latlng) { return L.marker(latlng); } ``` | | `style` | `Function` | `*` | A `Function` defining the [`Path options`](#path-option) for styling GeoJSON lines and polygons, called internally when data is added. The default value is to not override any defaults: ``` function (geoJsonFeature) { return {} } ``` | | `onEachFeature` | `Function` | `*` | A `Function` that will be called once for each created `Feature`, after it has been created and styled. Useful for attaching events and popups to features. The default is to do nothing with the newly created layers: ``` function (feature, layer) {} ``` | | `filter` | `Function` | `*` | A `Function` that will be used to decide whether to include a feature or not. The default is to include all features: ``` function (geoJsonFeature) { return true; } ``` Note: dynamically changing the `filter` option will have effect only on newly added data. It will *not* re-evaluate already included features. | | `coordsToLatLng` | `Function` | `*` | A `Function` that will be used for converting GeoJSON coordinates to [`LatLng`](#latlng)s. The default is the `coordsToLatLng` static method. | | `markersInheritOptions` | `Boolean` | `false` | Whether default Markers for "Point" type Features inherit from group options. | Options inherited from [Interactive layer](#interactive-layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `true` | If `false`, the layer will not emit mouse events and will act as a part of the underlying map. | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this layer will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events Events inherited from [FeatureGroup](#featuregroup) | Event | Data | Description | | --- | --- | --- | | `layeradd` | `[LayerEvent](#layerevent)` | Fired when a layer is added to this [`FeatureGroup`](#featuregroup) | | `layerremove` | `[LayerEvent](#layerevent)` | Fired when a layer is removed from this [`FeatureGroup`](#featuregroup) | Mouse events inherited from [Interactive layer](#interactive-layer) | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `addData(*data*)` | `this` | Adds a GeoJSON object to the layer. | | `resetStyle(*layer?*)` | `this` | Resets the given vector layer's style to the original GeoJSON style, useful for resetting style after hover events. If `layer` is omitted, the style of all features in the current layer is reset. | | `setStyle(*style*)` | `this` | Changes styles of GeoJSON vector layers with the given style function. | Methods inherited from [FeatureGroup](#featuregroup) | Method | Returns | Description | | --- | --- | --- | | `bringToFront()` | `this` | Brings the layer group to the top of all other layers | | `bringToBack()` | `this` | Brings the layer group to the back of all other layers | | `getBounds()` | `[LatLngBounds](#latlngbounds)` | Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children). | Methods inherited from [LayerGroup](#layergroup) | Method | Returns | Description | | --- | --- | --- | | `toGeoJSON(<Number|false> *precision?*)` | `Object` | Coordinates values are rounded with [`formatNum`](#util-formatnum) function with given `precision`. Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) representation of the layer group (as a GeoJSON `FeatureCollection`, `GeometryCollection`, or `MultiPoint`). | | `addLayer(<[Layer](#layer)> *layer*)` | `this` | Adds the given layer to the group. | | `removeLayer(<[Layer](#layer)> *layer*)` | `this` | Removes the given layer from the group. | | `removeLayer(<Number> *id*)` | `this` | Removes the layer with the given internal ID from the group. | | `hasLayer(<[Layer](#layer)> *layer*)` | `Boolean` | Returns `true` if the given layer is currently added to the group. | | `hasLayer(<Number> *id*)` | `Boolean` | Returns `true` if the given internal ID is currently added to the group. | | `clearLayers()` | `this` | Removes all the layers from the group. | | `invoke(<String> *methodName*, *…*)` | `this` | Calls `methodName` on every layer contained in this group, passing any additional parameters. Has no effect if the layers contained do not implement `methodName`. | | `eachLayer(<Function> *fn*, <Object> *context?*)` | `this` | Iterates over the layers of the group, optionally specifying context of the iterator function. ``` group.eachLayer(function (layer) { layer.bindPopup('Hello'); }); ``` | | `getLayer(<Number> *id*)` | `[Layer](#layer)` | Returns the layer with the given internal ID. | | `getLayers()` | `Layer[]` | Returns an array of all the layers added to the group. | | `setZIndex(<Number> *zIndex*)` | `this` | Calls `setZIndex` on every layer contained in this group, passing the z-index. | | `getLayerId(<[Layer](#layer)> *layer*)` | `Number` | Returns the internal ID for a layer | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | ### Functions There are several static functions which can be called without instantiating L.GeoJSON: | Function | Returns | Description | | --- | --- | --- | | `geometryToLayer(<Object> *featureData*, <[GeoJSON options](#geojson-option)> *options?*)` | `[Layer](#layer)` | Creates a [`Layer`](#layer) from a given GeoJSON feature. Can use a custom [`pointToLayer`](#geojson-pointtolayer) and/or [`coordsToLatLng`](#geojson-coordstolatlng) functions if provided as options. | | `coordsToLatLng(<Array> *coords*)` | `[LatLng](#latlng)` | Creates a [`LatLng`](#latlng) object from an array of 2 numbers (longitude, latitude) or 3 numbers (longitude, latitude, altitude) used in GeoJSON for points. | | `coordsToLatLngs(<Array> *coords*, <Number> *levelsDeep?*, <Function> *coordsToLatLng?*)` | `Array` | Creates a multidimensional array of [`LatLng`](#latlng)s from a GeoJSON coordinates array. `levelsDeep` specifies the nesting level (0 is for an array of points, 1 for an array of arrays of points, etc., 0 by default). Can use a custom [`coordsToLatLng`](#geojson-coordstolatlng) function. | | `latLngToCoords(<[LatLng](#latlng)> *latlng*, <Number|false> *precision?*)` | `Array` | Reverse of [`coordsToLatLng`](#geojson-coordstolatlng) Coordinates values are rounded with [`formatNum`](#util-formatnum) function. | | `latLngsToCoords(<Array> *latlngs*, <Number> *levelsDeep?*, <Boolean> *closed?*, <Number|false> *precision?*)` | `Array` | Reverse of [`coordsToLatLngs`](#geojson-coordstolatlngs) `closed` determines whether the first point should be appended to the end of the array to close the feature, only used when `levelsDeep` is 0. False by default. Coordinates values are rounded with [`formatNum`](#util-formatnum) function. | | `asFeature(<Object> *geojson*)` | `Object` | Normalize GeoJSON geometries/features into GeoJSON features. | GridLayer --------- Generic class for handling a tiled grid of HTML elements. This is the base class for all tile layers and replaces `TileLayer.Canvas`. GridLayer can be extended to create a tiled grid of HTML elements like `<canvas>`, `<img>` or `<div>`. GridLayer will handle creating and animating these DOM elements for you. ### Usage example #### Synchronous usage To create a custom layer, extend GridLayer and implement the `createTile()` method, which will be passed a [`Point`](#point) object with the `x`, `y`, and `z` (zoom level) coordinates to draw your tile. ``` var CanvasLayer = L.GridLayer.extend({ createTile: function(coords){ // create a <canvas> element for drawing var tile = L.DomUtil.create('canvas', 'leaflet-tile'); // setup tile width and height according to the options var size = this.getTileSize(); tile.width = size.x; tile.height = size.y; // get a canvas context and draw something on it using coords.x, coords.y and coords.z var ctx = tile.getContext('2d'); // return the tile so it can be rendered on screen return tile; } }); ``` #### Asynchronous usage Tile creation can also be asynchronous, this is useful when using a third-party drawing library. Once the tile is finished drawing it can be passed to the `done()` callback. ``` var CanvasLayer = L.GridLayer.extend({ createTile: function(coords, done){ var error; // create a <canvas> element for drawing var tile = L.DomUtil.create('canvas', 'leaflet-tile'); // setup tile width and height according to the options var size = this.getTileSize(); tile.width = size.x; tile.height = size.y; // draw something asynchronously and pass the tile to the done() callback setTimeout(function() { done(error, tile); }, 1000); return tile; } }); ``` ### Creation | Factory | Description | | --- | --- | | `L.gridLayer(<[GridLayer options](#gridlayer-option)> *options?*)` | Creates a new instance of GridLayer with the supplied options. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `tileSize` | `Number|Point` | `256` | Width and height of tiles in the grid. Use a number if width and height are equal, or `L.point(width, height)` otherwise. | | `opacity` | `Number` | `1.0` | Opacity of the tiles. Can be used in the `createTile()` function. | | `updateWhenIdle` | `Boolean` | `(depends)` | Load new tiles only when panning ends. `true` by default on mobile browsers, in order to avoid too many requests and keep smooth navigation. `false` otherwise in order to display new tiles *during* panning, since it is easy to pan outside the [`keepBuffer`](#gridlayer-keepbuffer) option in desktop browsers. | | `updateWhenZooming` | `Boolean` | `true` | By default, a smooth zoom animation (during a [touch zoom](#map-touchzoom) or a [`flyTo()`](#map-flyto)) will update grid layers every integer zoom level. Setting this option to `false` will update the grid layer only when the smooth animation ends. | | `updateInterval` | `Number` | `200` | Tiles will not update more than once every `updateInterval` milliseconds when panning. | | `zIndex` | `Number` | `1` | The explicit zIndex of the tile layer. | | `bounds` | `[LatLngBounds](#latlngbounds)` | `undefined` | If set, tiles will only be loaded inside the set [`LatLngBounds`](#latlngbounds). | | `minZoom` | `Number` | `0` | The minimum zoom level down to which this layer will be displayed (inclusive). | | `maxZoom` | `Number` | `undefined` | The maximum zoom level up to which this layer will be displayed (inclusive). | | `maxNativeZoom` | `Number` | `undefined` | Maximum zoom number the tile source has available. If it is specified, the tiles on all zoom levels higher than `maxNativeZoom` will be loaded from `maxNativeZoom` level and auto-scaled. | | `minNativeZoom` | `Number` | `undefined` | Minimum zoom number the tile source has available. If it is specified, the tiles on all zoom levels lower than `minNativeZoom` will be loaded from `minNativeZoom` level and auto-scaled. | | `noWrap` | `Boolean` | `false` | Whether the layer is wrapped around the antimeridian. If `true`, the GridLayer will only be displayed once at low zoom levels. Has no effect when the [map CRS](#map-crs) doesn't wrap around. Can be used in combination with [`bounds`](#gridlayer-bounds) to prevent requesting tiles outside the CRS limits. | | `pane` | `String` | `'tilePane'` | `Map pane` where the grid layer will be added. | | `className` | `String` | `''` | A custom class name to assign to the tile layer. Empty by default. | | `keepBuffer` | `Number` | `2` | When panning the map, keep this many rows and columns of tiles before unloading them. | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events | Event | Data | Description | | --- | --- | --- | | `loading` | `[Event](#event)` | Fired when the grid layer starts loading tiles. | | `tileunload` | `[TileEvent](#tileevent)` | Fired when a tile is removed (e.g. when a tile goes off the screen). | | `tileloadstart` | `[TileEvent](#tileevent)` | Fired when a tile is requested and starts loading. | | `tileerror` | `[TileErrorEvent](#tileerrorevent)` | Fired when there is an error loading a tile. | | `tileload` | `[TileEvent](#tileevent)` | Fired when a tile loads. | | `load` | `[Event](#event)` | Fired when the grid layer loaded all visible tiles. | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `bringToFront()` | `this` | Brings the tile layer to the top of all tile layers. | | `bringToBack()` | `this` | Brings the tile layer to the bottom of all tile layers. | | `getContainer()` | `HTMLElement` | Returns the HTML element that contains the tiles for this layer. | | `setOpacity(<Number> *opacity*)` | `this` | Changes the [opacity](#gridlayer-opacity) of the grid layer. | | `setZIndex(<Number> *zIndex*)` | `this` | Changes the [zIndex](#gridlayer-zindex) of the grid layer. | | `isLoading()` | `Boolean` | Returns `true` if any tile in the grid layer has not finished loading. | | `redraw()` | `this` | Causes the layer to clear all the tiles and request them again. | | `getTileSize()` | `[Point](#point)` | Normalizes the [tileSize option](#gridlayer-tilesize) into a point. Used by the `createTile()` method. | #### Extension methods Layers extending [`GridLayer`](#gridlayer) shall reimplement the following method. | Method | Returns | Description | | --- | --- | --- | | `createTile(<Object> *coords*, <Function> *done?*)` | `HTMLElement` | Called only internally, must be overridden by classes extending [`GridLayer`](#gridlayer). Returns the `HTMLElement` corresponding to the given `coords`. If the `done` callback is specified, it must be called when the tile has finished loading and drawing. | Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | LatLng ------ Represents a geographical point with a certain latitude and longitude. ### Usage example ``` var latlng = L.latLng(50.5, 30.5); ``` All Leaflet methods that accept LatLng objects also accept them in a simple Array form and simple object form (unless noted otherwise), so these lines are equivalent: ``` map.panTo([50, 30]); map.panTo({lon: 30, lat: 50}); map.panTo({lat: 50, lng: 30}); map.panTo(L.latLng(50, 30)); ``` Note that [`LatLng`](#latlng) does not inherit from Leaflet's [`Class`](#class) object, which means new classes can't inherit from it, and new methods can't be added to it with the `include` function. ### Creation | Factory | Description | | --- | --- | | `L.latLng(<Number> *latitude*, <Number> *longitude*, <Number> *altitude?*)` | Creates an object representing a geographical point with the given latitude and longitude (and optionally altitude). | | `L.latLng(<Array> *coords*)` | Expects an array of the form `[Number, Number]` or `[Number, Number, Number]` instead. | | `L.latLng(<Object> *coords*)` | Expects an plain object of the form `{lat: Number, lng: Number}` or `{lat: Number, lng: Number, alt: Number}` instead. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `equals(<[LatLng](#latlng)> *otherLatLng*, <Number> *maxMargin?*)` | `Boolean` | Returns `true` if the given [`LatLng`](#latlng) point is at the same position (within a small margin of error). The margin of error can be overridden by setting `maxMargin` to a small number. | | `toString()` | `String` | Returns a string representation of the point (for debugging purposes). | | `distanceTo(<[LatLng](#latlng)> *otherLatLng*)` | `Number` | Returns the distance (in meters) to the given [`LatLng`](#latlng) calculated using the [Spherical Law of Cosines](https://en.wikipedia.org/wiki/Spherical_law_of_cosines). | | `wrap()` | `[LatLng](#latlng)` | Returns a new [`LatLng`](#latlng) object with the longitude wrapped so it's always between -180 and +180 degrees. | | `toBounds(<Number> *sizeInMeters*)` | `[LatLngBounds](#latlngbounds)` | Returns a new [`LatLngBounds`](#latlngbounds) object in which each boundary is `sizeInMeters/2` meters apart from the [`LatLng`](#latlng). | ### Properties | Property | Type | Description | | --- | --- | --- | | `lat` | `Number` | Latitude in degrees | | `lng` | `Number` | Longitude in degrees | | `alt` | `Number` | Altitude in meters (optional) | LatLngBounds ------------ Represents a rectangular geographical area on a map. ### Usage example ``` var corner1 = L.latLng(40.712, -74.227), corner2 = L.latLng(40.774, -74.125), bounds = L.latLngBounds(corner1, corner2); ``` All Leaflet methods that accept LatLngBounds objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this: ``` map.fitBounds([ [40.712, -74.227], [40.774, -74.125] ]); ``` Caution: if the area crosses the antimeridian (often confused with the International Date Line), you must specify corners *outside* the [-180, 180] degrees longitude range. Note that [`LatLngBounds`](#latlngbounds) does not inherit from Leaflet's [`Class`](#class) object, which means new classes can't inherit from it, and new methods can't be added to it with the `include` function. ### Creation | Factory | Description | | --- | --- | | `L.latLngBounds(<[LatLng](#latlng)> *corner1*, <[LatLng](#latlng)> *corner2*)` | Creates a [`LatLngBounds`](#latlngbounds) object by defining two diagonally opposite corners of the rectangle. | | `L.latLngBounds(<LatLng[]> *latlngs*)` | Creates a [`LatLngBounds`](#latlngbounds) object defined by the geographical points it contains. Very useful for zooming the map to fit a particular set of locations with [`fitBounds`](#map-fitbounds). | ### Methods | Method | Returns | Description | | --- | --- | --- | | `extend(<[LatLng](#latlng)> *latlng*)` | `this` | Extend the bounds to contain the given point | | `extend(<[LatLngBounds](#latlngbounds)> *otherBounds*)` | `this` | Extend the bounds to contain the given bounds | | `pad(<Number> *bufferRatio*)` | `[LatLngBounds](#latlngbounds)` | Returns bounds created by extending or retracting the current bounds by a given ratio in each direction. For example, a ratio of 0.5 extends the bounds by 50% in each direction. Negative values will retract the bounds. | | `getCenter()` | `[LatLng](#latlng)` | Returns the center point of the bounds. | | `getSouthWest()` | `[LatLng](#latlng)` | Returns the south-west point of the bounds. | | `getNorthEast()` | `[LatLng](#latlng)` | Returns the north-east point of the bounds. | | `getNorthWest()` | `[LatLng](#latlng)` | Returns the north-west point of the bounds. | | `getSouthEast()` | `[LatLng](#latlng)` | Returns the south-east point of the bounds. | | `getWest()` | `Number` | Returns the west longitude of the bounds | | `getSouth()` | `Number` | Returns the south latitude of the bounds | | `getEast()` | `Number` | Returns the east longitude of the bounds | | `getNorth()` | `Number` | Returns the north latitude of the bounds | | `contains(<[LatLngBounds](#latlngbounds)> *otherBounds*)` | `Boolean` | Returns `true` if the rectangle contains the given one. | | `contains(<[LatLng](#latlng)> *latlng*)` | `Boolean` | Returns `true` if the rectangle contains the given point. | | `intersects(<[LatLngBounds](#latlngbounds)> *otherBounds*)` | `Boolean` | Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common. | | `overlaps(<[LatLngBounds](#latlngbounds)> *otherBounds*)` | `Boolean` | Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area. | | `toBBoxString()` | `String` | Returns a string with bounding box coordinates in a 'southwest\_lng,southwest\_lat,northeast\_lng,northeast\_lat' format. Useful for sending requests to web services that return geo data. | | `equals(<[LatLngBounds](#latlngbounds)> *otherBounds*, <Number> *maxMargin?*)` | `Boolean` | Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number. | | `isValid()` | `Boolean` | Returns `true` if the bounds are properly initialized. | Point ----- Represents a point with `x` and `y` coordinates in pixels. ### Usage example ``` var point = L.point(200, 300); ``` All Leaflet methods and options that accept [`Point`](#point) objects also accept them in a simple Array form (unless noted otherwise), so these lines are equivalent: ``` map.panBy([200, 300]); map.panBy(L.point(200, 300)); ``` Note that [`Point`](#point) does not inherit from Leaflet's [`Class`](#class) object, which means new classes can't inherit from it, and new methods can't be added to it with the `include` function. ### Creation | Factory | Description | | --- | --- | | `L.point(<Number> *x*, <Number> *y*, <Boolean> *round?*)` | Creates a Point object with the given `x` and `y` coordinates. If optional `round` is set to true, rounds the `x` and `y` values. | | `L.point(<Number[]> *coords*)` | Expects an array of the form `[x, y]` instead. | | `L.point(<Object> *coords*)` | Expects a plain object of the form `{x: Number, y: Number}` instead. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `clone()` | `[Point](#point)` | Returns a copy of the current point. | | `add(<[Point](#point)> *otherPoint*)` | `[Point](#point)` | Returns the result of addition of the current and the given points. | | `subtract(<[Point](#point)> *otherPoint*)` | `[Point](#point)` | Returns the result of subtraction of the given point from the current. | | `divideBy(<Number> *num*)` | `[Point](#point)` | Returns the result of division of the current point by the given number. | | `multiplyBy(<Number> *num*)` | `[Point](#point)` | Returns the result of multiplication of the current point by the given number. | | `scaleBy(<[Point](#point)> *scale*)` | `[Point](#point)` | Multiply each coordinate of the current point by each coordinate of `scale`. In linear algebra terms, multiply the point by the [scaling matrix](https://en.wikipedia.org/wiki/Scaling_%28geometry%29#Matrix_representation) defined by `scale`. | | `unscaleBy(<[Point](#point)> *scale*)` | `[Point](#point)` | Inverse of `scaleBy`. Divide each coordinate of the current point by each coordinate of `scale`. | | `round()` | `[Point](#point)` | Returns a copy of the current point with rounded coordinates. | | `floor()` | `[Point](#point)` | Returns a copy of the current point with floored coordinates (rounded down). | | `ceil()` | `[Point](#point)` | Returns a copy of the current point with ceiled coordinates (rounded up). | | `trunc()` | `[Point](#point)` | Returns a copy of the current point with truncated coordinates (rounded towards zero). | | `distanceTo(<[Point](#point)> *otherPoint*)` | `Number` | Returns the cartesian distance between the current and the given points. | | `equals(<[Point](#point)> *otherPoint*)` | `Boolean` | Returns `true` if the given point has the same coordinates. | | `contains(<[Point](#point)> *otherPoint*)` | `Boolean` | Returns `true` if both coordinates of the given point are less than the corresponding current point coordinates (in absolute values). | | `toString()` | `String` | Returns a string representation of the point for debugging purposes. | ### Properties | Property | Type | Description | | --- | --- | --- | | `x` | `Number` | The `x` coordinate of the point | | `y` | `Number` | The `y` coordinate of the point | Bounds ------ Represents a rectangular area in pixel coordinates. ### Usage example ``` var p1 = L.point(10, 10), p2 = L.point(40, 60), bounds = L.bounds(p1, p2); ``` All Leaflet methods that accept [`Bounds`](#bounds) objects also accept them in a simple Array form (unless noted otherwise), so the bounds example above can be passed like this: ``` otherBounds.intersects([[10, 10], [40, 60]]); ``` Note that [`Bounds`](#bounds) does not inherit from Leaflet's [`Class`](#class) object, which means new classes can't inherit from it, and new methods can't be added to it with the `include` function. ### Creation | Factory | Description | | --- | --- | | `L.bounds(<[Point](#point)> *corner1*, <[Point](#point)> *corner2*)` | Creates a Bounds object from two corners coordinate pairs. | | `L.bounds(<Point[]> *points*)` | Creates a Bounds object from the given array of points. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `extend(<[Point](#point)> *point*)` | `this` | Extends the bounds to contain the given point. | | `extend(<[Bounds](#bounds)> *otherBounds*)` | `this` | Extend the bounds to contain the given bounds | | `getCenter(<Boolean> *round?*)` | `[Point](#point)` | Returns the center point of the bounds. | | `getBottomLeft()` | `[Point](#point)` | Returns the bottom-left point of the bounds. | | `getTopRight()` | `[Point](#point)` | Returns the top-right point of the bounds. | | `getTopLeft()` | `[Point](#point)` | Returns the top-left point of the bounds (i.e. [`this.min`](#bounds-min)). | | `getBottomRight()` | `[Point](#point)` | Returns the bottom-right point of the bounds (i.e. [`this.max`](#bounds-max)). | | `getSize()` | `[Point](#point)` | Returns the size of the given bounds | | `contains(<[Bounds](#bounds)> *otherBounds*)` | `Boolean` | Returns `true` if the rectangle contains the given one. | | `contains(<[Point](#point)> *point*)` | `Boolean` | Returns `true` if the rectangle contains the given point. | | `intersects(<[Bounds](#bounds)> *otherBounds*)` | `Boolean` | Returns `true` if the rectangle intersects the given bounds. Two bounds intersect if they have at least one point in common. | | `overlaps(<[Bounds](#bounds)> *otherBounds*)` | `Boolean` | Returns `true` if the rectangle overlaps the given bounds. Two bounds overlap if their intersection is an area. | | `isValid()` | `Boolean` | Returns `true` if the bounds are properly initialized. | | `pad(<Number> *bufferRatio*)` | `[Bounds](#bounds)` | Returns bounds created by extending or retracting the current bounds by a given ratio in each direction. For example, a ratio of 0.5 extends the bounds by 50% in each direction. Negative values will retract the bounds. | | `equals(<[Bounds](#bounds)> *otherBounds*, <Number> *maxMargin?*)` | `Boolean` | Returns `true` if the rectangle is equivalent (within a small margin of error) to the given bounds. The margin of error can be overridden by setting `maxMargin` to a small number. | ### Properties | Property | Type | Description | | --- | --- | --- | | `min` | `[Point](#point)` | The top left corner of the rectangle. | | `max` | `[Point](#point)` | The bottom right corner of the rectangle. | Icon ---- Represents an icon to provide when creating a marker. ### Usage example ``` var myIcon = L.icon({ iconUrl: 'my-icon.png', iconSize: [38, 95], iconAnchor: [22, 94], popupAnchor: [-3, -76], shadowUrl: 'my-icon-shadow.png', shadowSize: [68, 95], shadowAnchor: [22, 94] }); L.marker([50.505, 30.57], {icon: myIcon}).addTo(map); ``` [`L.Icon.Default`](#icon-default) extends [`L.Icon`](#icon) and is the blue icon Leaflet uses for markers by default. ### Creation | Factory | Description | | --- | --- | | `L.icon(<[Icon options](#icon-option)> *options*)` | Creates an icon instance with the given options. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `iconUrl` | `String` | `null` | **(required)** The URL to the icon image (absolute or relative to your script path). | | `iconRetinaUrl` | `String` | `null` | The URL to a retina sized version of the icon image (absolute or relative to your script path). Used for Retina screen devices. | | `iconSize` | `[Point](#point)` | `null` | Size of the icon image in pixels. | | `iconAnchor` | `[Point](#point)` | `null` | The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if size is specified, also can be set in CSS with negative margins. | | `popupAnchor` | `[Point](#point)` | `[0, 0]` | The coordinates of the point from which popups will "open", relative to the icon anchor. | | `tooltipAnchor` | `[Point](#point)` | `[0, 0]` | The coordinates of the point from which tooltips will "open", relative to the icon anchor. | | `shadowUrl` | `String` | `null` | The URL to the icon shadow image. If not specified, no shadow image will be created. | | `shadowRetinaUrl` | `String` | `null` | | | `shadowSize` | `[Point](#point)` | `null` | Size of the shadow image in pixels. | | `shadowAnchor` | `[Point](#point)` | `null` | The coordinates of the "tip" of the shadow (relative to its top left corner) (the same as iconAnchor if not specified). | | `className` | `String` | `''` | A custom class name to assign to both icon and shadow images. Empty by default. | | `crossOrigin` | `Boolean|String` | `false` | Whether the crossOrigin attribute will be added to the tiles. If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data. Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `createIcon(<HTMLElement> *oldIcon?*)` | `HTMLElement` | Called internally when the icon has to be shown, returns a `<img>` HTML element styled according to the options. | | `createShadow(<HTMLElement> *oldIcon?*)` | `HTMLElement` | As `createIcon`, but for the shadow beneath it. | ### Icon.Default A trivial subclass of [`Icon`](#icon), represents the icon to use in [`Marker`](#marker)s when no icon is specified. Points to the blue marker image distributed with Leaflet releases. In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options` (which is a set of [`Icon options`](#icon-option)). If you want to *completely* replace the default icon, override the `L.Marker.prototype.options.icon` with your own icon instead. | Option | Type | Default | Description | | --- | --- | --- | --- | | `imagePath` | `String` | | [`Icon.Default`](#icon-default) will try to auto-detect the location of the blue icon images. If you are placing these images in a non-standard way, set this option to point to the right path. | DivIcon ------- Represents a lightweight icon for markers that uses a simple `<div>` element instead of an image. Inherits from [`Icon`](#icon) but ignores the `iconUrl` and shadow options. ### Usage example ``` var myIcon = L.divIcon({className: 'my-div-icon'}); // you can set .my-div-icon styles in CSS L.marker([50.505, 30.57], {icon: myIcon}).addTo(map); ``` By default, it has a 'leaflet-div-icon' CSS class and is styled as a little white square with a shadow. ### Creation | Factory | Description | | --- | --- | | `L.divIcon(<[DivIcon options](#divicon-option)> *options*)` | Creates a [`DivIcon`](#divicon) instance with the given options. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `html` | `String|HTMLElement` | `''` | Custom HTML code to put inside the div element, empty by default. Alternatively, an instance of `HTMLElement`. | | `bgPos` | `[Point](#point)` | `[0, 0]` | Optional relative position of the background, in pixels | Options inherited from [Icon](#icon) | Option | Type | Default | Description | | --- | --- | --- | --- | | `iconUrl` | `String` | `null` | **(required)** The URL to the icon image (absolute or relative to your script path). | | `iconRetinaUrl` | `String` | `null` | The URL to a retina sized version of the icon image (absolute or relative to your script path). Used for Retina screen devices. | | `iconSize` | `[Point](#point)` | `null` | Size of the icon image in pixels. | | `iconAnchor` | `[Point](#point)` | `null` | The coordinates of the "tip" of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker's geographical location. Centered by default if size is specified, also can be set in CSS with negative margins. | | `popupAnchor` | `[Point](#point)` | `[0, 0]` | The coordinates of the point from which popups will "open", relative to the icon anchor. | | `tooltipAnchor` | `[Point](#point)` | `[0, 0]` | The coordinates of the point from which tooltips will "open", relative to the icon anchor. | | `shadowUrl` | `String` | `null` | The URL to the icon shadow image. If not specified, no shadow image will be created. | | `shadowRetinaUrl` | `String` | `null` | | | `shadowSize` | `[Point](#point)` | `null` | Size of the shadow image in pixels. | | `shadowAnchor` | `[Point](#point)` | `null` | The coordinates of the "tip" of the shadow (relative to its top left corner) (the same as iconAnchor if not specified). | | `className` | `String` | `''` | A custom class name to assign to both icon and shadow images. Empty by default. | | `crossOrigin` | `Boolean|String` | `false` | Whether the crossOrigin attribute will be added to the tiles. If a String is provided, all tiles will have their crossOrigin attribute set to the String provided. This is needed if you want to access tile pixel data. Refer to [CORS Settings](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) for valid String values. | ### Methods Methods inherited from [Icon](#icon) | Method | Returns | Description | | --- | --- | --- | | `createIcon(<HTMLElement> *oldIcon?*)` | `HTMLElement` | Called internally when the icon has to be shown, returns a `<img>` HTML element styled according to the options. | | `createShadow(<HTMLElement> *oldIcon?*)` | `HTMLElement` | As `createIcon`, but for the shadow beneath it. | Control.Zoom ------------ A basic zoom control with two buttons (zoom in and zoom out). It is put on the map by default unless you set its [`zoomControl` option](#map-zoomcontrol) to `false`. Extends [`Control`](#control). ### Creation | Factory | Description | | --- | --- | | `L.control.zoom(<[Control.Zoom options](#control-zoom-option)> *options*)` | Creates a zoom control | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `zoomInText` | `String` | `'<span aria-hidden="true">+</span>'` | The text set on the 'zoom in' button. | | `zoomInTitle` | `String` | `'Zoom in'` | The title set on the 'zoom in' button. | | `zoomOutText` | `String` | `'<span aria-hidden="true">&#x2212;</span>'` | The text set on the 'zoom out' button. | | `zoomOutTitle` | `String` | `'Zoom out'` | The title set on the 'zoom out' button. | Options inherited from [Control](#control) | Option | Type | Default | Description | | --- | --- | --- | --- | | `position` | `String` | `'topright'` | The position of the control (one of the map corners). Possible values are `'topleft'`, `'topright'`, `'bottomleft'` or `'bottomright'` | ### Methods Methods inherited from [Control](#control) | Method | Returns | Description | | --- | --- | --- | | `getPosition()` | `string` | Returns the position of the control. | | `setPosition(<string> *position*)` | `this` | Sets the position of the control. | | `getContainer()` | `HTMLElement` | Returns the HTMLElement that contains the control. | | `addTo(<[Map](#map)> *map*)` | `this` | Adds the control to the given map. | | `remove()` | `this` | Removes the control from the map it is currently active on. | Control.Attribution ------------------- The attribution control allows you to display attribution data in a small text box on a map. It is put on the map by default unless you set its [`attributionControl` option](#map-attributioncontrol) to `false`, and it fetches attribution texts from layers with the [`getAttribution` method](#layer-getattribution) automatically. Extends Control. ### Creation | Factory | Description | | --- | --- | | `L.control.attribution(<[Control.Attribution options](#control-attribution-option)> *options*)` | Creates an attribution control. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `prefix` | `String|false` | `'Leaflet'` | The HTML text shown before the attributions. Pass `false` to disable. | Options inherited from [Control](#control) | Option | Type | Default | Description | | --- | --- | --- | --- | | `position` | `String` | `'topright'` | The position of the control (one of the map corners). Possible values are `'topleft'`, `'topright'`, `'bottomleft'` or `'bottomright'` | ### Methods | Method | Returns | Description | | --- | --- | --- | | `setPrefix(<String|false> *prefix*)` | `this` | The HTML text shown before the attributions. Pass `false` to disable. | | `addAttribution(<String> *text*)` | `this` | Adds an attribution text (e.g. `'&copy; OpenStreetMap contributors'`). | | `removeAttribution(<String> *text*)` | `this` | Removes an attribution text. | Methods inherited from [Control](#control) | Method | Returns | Description | | --- | --- | --- | | `getPosition()` | `string` | Returns the position of the control. | | `setPosition(<string> *position*)` | `this` | Sets the position of the control. | | `getContainer()` | `HTMLElement` | Returns the HTMLElement that contains the control. | | `addTo(<[Map](#map)> *map*)` | `this` | Adds the control to the given map. | | `remove()` | `this` | Removes the control from the map it is currently active on. | Control.Layers -------------- The layers control gives users the ability to switch between different base layers and switch overlays on/off (check out the [detailed example](https://leafletjs.com/examples/layers-control/)). Extends [`Control`](#control). ### Usage example ``` var baseLayers = { "Mapbox": mapbox, "OpenStreetMap": osm }; var overlays = { "Marker": marker, "Roads": roadsLayer }; L.control.layers(baseLayers, overlays).addTo(map); ``` The `baseLayers` and `overlays` parameters are object literals with layer names as keys and [`Layer`](#layer) objects as values: ``` { "<someName1>": layer1, "<someName2>": layer2 } ``` The layer names can contain HTML, which allows you to add additional styling to the items: ``` {"<img src='my-layer-icon' /> <span class='my-layer-item'>My Layer</span>": myLayer} ``` ### Creation | Factory | Description | | --- | --- | | `L.control.layers(<Object> *baselayers?*, <Object> *overlays?*, <[Control.Layers options](#control-layers-option)> *options?*)` | Creates a layers control with the given layers. Base layers will be switched with radio buttons, while overlays will be switched with checkboxes. Note that all base layers should be passed in the base layers object, but only one should be added to the map during map instantiation. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `collapsed` | `Boolean` | `true` | If `true`, the control will be collapsed into an icon and expanded on mouse hover, touch, or keyboard activation. | | `autoZIndex` | `Boolean` | `true` | If `true`, the control will assign zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off. | | `hideSingleBase` | `Boolean` | `false` | If `true`, the base layers in the control will be hidden when there is only one. | | `sortLayers` | `Boolean` | `false` | Whether to sort the layers. When `false`, layers will keep the order in which they were added to the control. | | `sortFunction` | `Function` | `*` | A [compare function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) that will be used for sorting the layers, when `sortLayers` is `true`. The function receives both the [`L.Layer`](#layer) instances and their names, as in `sortFunction(layerA, layerB, nameA, nameB)`. By default, it sorts layers alphabetically by their name. | Options inherited from [Control](#control) | Option | Type | Default | Description | | --- | --- | --- | --- | | `position` | `String` | `'topright'` | The position of the control (one of the map corners). Possible values are `'topleft'`, `'topright'`, `'bottomleft'` or `'bottomright'` | ### Methods | Method | Returns | Description | | --- | --- | --- | | `addBaseLayer(<[Layer](#layer)> *layer*, <String> *name*)` | `this` | Adds a base layer (radio button entry) with the given name to the control. | | `addOverlay(<[Layer](#layer)> *layer*, <String> *name*)` | `this` | Adds an overlay (checkbox entry) with the given name to the control. | | `removeLayer(<[Layer](#layer)> *layer*)` | `this` | Remove the given layer from the control. | | `expand()` | `this` | Expand the control container if collapsed. | | `collapse()` | `this` | Collapse the control container if expanded. | Methods inherited from [Control](#control) | Method | Returns | Description | | --- | --- | --- | | `getPosition()` | `string` | Returns the position of the control. | | `setPosition(<string> *position*)` | `this` | Sets the position of the control. | | `getContainer()` | `HTMLElement` | Returns the HTMLElement that contains the control. | | `addTo(<[Map](#map)> *map*)` | `this` | Adds the control to the given map. | | `remove()` | `this` | Removes the control from the map it is currently active on. | Control.Scale ------------- A simple scale control that shows the scale of the current center of screen in metric (m/km) and imperial (mi/ft) systems. Extends [`Control`](#control). ### Usage example ``` L.control.scale().addTo(map); ``` ### Creation | Factory | Description | | --- | --- | | `L.control.scale(<[Control.Scale options](#control-scale-option)> *options?*)` | Creates an scale control with the given options. | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `maxWidth` | `Number` | `100` | Maximum width of the control in pixels. The width is set dynamically to show round values (e.g. 100, 200, 500). | | `metric` | `Boolean` | `True` | Whether to show the metric scale line (m/km). | | `imperial` | `Boolean` | `True` | Whether to show the imperial scale line (mi/ft). | | `updateWhenIdle` | `Boolean` | `false` | If `true`, the control is updated on [`moveend`](#map-moveend), otherwise it's always up-to-date (updated on [`move`](#map-move)). | Options inherited from [Control](#control) | Option | Type | Default | Description | | --- | --- | --- | --- | | `position` | `String` | `'topright'` | The position of the control (one of the map corners). Possible values are `'topleft'`, `'topright'`, `'bottomleft'` or `'bottomright'` | ### Methods Methods inherited from [Control](#control) | Method | Returns | Description | | --- | --- | --- | | `getPosition()` | `string` | Returns the position of the control. | | `setPosition(<string> *position*)` | `this` | Sets the position of the control. | | `getContainer()` | `HTMLElement` | Returns the HTMLElement that contains the control. | | `addTo(<[Map](#map)> *map*)` | `this` | Adds the control to the given map. | | `remove()` | `this` | Removes the control from the map it is currently active on. | Browser ------- A namespace with static properties for browser/feature detection used by Leaflet internally. ### Usage example ``` if (L.Browser.ielt9) { alert('Upgrade your browser, dude!'); } ``` ### Properties | Property | Type | Description | | --- | --- | --- | | `ie` | `Boolean` | `true` for all Internet Explorer versions (not Edge). | | `ielt9` | `Boolean` | `true` for Internet Explorer versions less than 9. | | `edge` | `Boolean` | `true` for the Edge web browser. | | `webkit` | `Boolean;` | `true` for webkit-based browsers like Chrome and Safari (including mobile versions). | | `android` | `Boolean` | **Deprecated.** `true` for any browser running on an Android platform. | | `android23` | `Boolean` | **Deprecated.** `true` for browsers running on Android 2 or Android 3. | | `androidStock` | `Boolean` | **Deprecated.** `true` for the Android stock browser (i.e. not Chrome) | | `opera` | `Boolean` | `true` for the Opera browser | | `chrome` | `Boolean` | `true` for the Chrome browser. | | `gecko` | `Boolean` | `true` for gecko-based browsers like Firefox. | | `safari` | `Boolean` | `true` for the Safari browser. | | `opera12` | `Boolean` | `true` for the Opera browser supporting CSS transforms (version 12 or later). | | `win` | `Boolean` | `true` when the browser is running in a Windows platform | | `ie3d` | `Boolean` | `true` for all Internet Explorer versions supporting CSS transforms. | | `webkit3d` | `Boolean` | `true` for webkit-based browsers supporting CSS transforms. | | `gecko3d` | `Boolean` | `true` for gecko-based browsers supporting CSS transforms. | | `any3d` | `Boolean` | `true` for all browsers supporting CSS transforms. | | `mobile` | `Boolean` | `true` for all browsers running in a mobile device. | | `mobileWebkit` | `Boolean` | `true` for all webkit-based browsers in a mobile device. | | `mobileWebkit3d` | `Boolean` | `true` for all webkit-based browsers in a mobile device supporting CSS transforms. | | `msPointer` | `Boolean` | `true` for browsers implementing the Microsoft touch events model (notably IE10). | | `pointer` | `Boolean` | `true` for all browsers supporting [pointer events](https://msdn.microsoft.com/en-us/library/dn433244%28v=vs.85%29.aspx). | | `touchNative` | `Boolean` | `true` for all browsers supporting [touch events](https://developer.mozilla.org/docs/Web/API/Touch_events). **This does not necessarily mean** that the browser is running in a computer with a touchscreen, it only means that the browser is capable of understanding touch events. | | `touch` | `Boolean` | `true` for all browsers supporting either [touch](#browser-touch) or [pointer](#browser-pointer) events. Note: pointer events will be preferred (if available), and processed for all `touch*` listeners. | | `mobileOpera` | `Boolean` | `true` for the Opera browser in a mobile device. | | `mobileGecko` | `Boolean` | `true` for gecko-based browsers running in a mobile device. | | `retina` | `Boolean` | `true` for browsers on a high-resolution "retina" screen or on any screen when browser's display zoom is more than 100%. | | `passiveEvents` | `Boolean` | `true` for browsers that support passive events. | | `canvas` | `Boolean` | `true` when the browser supports [`<canvas>`](https://developer.mozilla.org/docs/Web/API/Canvas_API). | | `svg` | `Boolean` | `true` when the browser supports [SVG](https://developer.mozilla.org/docs/Web/SVG). | | `vml` | `Boolean` | `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language). | | `mac` | `Boolean` | `true` when the browser is running in a Mac platform `true` when the browser is running in a Linux platform | Util ---- Various utility functions, used by Leaflet internally. ### Functions | Function | Returns | Description | | --- | --- | --- | | `extend(<Object> *dest*, <Object> *src?*)` | `Object` | Merges the properties of the `src` object (or multiple objects) into `dest` object and returns the latter. Has an `L.extend` shortcut. | | `create(<Object> *proto*, <Object> *properties?*)` | `Object` | Compatibility polyfill for [Object.create](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/create) | | `bind(<Function> *fn*, *…*)` | `Function` | Returns a new function bound to the arguments passed, like [Function.prototype.bind](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). Has a `L.bind()` shortcut. | | `stamp(<Object> *obj*)` | `Number` | Returns the unique ID of an object, assigning it one if it doesn't have it. | | `throttle(<Function> *fn*, <Number> *time*, <Object> *context*)` | `Function` | Returns a function which executes function `fn` with the given scope `context` (so that the `this` keyword refers to `context` inside `fn`'s code). The function `fn` will be called no more than one time per given amount of `time`. The arguments received by the bound function will be any arguments passed when binding the function, followed by any arguments passed when invoking the bound function. Has an `L.throttle` shortcut. | | `wrapNum(<Number> *num*, <Number[]> *range*, <Boolean> *includeMax?*)` | `Number` | Returns the number `num` modulo `range` in such a way so it lies within `range[0]` and `range[1]`. The returned value will be always smaller than `range[1]` unless `includeMax` is set to `true`. | | `falseFn()` | `Function` | Returns a function which always returns `false`. | | `formatNum(<Number> *num*, <Number|false> *precision?*)` | `Number` | Returns the number `num` rounded with specified `precision`. The default `precision` value is 6 decimal places. `false` can be passed to skip any processing (can be useful to avoid round-off errors). | | `trim(<String> *str*)` | `String` | Compatibility polyfill for [String.prototype.trim](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim) | | `splitWords(<String> *str*)` | `String[]` | Trims and splits the string on whitespace and returns the array of parts. | | `setOptions(<Object> *obj*, <Object> *options*)` | `Object` | Merges the given properties to the `options` of the `obj` object, returning the resulting options. See `Class options`. Has an `L.setOptions` shortcut. | | `getParamString(<Object> *obj*, <String> *existingUrl?*, <Boolean> *uppercase?*)` | `String` | Converts an object into a parameter URL string, e.g. `{a: "foo", b: "bar"}` translates to `'?a=foo&b=bar'`. If `existingUrl` is set, the parameters will be appended at the end. If `uppercase` is `true`, the parameter names will be uppercased (e.g. `'?A=foo&B=bar'`) | | `template(<String> *str*, <Object> *data*)` | `String` | Simple templating facility, accepts a template string of the form `'Hello {a}, {b}'` and a data object like `{a: 'foo', b: 'bar'}`, returns evaluated string `('Hello foo, bar')`. You can also specify functions instead of strings for data values — they will be evaluated passing `data` as an argument. | | `isArray(*obj*)` | `Boolean` | Compatibility polyfill for [Array.isArray](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) | | `indexOf(<Array> *array*, <Object> *el*)` | `Number` | Compatibility polyfill for [Array.prototype.indexOf](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) | | `requestAnimFrame(<Function> *fn*, <Object> *context?*, <Boolean> *immediate?*)` | `Number` | Schedules `fn` to be executed when the browser repaints. `fn` is bound to `context` if given. When `immediate` is set, `fn` is called immediately if the browser doesn't have native support for [`window.requestAnimationFrame`](https://developer.mozilla.org/docs/Web/API/window/requestAnimationFrame), otherwise it's delayed. Returns a request ID that can be used to cancel the request. | | `cancelAnimFrame(<Number> *id*)` | `undefined` | Cancels a previous `requestAnimFrame`. See also [window.cancelAnimationFrame](https://developer.mozilla.org/docs/Web/API/window/cancelAnimationFrame). | ### Properties | Property | Type | Description | | --- | --- | --- | | `lastId` | `Number` | Last unique ID used by [`stamp()`](#util-stamp) | | `emptyImageUrl` | `String` | Data URI string containing a base64-encoded empty GIF image. Used as a hack to free memory from unused images on WebKit-powered mobile devices (by setting image `src` to this string). | Transformation -------------- Represents an affine transformation: a set of coefficients `a`, `b`, `c`, `d` for transforming a point of a form `(x, y)` into `(a*x + b, c*y + d)` and doing the reverse. Used by Leaflet in its projections code. ### Usage example ``` var transformation = L.transformation(2, 5, -1, 10), p = L.point(1, 2), p2 = transformation.transform(p), // L.point(7, 8) p3 = transformation.untransform(p2); // L.point(1, 2) ``` ### Creation | Factory | Description | | --- | --- | | `L.transformation(<Number> *a*, <Number> *b*, <Number> *c*, <Number> *d*)` | Instantiates a Transformation object with the given coefficients. | | `L.transformation(<Array> *coefficients*)` | Expects an coefficients array of the form `[a: Number, b: Number, c: Number, d: Number]`. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `transform(<[Point](#point)> *point*, <Number> *scale?*)` | `[Point](#point)` | Returns a transformed point, optionally multiplied by the given scale. Only accepts actual [`L.Point`](#point) instances, not arrays. | | `untransform(<[Point](#point)> *point*, <Number> *scale?*)` | `[Point](#point)` | Returns the reverse transformation of the given point, optionally divided by the given scale. Only accepts actual [`L.Point`](#point) instances, not arrays. | LineUtil -------- Various utility functions for polyline points processing, used by Leaflet internally to make polylines lightning-fast. ### Functions | Function | Returns | Description | | --- | --- | --- | | `simplify(<Point[]> *points*, <Number> *tolerance*)` | `Point[]` | Dramatically reduces the number of points in a polyline while retaining its shape and returns a new array of simplified points, using the [Ramer-Douglas-Peucker algorithm](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm). Used for a huge performance boost when processing/displaying Leaflet polylines for each zoom level and also reducing visual noise. tolerance affects the amount of simplification (lesser value means higher quality but slower and with more points). Also released as a separated micro-library [Simplify.js](https://mourner.github.io/simplify-js/). | | `pointToSegmentDistance(<[Point](#point)> *p*, <[Point](#point)> *p1*, <[Point](#point)> *p2*)` | `Number` | Returns the distance between point `p` and segment `p1` to `p2`. | | `closestPointOnSegment(<[Point](#point)> *p*, <[Point](#point)> *p1*, <[Point](#point)> *p2*)` | `Number` | Returns the closest point from a point `p` on a segment `p1` to `p2`. | | `clipSegment(<[Point](#point)> *a*, <[Point](#point)> *b*, <[Bounds](#bounds)> *bounds*, <Boolean> *useLastCode?*, <Boolean> *round?*)` | `Point[]|Boolean` | Clips the segment a to b by rectangular bounds with the [Cohen-Sutherland algorithm](https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm) (modifying the segment points directly!). Used by Leaflet to only show polyline points that are on the screen or near, increasing performance. | | `isFlat(<LatLng[]> *latlngs*)` | `Boolean` | Returns true if `latlngs` is a flat array, false is nested. | | `polylineCenter(<LatLng[]> *latlngs*, <[CRS](#crs)> *crs*)` | `[LatLng](#latlng)` | Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polyline. | PolyUtil -------- Various utility functions for polygon geometries. ### Functions | Function | Returns | Description | | --- | --- | --- | | `clipPolygon(<Point[]> *points*, <[Bounds](#bounds)> *bounds*, <Boolean> *round?*)` | `Point[]` | Clips the polygon geometry defined by the given `points` by the given bounds (using the [Sutherland-Hodgman algorithm](https://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman_algorithm)). Used by Leaflet to only show polygon points that are on the screen or near, increasing performance. Note that polygon points needs different algorithm for clipping than polyline, so there's a separate method for it. | | `polygonCenter(<LatLng[] crs: CRS> *latlngs*)` | `[LatLng](#latlng)` | Returns the center ([centroid](http://en.wikipedia.org/wiki/Centroid)) of the passed LatLngs (first ring) from a polygon. | DomEvent -------- Utility functions to work with the [DOM events](https://developer.mozilla.org/docs/Web/API/Event), used by Leaflet internally. ### Functions | Function | Returns | Description | | --- | --- | --- | | `on(<HTMLElement> *el*, <String> *types*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular DOM event type of the element `el`. You can optionally specify the context of the listener (object the `this` keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<HTMLElement> *el*, <Object> *eventMap*, <Object> *context?*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<HTMLElement> *el*, <String> *types*, <Function> *fn*, <Object> *context?*)` | `this` | Removes a previously added listener function. Note that if you passed a custom context to on, you must pass the same context to `off` in order to remove the listener. | | `off(<HTMLElement> *el*, <Object> *eventMap*, <Object> *context?*)` | `this` | Removes a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<HTMLElement> *el*, <String> *types*)` | `this` | Removes all previously added listeners of given types. | | `off(<HTMLElement> *el*)` | `this` | Removes all previously added listeners from given HTMLElement | | `stopPropagation(<DOMEvent> *ev*)` | `this` | Stop the given event from propagation to parent elements. Used inside the listener functions: ``` L.DomEvent.on(div, 'click', function (ev) { L.DomEvent.stopPropagation(ev); }); ``` | | `disableScrollPropagation(<HTMLElement> *el*)` | `this` | Adds `stopPropagation` to the element's `'wheel'` events (plus browser variants). | | `disableClickPropagation(<HTMLElement> *el*)` | `this` | Adds `stopPropagation` to the element's `'click'`, `'dblclick'`, `'contextmenu'`, `'mousedown'` and `'touchstart'` events (plus browser variants). | | `preventDefault(<DOMEvent> *ev*)` | `this` | Prevents the default action of the DOM Event `ev` from happening (such as following a link in the href of the a element, or doing a POST request with page reload when a `<form>` is submitted). Use it inside listener functions. | | `stop(<DOMEvent> *ev*)` | `this` | Does `stopPropagation` and `preventDefault` at the same time. | | `getPropagationPath(<DOMEvent> *ev*)` | `Array` | Compatibility polyfill for [`Event.composedPath()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath). Returns an array containing the `HTMLElement`s that the given DOM event should propagate to (if not stopped). | | `getMousePosition(<DOMEvent> *ev*, <HTMLElement> *container?*)` | `[Point](#point)` | Gets normalized mouse position from a DOM event relative to the `container` (border excluded) or to the whole page if not specified. | | `getWheelDelta(<DOMEvent> *ev*)` | `Number` | Gets normalized wheel delta from a wheel DOM event, in vertical pixels scrolled (negative if scrolling down). Events from pointing devices without precise scrolling are mapped to a best guess of 60 pixels. | | `addListener(*…*)` | `this` | Alias to [`L.DomEvent.on`](#domevent-on) | | `removeListener(*…*)` | `this` | Alias to [`L.DomEvent.off`](#domevent-off) | DomUtil ------- Utility functions to work with the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model) tree, used by Leaflet internally. Most functions expecting or returning a `HTMLElement` also work for SVG elements. The only difference is that classes refer to CSS classes in HTML and SVG classes in SVG. ### Functions | Function | Returns | Description | | --- | --- | --- | | `get(<String|HTMLElement> *id*)` | `HTMLElement` | Returns an element given its DOM id, or returns the element itself if it was passed directly. | | `getStyle(<HTMLElement> *el*, <String> *styleAttrib*)` | `String` | Returns the value for a certain style attribute on an element, including computed values or values set through CSS. | | `create(<String> *tagName*, <String> *className?*, <HTMLElement> *container?*)` | `HTMLElement` | Creates an HTML element with `tagName`, sets its class to `className`, and optionally appends it to `container` element. | | `remove(<HTMLElement> *el*)` | | Removes `el` from its parent element | | `empty(<HTMLElement> *el*)` | | Removes all of `el`'s children elements from `el` | | `toFront(<HTMLElement> *el*)` | | Makes `el` the last child of its parent, so it renders in front of the other children. | | `toBack(<HTMLElement> *el*)` | | Makes `el` the first child of its parent, so it renders behind the other children. | | `hasClass(<HTMLElement> *el*, <String> *name*)` | `Boolean` | Returns `true` if the element's class attribute contains `name`. | | `addClass(<HTMLElement> *el*, <String> *name*)` | | Adds `name` to the element's class attribute. | | `removeClass(<HTMLElement> *el*, <String> *name*)` | | Removes `name` from the element's class attribute. | | `setClass(<HTMLElement> *el*, <String> *name*)` | | Sets the element's class. | | `getClass(<HTMLElement> *el*)` | `String` | Returns the element's class. | | `setOpacity(<HTMLElement> *el*, <Number> *opacity*)` | | Set the opacity of an element (including old IE support). `opacity` must be a number from `0` to `1`. | | `testProp(<String[]> *props*)` | `String|false` | Goes through the array of style names and returns the first name that is a valid style name for an element. If no such name is found, it returns false. Useful for vendor-prefixed styles like `transform`. | | `setTransform(<HTMLElement> *el*, <[Point](#point)> *offset*, <Number> *scale?*)` | | Resets the 3D CSS transform of `el` so it is translated by `offset` pixels and optionally scaled by `scale`. Does not have an effect if the browser doesn't support 3D CSS transforms. | | `setPosition(<HTMLElement> *el*, <[Point](#point)> *position*)` | | Sets the position of `el` to coordinates specified by `position`, using CSS translate or top/left positioning depending on the browser (used by Leaflet internally to position its layers). | | `getPosition(<HTMLElement> *el*)` | `[Point](#point)` | Returns the coordinates of an element previously positioned with setPosition. | | `disableTextSelection()` | | Prevents the user from generating `selectstart` DOM events, usually generated when the user drags the mouse through a page with text. Used internally by Leaflet to override the behaviour of any click-and-drag interaction on the map. Affects drag interactions on the whole document. | | `enableTextSelection()` | | Cancels the effects of a previous [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection). | | `disableImageDrag()` | | As [`L.DomUtil.disableTextSelection`](#domutil-disabletextselection), but for `dragstart` DOM events, usually generated when the user drags an image. | | `enableImageDrag()` | | Cancels the effects of a previous [`L.DomUtil.disableImageDrag`](#domutil-disabletextselection). | | `preventOutline(<HTMLElement> *el*)` | | Makes the [outline](https://developer.mozilla.org/docs/Web/CSS/outline) of the element `el` invisible. Used internally by Leaflet to prevent focusable elements from displaying an outline when the user performs a drag interaction on them. | | `restoreOutline()` | | Cancels the effects of a previous [`L.DomUtil.preventOutline`](https://leafletjs.com/reference.html). | | `getSizedParentNode(<HTMLElement> *el*)` | `HTMLElement` | Finds the closest parent node which size (width and height) is not null. | | `getScale(<HTMLElement> *el*)` | `Object` | Computes the CSS scale currently applied on the element. Returns an object with `x` and `y` members as horizontal and vertical scales respectively, and `boundingClientRect` as the result of [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). | ### Properties | Property | Type | Description | | --- | --- | --- | | `TRANSFORM` | `String` | Vendor-prefixed transform style name (e.g. `'webkitTransform'` for WebKit). | | `TRANSITION` | `String` | Vendor-prefixed transition style name. | | `TRANSITION_END` | `String` | Vendor-prefixed transitionend event name. | PosAnimation ------------ Used internally for panning animations, utilizing CSS3 Transitions for modern browsers and a timer fallback for IE6-9. ### Usage example ``` var myPositionMarker = L.marker([48.864716, 2.294694]).addTo(map); myPositionMarker.on("click", function() { var pos = map.latLngToLayerPoint(myPositionMarker.getLatLng()); pos.y -= 25; var fx = new L.PosAnimation(); fx.once('end',function() { pos.y += 25; fx.run(myPositionMarker._icon, pos, 0.8); }); fx.run(myPositionMarker._icon, pos, 0.3); }); ``` ### Constructor | Constructor | Description | | --- | --- | | `L.PosAnimation()` | Creates a [`PosAnimation`](#posanimation) object. | ### Events | Event | Data | Description | | --- | --- | --- | | `start` | `[Event](#event)` | Fired when the animation starts | | `step` | `[Event](#event)` | Fired continuously during the animation. | | `end` | `[Event](#event)` | Fired when the animation ends. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `run(<HTMLElement> *el*, <[Point](#point)> *newPos*, <Number> *duration?*, <Number> *easeLinearity?*)` | | Run an animation of a given element to a new position, optionally setting duration in seconds (`0.25` by default) and easing linearity factor (3rd argument of the [cubic bezier curve](https://cubic-bezier.com/#0,0,.5,1), `0.5` by default). | | `stop()` | | Stops the animation (if currently running). | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Draggable --------- A class for making DOM elements draggable (including touch support). Used internally for map and marker dragging. Only works for elements that were positioned with [`L.DomUtil.setPosition`](#domutil-setposition). ### Usage example ``` var draggable = new L.Draggable(elementToDrag); draggable.enable(); ``` ### Constructor | Constructor | Description | | --- | --- | | `L.Draggable(<HTMLElement> *el*, <HTMLElement> *dragHandle?*, <Boolean> *preventOutline?*, <[Draggable options](#draggable-option)> *options?*)` | Creates a [`Draggable`](#draggable) object for moving `el` when you start dragging the `dragHandle` element (equals `el` itself by default). | ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `clickTolerance` | `Number` | `3` | The max number of pixels a user can shift the mouse pointer during a click for it to be considered a valid click (as opposed to a mouse drag). | ### Events | Event | Data | Description | | --- | --- | --- | | `down` | `[Event](#event)` | Fired when a drag is about to start. | | `dragstart` | `[Event](#event)` | Fired when a drag starts | | `predrag` | `[Event](#event)` | Fired continuously during dragging *before* each corresponding update of the element's position. | | `drag` | `[Event](#event)` | Fired continuously during dragging. | | `dragend` | `[DragEndEvent](#dragendevent)` | Fired when the drag ends. | ### Methods | Method | Returns | Description | | --- | --- | --- | | `enable()` | | Enables the dragging ability | | `disable()` | | Disables the dragging ability | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Class ----- L.Class powers the OOP facilities of Leaflet and is used to create almost all of the Leaflet classes documented here. In addition to implementing a simple classical inheritance model, it introduces several special properties for convenient code organization — options, includes and statics. ### Usage example ``` var MyClass = L.Class.extend({ initialize: function (greeter) { this.greeter = greeter; // class constructor }, greet: function (name) { alert(this.greeter + ', ' + name) } }); // create instance of MyClass, passing "Hello" to the constructor var a = new MyClass("Hello"); // call greet method, alerting "Hello, World" a.greet("World"); ``` #### Class Factories You may have noticed that Leaflet objects are created without using the `new` keyword. This is achieved by complementing each class with a lowercase factory method: ``` new L.Map('map'); // becomes: L.map('map'); ``` The factories are implemented very easily, and you can do this for your own classes: ``` L.map = function (id, options) { return new L.Map(id, options); }; ``` #### Inheritance You use L.Class.extend to define new classes, but you can use the same method on any class to inherit from it: ``` var MyChildClass = MyClass.extend({ // ... new properties and methods }); ``` This will create a class that inherits all methods and properties of the parent class (through a proper prototype chain), adding or overriding the ones you pass to extend. It will also properly react to instanceof: ``` var a = new MyChildClass(); a instanceof MyChildClass; // true a instanceof MyClass; // true ``` You can call parent methods (including constructor) from corresponding child ones (as you do with super calls in other languages) by accessing parent class prototype and using JavaScript's call or apply: ``` var MyChildClass = MyClass.extend({ initialize: function () { MyClass.prototype.initialize.call(this, "Yo"); }, greet: function (name) { MyClass.prototype.greet.call(this, 'bro ' + name + '!'); } }); var a = new MyChildClass(); a.greet('Jason'); // alerts "Yo, bro Jason!" ``` #### Options `options` is a special property that unlike other objects that you pass to `extend` will be merged with the parent one instead of overriding it completely, which makes managing configuration of objects and default values convenient: ``` var MyClass = L.Class.extend({ options: { myOption1: 'foo', myOption2: 'bar' } }); var MyChildClass = MyClass.extend({ options: { myOption1: 'baz', myOption3: 5 } }); var a = new MyChildClass(); a.options.myOption1; // 'baz' a.options.myOption2; // 'bar' a.options.myOption3; // 5 ``` There's also [`L.Util.setOptions`](#util-setoptions), a method for conveniently merging options passed to constructor with the defaults defines in the class: ``` var MyClass = L.Class.extend({ options: { foo: 'bar', bla: 5 }, initialize: function (options) { L.Util.setOptions(this, options); ... } }); var a = new MyClass({bla: 10}); a.options; // {foo: 'bar', bla: 10} ``` Note that the options object allows any keys, not just the options defined by the class and its base classes. This means you can use the options object to store application specific information, as long as you avoid keys that are already used by the class in question. #### Includes `includes` is a special class property that merges all specified objects into the class (such objects are called mixins). ``` var MyMixin = { foo: function () { ... }, bar: 5 }; var MyClass = L.Class.extend({ includes: MyMixin }); var a = new MyClass(); a.foo(); ``` You can also do such includes in runtime with the `include` method: ``` MyClass.include(MyMixin); ``` `statics` is just a convenience property that injects specified object properties as the static properties of the class, useful for defining constants: ``` var MyClass = L.Class.extend({ statics: { FOO: 'bar', BLA: 5 } }); MyClass.FOO; // 'bar' ``` #### Constructor hooks If you're a plugin developer, you often need to add additional initialization code to existing classes (e.g. editing hooks for [`L.Polyline`](#polyline)). Leaflet comes with a way to do it easily using the `addInitHook` method: ``` MyClass.addInitHook(function () { // ... do something in constructor additionally // e.g. add event listeners, set custom properties etc. }); ``` You can also use the following shortcut when you just need to make one additional method call: ``` MyClass.addInitHook('methodName', arg1, arg2, …); ``` ### Functions | Function | Returns | Description | | --- | --- | --- | | `extend(<Object> *props*)` | `Function` | [Extends the current class](#class-inheritance) given the properties to be included. Returns a Javascript function that is a class constructor (to be called with `new`). | | `include(<Object> *properties*)` | `this` | [Includes a mixin](#class-includes) into the current class. | | `mergeOptions(<Object> *options*)` | `this` | [Merges `options`](#class-options) into the defaults of the class. | | `addInitHook(<Function> *fn*)` | `this` | Adds a [constructor hook](#class-constructor-hooks) to the class. | Evented ------- A set of methods shared between event-powered classes (like [`Map`](#map) and [`Marker`](#marker)). Generally, events allow you to execute some function when something happens with an object (e.g. the user clicks on the map, causing the map to fire `'click'` event). ### Usage example ``` map.on('click', function(e) { alert(e.latlng); } ); ``` Leaflet deals with event listeners by reference, so if you want to add a listener and then remove it, define it as a function: ``` function onClick(e) { ... } map.on('click', onClick); map.off('click', onClick); ``` ### Methods | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Layer ----- A set of methods from the Layer base class that all Leaflet layers use. Inherits all methods, options and events from [`L.Evented`](#evented). ### Usage example ``` var layer = L.marker(latlng).addTo(map); layer.addTo(map); layer.remove(); ``` ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | #### Popup events | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | #### Tooltip events | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods Classes extending [`L.Layer`](#layer) will inherit the following methods: | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | #### Extension methods Every layer should extend from [`L.Layer`](#layer) and (re-)implement the following methods. | Method | Returns | Description | | --- | --- | --- | | `onAdd(<[Map](#map)> *map*)` | `this` | Should contain code that creates DOM elements for the layer, adds them to `map panes` where they should belong and puts listeners on relevant map events. Called on [`map.addLayer(layer)`](#map-addlayer). | | `onRemove(<[Map](#map)> *map*)` | `this` | Should contain all clean up code that removes the layer's elements from the DOM and removes listeners previously added in [`onAdd`](#layer-onadd). Called on [`map.removeLayer(layer)`](#map-removelayer). | | `getEvents()` | `Object` | This optional method should return an object like `{ viewreset: this._reset }` for [`addEventListener`](#evented-addeventlistener). The event handlers in this object will be automatically added and removed from the map with your layer. | | `getAttribution()` | `String` | This optional method should return a string containing HTML to be shown on the `Attribution control` whenever the layer is visible. | | `beforeAdd(<[Map](#map)> *map*)` | `this` | Optional method. Called on [`map.addLayer(layer)`](#map-addlayer), before the layer is added to the map, before events are initialized, without waiting until the map is in a usable state. Use for early initialization only. | #### Popup methods All layers share a set of methods convenient for binding popups to it. ``` var layer = L.Polygon(latlngs).bindPopup('Hi There!').addTo(map); layer.openPopup(); layer.closePopup(); ``` Popups will also be automatically opened when the layer is clicked on and closed when the layer is removed from the map or another popup is opened. | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | #### Tooltip methods All layers share a set of methods convenient for binding tooltips to it. ``` var layer = L.Polygon(latlngs).bindTooltip('Hi There!').addTo(map); layer.openTooltip(); layer.closeTooltip(); ``` | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Interactive layer ----------------- Some [`Layer`](#layer)s can be made interactive - when the user interacts with such a layer, mouse events like `click` and `mouseover` can be handled. Use the [event handling methods](#evented-method) to handle these events. ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `interactive` | `Boolean` | `true` | If `false`, the layer will not emit mouse events and will act as a part of the underlying map. | | `bubblingMouseEvents` | `Boolean` | `true` | When `true`, a mouse event on this layer will trigger the same event on the map (unless [`L.DomEvent.stopPropagation`](#domevent-stoppropagation) is used). | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events #### Mouse events | Event | Data | Description | | --- | --- | --- | | `click` | `[MouseEvent](#mouseevent)` | Fired when the user clicks (or taps) the layer. | | `dblclick` | `[MouseEvent](#mouseevent)` | Fired when the user double-clicks (or double-taps) the layer. | | `mousedown` | `[MouseEvent](#mouseevent)` | Fired when the user pushes the mouse button on the layer. | | `mouseup` | `[MouseEvent](#mouseevent)` | Fired when the user releases the mouse button pushed on the layer. | | `mouseover` | `[MouseEvent](#mouseevent)` | Fired when the mouse enters the layer. | | `mouseout` | `[MouseEvent](#mouseevent)` | Fired when the mouse leaves the layer. | | `contextmenu` | `[MouseEvent](#mouseevent)` | Fired when the user right-clicks on the layer, prevents default browser context menu from showing if there are listeners on this event. Also fired on mobile when the user holds a single touch for a second (also called long press). | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Control ------- L.Control is a base class for implementing map controls. Handles positioning. All other controls extend from this class. ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `position` | `String` | `'topright'` | The position of the control (one of the map corners). Possible values are `'topleft'`, `'topright'`, `'bottomleft'` or `'bottomright'` | ### Methods Classes extending L.Control will inherit the following methods: | Method | Returns | Description | | --- | --- | --- | | `getPosition()` | `string` | Returns the position of the control. | | `setPosition(<string> *position*)` | `this` | Sets the position of the control. | | `getContainer()` | `HTMLElement` | Returns the HTMLElement that contains the control. | | `addTo(<[Map](#map)> *map*)` | `this` | Adds the control to the given map. | | `remove()` | `this` | Removes the control from the map it is currently active on. | #### Extension methods Every control should extend from [`L.Control`](#control) and (re-)implement the following methods. | Method | Returns | Description | | --- | --- | --- | | `onAdd(<[Map](#map)> *map*)` | `HTMLElement` | Should return the container DOM element for the control and add listeners on relevant map events. Called on [`control.addTo(map)`](#control-addTo). | | `onRemove(<[Map](#map)> *map*)` | | Optional method. Should contain all clean up code that removes the listeners previously added in [`onAdd`](#control-onadd). Called on [`control.remove()`](#control-remove). | Handler ------- Abstract class for map interaction handlers ### Methods | Method | Returns | Description | | --- | --- | --- | | `enable()` | `this` | Enables the handler | | `disable()` | `this` | Disables the handler | | `enabled()` | `Boolean` | Returns `true` if the handler is enabled | #### Extension methods Classes inheriting from [`Handler`](#handler) must implement the two following methods: | Method | Returns | Description | | --- | --- | --- | | `addHooks()` | | Called when the handler is enabled, should add event hooks. | | `removeHooks()` | | Called when the handler is disabled, should remove the event hooks added previously. | ### Functions #### There is static function which can be called without instantiating L.Handler: | Function | Returns | Description | | --- | --- | --- | | `addTo(<[Map](#map)> *map*, <String> *name*)` | `this` | Adds a new Handler to the given map with the given name. | Projection ---------- An object with methods for projecting geographical coordinates of the world onto a flat surface (and back). See [Map projection](https://en.wikipedia.org/wiki/Map_projection). ### Methods | Method | Returns | Description | | --- | --- | --- | | `project(<[LatLng](#latlng)> *latlng*)` | `[Point](#point)` | Projects geographical coordinates into a 2D point. Only accepts actual [`L.LatLng`](#latlng) instances, not arrays. | | `unproject(<[Point](#point)> *point*)` | `[LatLng](#latlng)` | The inverse of `project`. Projects a 2D point into a geographical location. Only accepts actual [`L.Point`](#point) instances, not arrays. Note that the projection instances do not inherit from Leaflet's [`Class`](#class) object, and can't be instantiated. Also, new classes can't inherit from them, and methods can't be added to them with the `include` function. | ### Properties | Property | Type | Description | | --- | --- | --- | | `bounds` | `[Bounds](#bounds)` | The bounds (specified in CRS units) where the projection is valid | ### Defined projections Leaflet comes with a set of already defined Projections out of the box: | Projection | Description | | --- | --- | | `L.Projection.LonLat` | Equirectangular, or Plate Carree projection — the most simple projection, mostly used by GIS enthusiasts. Directly maps `x` as longitude, and `y` as latitude. Also suitable for flat worlds, e.g. game maps. Used by the `EPSG:4326` and `Simple` CRS. | | `L.Projection.Mercator` | Elliptical Mercator projection — more complex than Spherical Mercator. Assumes that Earth is an ellipsoid. Used by the EPSG:3395 CRS. | | `L.Projection.SphericalMercator` | Spherical Mercator projection — the most common projection for online maps, used by almost all free and commercial tile providers. Assumes that Earth is a sphere. Used by the `EPSG:3857` CRS. | CRS --- ### Methods | Method | Returns | Description | | --- | --- | --- | | `latLngToPoint(<[LatLng](#latlng)> *latlng*, <Number> *zoom*)` | `[Point](#point)` | Projects geographical coordinates into pixel coordinates for a given zoom. | | `pointToLatLng(<[Point](#point)> *point*, <Number> *zoom*)` | `[LatLng](#latlng)` | The inverse of `latLngToPoint`. Projects pixel coordinates on a given zoom into geographical coordinates. | | `project(<[LatLng](#latlng)> *latlng*)` | `[Point](#point)` | Projects geographical coordinates into coordinates in units accepted for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). | | `unproject(<[Point](#point)> *point*)` | `[LatLng](#latlng)` | Given a projected coordinate returns the corresponding LatLng. The inverse of `project`. | | `scale(<Number> *zoom*)` | `Number` | Returns the scale used when transforming projected coordinates into pixel coordinates for a particular zoom. For example, it returns `256 * 2^zoom` for Mercator-based CRS. | | `zoom(<Number> *scale*)` | `Number` | Inverse of `scale()`, returns the zoom level corresponding to a scale factor of `scale`. | | `getProjectedBounds(<Number> *zoom*)` | `[Bounds](#bounds)` | Returns the projection's bounds scaled and transformed for the provided `zoom`. | | `distance(<[LatLng](#latlng)> *latlng1*, <[LatLng](#latlng)> *latlng2*)` | `Number` | Returns the distance between two geographical coordinates. | | `wrapLatLng(<[LatLng](#latlng)> *latlng*)` | `[LatLng](#latlng)` | Returns a [`LatLng`](#latlng) where lat and lng has been wrapped according to the CRS's `wrapLat` and `wrapLng` properties, if they are outside the CRS's bounds. | | `wrapLatLngBounds(<[LatLngBounds](#latlngbounds)> *bounds*)` | `[LatLngBounds](#latlngbounds)` | Returns a [`LatLngBounds`](#latlngbounds) with the same size as the given one, ensuring that its center is within the CRS's bounds. Only accepts actual [`L.LatLngBounds`](#latlngbounds) instances, not arrays. | ### Properties | Property | Type | Description | | --- | --- | --- | | `code` | `String` | Standard code name of the CRS passed into WMS services (e.g. `'EPSG:3857'`) | | `wrapLng` | `Number[]` | An array of two numbers defining whether the longitude (horizontal) coordinate axis wraps around a given range and how. Defaults to `[-180, 180]` in most geographical CRSs. If `undefined`, the longitude axis does not wrap around. | | `wrapLat` | `Number[]` | Like `wrapLng`, but for the latitude (vertical) axis. | | `infinite` | `Boolean` | If true, the coordinate space will be unbounded (infinite in both axes) | ### Defined CRSs | CRS | Description | | --- | --- | | `L.CRS.EPSG3395` | Rarely used by some commercial tile providers. Uses Elliptical Mercator projection. | | `L.CRS.EPSG3857` | The most common CRS for online maps, used by almost all free and commercial tile providers. Uses Spherical Mercator projection. Set in by default in Map's `crs` option. | | `L.CRS.EPSG4326` | A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. Leaflet 1.0.x complies with the [TMS coordinate scheme for EPSG:4326](https://wiki.osgeo.org/wiki/Tile_Map_Service_Specification#global-geodetic), which is a breaking change from 0.7.x behaviour. If you are using a [`TileLayer`](#tilelayer) with this CRS, ensure that there are two 256x256 pixel tiles covering the whole earth at zoom level zero, and that the tile coordinate origin is (-180,+90), or (-180,-90) for [`TileLayer`](#tilelayer)s with [the `tms` option](#tilelayer-tms) set. | | `L.CRS.Earth` | Serves as the base for CRS that are global such that they cover the earth. Can only be used as the base for other CRS and cannot be used directly, since it does not have a `code`, `projection` or `transformation`. `distance()` returns meters. | | `L.CRS.Simple` | A simple CRS that maps longitude and latitude into `x` and `y` directly. May be used for maps of flat surfaces (e.g. game maps). Note that the `y` axis should still be inverted (going from bottom to top). `distance()` returns simple euclidean distance. | | `L.CRS.Base` | Object that defines coordinate reference systems for projecting geographical points into pixel (screen) coordinates and back (and to coordinates in other units for [WMS](https://en.wikipedia.org/wiki/Web_Map_Service) services). See [spatial reference system](https://en.wikipedia.org/wiki/Spatial_reference_system). Leaflet defines the most usual CRSs by default. If you want to use a CRS not defined by default, take a look at the [Proj4Leaflet](https://github.com/kartena/Proj4Leaflet) plugin. Note that the CRS instances do not inherit from Leaflet's [`Class`](#class) object, and can't be instantiated. Also, new classes can't inherit from them, and methods can't be added to them with the `include` function. | Renderer -------- Base class for vector renderer implementations ([`SVG`](#svg), [`Canvas`](#canvas)). Handles the DOM container of the renderer, its bounds, and its zoom animation. A [`Renderer`](#renderer) works as an implicit layer group for all [`Path`](#path)s - the renderer itself can be added or removed to the map. All paths use a renderer, which can be implicit (the map will decide the type of renderer and use it automatically) or explicit (using the [`renderer`](#path-renderer) option of the path). Do not use this class directly, use [`SVG`](#svg) and [`Canvas`](#canvas) instead. ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `padding` | `Number` | `0.1` | How much to extend the clip area around the map view (relative to its size) e.g. 0.1 would be 10% of map view in each direction | Options inherited from [Layer](#layer) | Option | Type | Default | Description | | --- | --- | --- | --- | | `pane` | `String` | `'overlayPane'` | By default the layer will be added to the map's [overlay pane](#map-overlaypane). Overriding this option will cause the layer to be placed on another pane by default. | | `attribution` | `String` | `null` | String to be shown in the attribution control, e.g. "© OpenStreetMap contributors". It describes the layer data and is often a legal obligation towards copyright holders and tile providers. | ### Events | Event | Data | Description | | --- | --- | --- | | `update` | `[Event](#event)` | Fired when the renderer updates its bounds, center and zoom, for example when its map has moved | Events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `add` | `[Event](#event)` | Fired after the layer is added to a map | | `remove` | `[Event](#event)` | Fired after the layer is removed from a map | Popup events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `popupopen` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is opened | | `popupclose` | `[PopupEvent](#popupevent)` | Fired when a popup bound to this layer is closed | Tooltip events inherited from [Layer](#layer) | Event | Data | Description | | --- | --- | --- | | `tooltipopen` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is opened. | | `tooltipclose` | `[TooltipEvent](#tooltipevent)` | Fired when a tooltip bound to this layer is closed. | ### Methods Methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `addTo(<Map|LayerGroup> *map*)` | `this` | Adds the layer to the given map or layer group. | | `remove()` | `this` | Removes the layer from the map it is currently active on. | | `removeFrom(<[Map](#map)> *map*)` | `this` | Removes the layer from the given map | | `removeFrom(<[LayerGroup](#layergroup)> *group*)` | `this` | Removes the layer from the given [`LayerGroup`](#layergroup) | | `getPane(<String> *name?*)` | `HTMLElement` | Returns the `HTMLElement` representing the named pane on the map. If `name` is omitted, returns the pane for this layer. | | `getAttribution()` | `String` | Used by the `attribution control`, returns the [attribution option](#gridlayer-attribution). | Popup methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindPopup(<String|HTMLElement|Function|Popup> *content*, <[Popup options](#popup-option)> *options?*)` | `this` | Binds a popup to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindPopup()` | `this` | Removes the popup previously bound with `bindPopup`. | | `openPopup(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound popup at the specified `latlng` or at the default popup anchor if no `latlng` is passed. | | `closePopup()` | `this` | Closes the popup bound to this layer if it is open. | | `togglePopup()` | `this` | Opens or closes the popup bound to this layer depending on its current state. | | `isPopupOpen()` | `boolean` | Returns `true` if the popup bound to this layer is currently open. | | `setPopupContent(<String|HTMLElement|Popup> *content*)` | `this` | Sets the content of the popup bound to this layer. | | `getPopup()` | `[Popup](#popup)` | Returns the popup bound to this layer. | Tooltip methods inherited from [Layer](#layer) | Method | Returns | Description | | --- | --- | --- | | `bindTooltip(<String|HTMLElement|Function|Tooltip> *content*, <[Tooltip options](#tooltip-option)> *options?*)` | `this` | Binds a tooltip to the layer with the passed `content` and sets up the necessary event listeners. If a `Function` is passed it will receive the layer as the first argument and should return a `String` or `HTMLElement`. | | `unbindTooltip()` | `this` | Removes the tooltip previously bound with `bindTooltip`. | | `openTooltip(<[LatLng](#latlng)> *latlng?*)` | `this` | Opens the bound tooltip at the specified `latlng` or at the default tooltip anchor if no `latlng` is passed. | | `closeTooltip()` | `this` | Closes the tooltip bound to this layer if it is open. | | `toggleTooltip()` | `this` | Opens or closes the tooltip bound to this layer depending on its current state. | | `isTooltipOpen()` | `boolean` | Returns `true` if the tooltip bound to this layer is currently open. | | `setTooltipContent(<String|HTMLElement|Tooltip> *content*)` | `this` | Sets the content of the tooltip bound to this layer. | | `getTooltip()` | `[Tooltip](#tooltip)` | Returns the tooltip bound to this layer. | Methods inherited from [Evented](#evented) | Method | Returns | Description | | --- | --- | --- | | `on(<String> *type*, <Function> *fn*, <Object> *context?*)` | `this` | Adds a listener function (`fn`) to a particular event type of the object. You can optionally specify the context of the listener (object the this keyword will point to). You can also pass several space-separated types (e.g. `'click dblclick'`). | | `on(<Object> *eventMap*)` | `this` | Adds a set of type/listener pairs, e.g. `{click: onClick, mousemove: onMouseMove}` | | `off(<String> *type*, <Function> *fn?*, <Object> *context?*)` | `this` | Removes a previously added listener function. If no function is specified, it will remove all the listeners of that particular event from the object. Note that if you passed a custom context to `on`, you must pass the same context to `off` in order to remove the listener. | | `off(<Object> *eventMap*)` | `this` | Removes a set of type/listener pairs. | | `off()` | `this` | Removes all listeners to all events on the object. This includes implicitly attached events. | | `fire(<String> *type*, <Object> *data?*, <Boolean> *propagate?*)` | `this` | Fires an event of the specified type. You can optionally provide a data object — the first argument of the listener function will contain its properties. The event can optionally be propagated to event parents. | | `listens(<String> *type*, <Boolean> *propagate?*)` | `Boolean` | Returns `true` if a particular event type has any listeners attached to it. The verification can optionally be propagated, it will return `true` if parents have the listener attached to it. | | `once(*…*)` | `this` | Behaves as [`on(…)`](#evented-on), except the listener will only get fired once and then removed. | | `addEventParent(<[Evented](#evented)> *obj*)` | `this` | Adds an event parent - an [`Evented`](#evented) that will receive propagated events | | `removeEventParent(<[Evented](#evented)> *obj*)` | `this` | Removes an event parent, so it will stop receiving propagated events | | `addEventListener(*…*)` | `this` | Alias to [`on(…)`](#evented-on) | | `removeEventListener(*…*)` | `this` | Alias to [`off(…)`](#evented-off) | | `clearAllEventListeners(*…*)` | `this` | Alias to [`off()`](#evented-off) | | `addOneTimeEventListener(*…*)` | `this` | Alias to [`once(…)`](#evented-once) | | `fireEvent(*…*)` | `this` | Alias to [`fire(…)`](#evented-fire) | | `hasEventListeners(*…*)` | `Boolean` | Alias to [`listens(…)`](#evented-listens) | Event objects ------------- Whenever a class inheriting from [`Evented`](#evented) fires an event, a listener function will be called with an event argument, which is a plain object containing information about the event. For example: ``` map.on('click', function(ev) { alert(ev.latlng); // ev is an event object (MouseEvent in this case) }); ``` The information available depends on the event type: ### Event The base event object. All other event objects contain these properties too. | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | ### KeyboardEvent | Property | Type | Description | | --- | --- | --- | | `originalEvent` | `DOMEvent` | The original [DOM `KeyboardEvent`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent) that triggered this Leaflet event. | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | ### MouseEvent | Property | Type | Description | | --- | --- | --- | | `latlng` | `[LatLng](#latlng)` | The geographical point where the mouse event occurred. | | `layerPoint` | `[Point](#point)` | Pixel coordinates of the point where the mouse event occurred relative to the map layer. | | `containerPoint` | `[Point](#point)` | Pixel coordinates of the point where the mouse event occurred relative to the map сontainer. | | `originalEvent` | `DOMEvent` | The original [DOM `MouseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent) or [DOM `TouchEvent`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent) that triggered this Leaflet event. | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | ### LocationEvent | Property | Type | Description | | --- | --- | --- | | `latlng` | `[LatLng](#latlng)` | Detected geographical location of the user. | | `bounds` | `[LatLngBounds](#latlngbounds)` | Geographical bounds of the area user is located in (with respect to the accuracy of location). | | `accuracy` | `Number` | Accuracy of location in meters. | | `altitude` | `Number` | Height of the position above the WGS84 ellipsoid in meters. | | `altitudeAccuracy` | `Number` | Accuracy of altitude in meters. | | `heading` | `Number` | The direction of travel in degrees counting clockwise from true North. | | `speed` | `Number` | Current velocity in meters per second. | | `timestamp` | `Number` | The time when the position was acquired. | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | ### ErrorEvent | Property | Type | Description | | --- | --- | --- | | `message` | `String` | Error message. | | `code` | `Number` | Error code (if applicable). | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | ### LayerEvent | Property | Type | Description | | --- | --- | --- | | `layer` | `[Layer](#layer)` | The layer that was added or removed. | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | ### LayersControlEvent | Property | Type | Description | | --- | --- | --- | | `layer` | `[Layer](#layer)` | The layer that was added or removed. | | `name` | `String` | The name of the layer that was added or removed. | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | ### TileEvent | Property | Type | Description | | --- | --- | --- | | `tile` | `HTMLElement` | The tile element (image). | | `coords` | `[Point](#point)` | Point object with the tile's `x`, `y`, and `z` (zoom level) coordinates. | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | ### TileErrorEvent | Property | Type | Description | | --- | --- | --- | | `tile` | `HTMLElement` | The tile element (image). | | `coords` | `[Point](#point)` | Point object with the tile's `x`, `y`, and `z` (zoom level) coordinates. | | `error` | `*` | Error passed to the tile's `done()` callback. | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | ### ResizeEvent | Property | Type | Description | | --- | --- | --- | | `oldSize` | `[Point](#point)` | The old size before resize event. | | `newSize` | `[Point](#point)` | The new size after the resize event. | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | ### GeoJSONEvent | Property | Type | Description | | --- | --- | --- | | `layer` | `[Layer](#layer)` | The layer for the GeoJSON feature that is being added to the map. | | `properties` | `Object` | GeoJSON properties of the feature. | | `geometryType` | `String` | GeoJSON geometry type of the feature. | | `id` | `String` | GeoJSON ID of the feature (if present). | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | ### PopupEvent | Property | Type | Description | | --- | --- | --- | | `popup` | `[Popup](#popup)` | The popup that was opened or closed. | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | ### TooltipEvent | Property | Type | Description | | --- | --- | --- | | `tooltip` | `[Tooltip](#tooltip)` | The tooltip that was opened or closed. | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | ### DragEndEvent | Property | Type | Description | | --- | --- | --- | | `distance` | `Number` | The distance in pixels the draggable element was moved by. | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | ### ZoomAnimEvent | Property | Type | Description | | --- | --- | --- | | `center` | `[LatLng](#latlng)` | The current center of the map | | `zoom` | `Number` | The current zoom level of the map | | `noUpdate` | `Boolean` | Whether layers should update their contents due to this event | Properties inherited from [Event](#event) | Property | Type | Description | | --- | --- | --- | | `type` | `String` | The event type (e.g. `'click'`). | | `target` | `Object` | The object that fired the event. For propagated events, the last object in the propagation chain that fired the event. | | `sourceTarget` | `Object` | The object that originally fired the event. For non-propagated events, this will be the same as the `target`. | | `propagatedFrom` | `Object` | For propagated events, the last object that propagated the event to its event parent. | | `layer` | `Object` | **Deprecated.** The same as `propagatedFrom`. | Global Switches --------------- Global switches are created for rare cases and generally make Leaflet to not detect a particular browser feature even if it's there. You need to set the switch as a global variable to true before including Leaflet on the page, like this: ``` <script>L_NO_TOUCH = true;</script> <script src="leaflet.js"></script> ``` | Switch | Description | | --- | --- | | `L_NO_TOUCH` | Forces Leaflet to not use touch events even if it detects them. | | `L_DISABLE_3D` | Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning (which may cause glitches in some rare environments) even if they're supported. | noConflict ---------- This method restores the `L` global variable to the original value it had before Leaflet inclusion, and returns the real Leaflet namespace so you can put it elsewhere, like this: ``` <script src='libs/l.js'> <!-- L points to some other library --> <script src='leaflet.js'> <!-- you include Leaflet, it replaces the L variable to Leaflet namespace --> <script> var Leaflet = L.noConflict(); // now L points to that other library again, and you can use Leaflet.Map etc. </script> ``` version ------- A constant that represents the Leaflet version in use. ``` L.version; // contains "1.0.0" (or whatever version is currently in use) ```
programming_docs
requests Developer Interface Developer Interface =================== This part of the documentation covers all the interfaces of Requests. For parts where Requests depends on external libraries, we document the most important right here and provide links to the canonical documentation. Main Interface -------------- All of Requests’ functionality can be accessed by these 7 methods. They all return an instance of the [`Response`](#requests.Response "requests.Response") object. requests.request(*method*, *url*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/api/#request) Constructs and sends a [`Request`](#requests.Request "requests.Request"). Parameters * **method** – method for the new [`Request`](#requests.Request "requests.Request") object: `GET`, `OPTIONS`, `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`. * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **params** – (optional) Dictionary, list of tuples or bytes to send in the query string for the [`Request`](#requests.Request "requests.Request"). * **data** – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the [`Request`](#requests.Request "requests.Request"). * **json** – (optional) A JSON serializable Python object to send in the body of the [`Request`](#requests.Request "requests.Request"). * **headers** – (optional) Dictionary of HTTP Headers to send with the [`Request`](#requests.Request "requests.Request"). * **cookies** – (optional) Dict or CookieJar object to send with the [`Request`](#requests.Request "requests.Request"). * **files** – (optional) Dictionary of `'name': file-like-objects` (or `{'name': file-tuple}`) for multipart encoding upload. `file-tuple` can be a 2-tuple `('filename', fileobj)`, 3-tuple `('filename', fileobj, 'content_type')` or a 4-tuple `('filename', fileobj, 'content_type', custom_headers)`, where `'content-type'` is a string defining the content type of the given file and `custom_headers` a dict-like object containing additional headers to add for the file. * **auth** – (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. * **timeout** ([float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)") *or* [tuple](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)")) – (optional) How many seconds to wait for the server to send data before giving up, as a float, or a [(connect timeout, read timeout)](https://requests.readthedocs.io/en/latest/user/advanced/#timeouts) tuple. * **allow\_redirects** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to `True`. * **proxies** – (optional) Dictionary mapping protocol to the URL of the proxy. * **verify** – (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to `True`. * **stream** – (optional) if `False`, the response content will be immediately downloaded. * **cert** – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair. Returns [`Response`](#requests.Response "requests.Response") object Return type [requests.Response](#requests.Response "requests.Response") Usage: ``` >>> import requests >>> req = requests.request('GET', 'https://httpbin.org/get') >>> req <Response [200]> ``` requests.head(*url*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/api/#head) Sends a HEAD request. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **\*\*kwargs** – Optional arguments that `request` takes. If `allow_redirects` is not provided, it will be set to `False` (as opposed to the default [`request`](#requests.request "requests.request") behavior). Returns [`Response`](#requests.Response "requests.Response") object Return type [requests.Response](#requests.Response "requests.Response") requests.get(*url*, *params=None*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/api/#get) Sends a GET request. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **params** – (optional) Dictionary, list of tuples or bytes to send in the query string for the [`Request`](#requests.Request "requests.Request"). * **\*\*kwargs** – Optional arguments that `request` takes. Returns [`Response`](#requests.Response "requests.Response") object Return type [requests.Response](#requests.Response "requests.Response") requests.post(*url*, *data=None*, *json=None*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/api/#post) Sends a POST request. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **data** – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the [`Request`](#requests.Request "requests.Request"). * **json** – (optional) json data to send in the body of the [`Request`](#requests.Request "requests.Request"). * **\*\*kwargs** – Optional arguments that `request` takes. Returns [`Response`](#requests.Response "requests.Response") object Return type [requests.Response](#requests.Response "requests.Response") requests.put(*url*, *data=None*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/api/#put) Sends a PUT request. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **data** – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the [`Request`](#requests.Request "requests.Request"). * **json** – (optional) json data to send in the body of the [`Request`](#requests.Request "requests.Request"). * **\*\*kwargs** – Optional arguments that `request` takes. Returns [`Response`](#requests.Response "requests.Response") object Return type [requests.Response](#requests.Response "requests.Response") requests.patch(*url*, *data=None*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/api/#patch) Sends a PATCH request. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **data** – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the [`Request`](#requests.Request "requests.Request"). * **json** – (optional) json data to send in the body of the [`Request`](#requests.Request "requests.Request"). * **\*\*kwargs** – Optional arguments that `request` takes. Returns [`Response`](#requests.Response "requests.Response") object Return type [requests.Response](#requests.Response "requests.Response") requests.delete(*url*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/api/#delete) Sends a DELETE request. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **\*\*kwargs** – Optional arguments that `request` takes. Returns [`Response`](#requests.Response "requests.Response") object Return type [requests.Response](#requests.Response "requests.Response") Exceptions ---------- *exception* requests.RequestException(*\*args*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/#RequestException) There was an ambiguous exception that occurred while handling your request. *exception* requests.ConnectionError(*\*args*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/#ConnectionError) A Connection error occurred. *exception* requests.HTTPError(*\*args*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/#HTTPError) An HTTP error occurred. *exception* requests.URLRequired(*\*args*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/#URLRequired) A valid URL is required to make a request. *exception* requests.TooManyRedirects(*\*args*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/#TooManyRedirects) Too many redirects. *exception* requests.ConnectTimeout(*\*args*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/#ConnectTimeout) The request timed out while trying to connect to the remote server. Requests that produced this error are safe to retry. *exception* requests.ReadTimeout(*\*args*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/#ReadTimeout) The server did not send any data in the allotted amount of time. *exception* requests.Timeout(*\*args*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/exceptions/#Timeout) The request timed out. Catching this error will catch both [`ConnectTimeout`](#requests.ConnectTimeout "requests.exceptions.ConnectTimeout") and [`ReadTimeout`](#requests.ReadTimeout "requests.exceptions.ReadTimeout") errors. Request Sessions ---------------- *class* requests.Session[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session) A Requests session. Provides cookie persistence, connection-pooling, and configuration. Basic Usage: ``` >>> import requests >>> s = requests.Session() >>> s.get('https://httpbin.org/get') <Response [200]> ``` Or as a context manager: ``` >>> with requests.Session() as s: ... s.get('https://httpbin.org/get') <Response [200]> ``` auth Default Authentication tuple or object to attach to [`Request`](#requests.Request "requests.Request"). cert SSL client certificate default, if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair. close()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.close) Closes all adapters and as such the session cookies A CookieJar containing all currently outstanding cookies set on this session. By default it is a [`RequestsCookieJar`](#requests.cookies.RequestsCookieJar "requests.cookies.RequestsCookieJar"), but may be any other `cookielib.CookieJar` compatible object. delete(*url*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.delete) Sends a DELETE request. Returns [`Response`](#requests.Response "requests.Response") object. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **\*\*kwargs** – Optional arguments that `request` takes. Return type [requests.Response](#requests.Response "requests.Response") get(*url*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.get) Sends a GET request. Returns [`Response`](#requests.Response "requests.Response") object. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **\*\*kwargs** – Optional arguments that `request` takes. Return type [requests.Response](#requests.Response "requests.Response") get\_adapter(*url*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.get_adapter) Returns the appropriate connection adapter for the given URL. Return type [requests.adapters.BaseAdapter](#requests.adapters.BaseAdapter "requests.adapters.BaseAdapter") get\_redirect\_target(*resp*) Receives a Response. Returns a redirect URI or `None` head(*url*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.head) Sends a HEAD request. Returns [`Response`](#requests.Response "requests.Response") object. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **\*\*kwargs** – Optional arguments that `request` takes. Return type [requests.Response](#requests.Response "requests.Response") headers A case-insensitive dictionary of headers to be sent on each [`Request`](#requests.Request "requests.Request") sent from this [`Session`](#requests.Session "requests.Session"). hooks Event-handling hooks. max\_redirects Maximum number of redirects allowed. If the request exceeds this limit, a [`TooManyRedirects`](#requests.TooManyRedirects "requests.TooManyRedirects") exception is raised. This defaults to requests.models.DEFAULT\_REDIRECT\_LIMIT, which is 30. merge\_environment\_settings(*url*, *proxies*, *stream*, *verify*, *cert*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.merge_environment_settings) Check the environment and merge it with some settings. Return type [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") mount(*prefix*, *adapter*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.mount) Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. options(*url*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.options) Sends a OPTIONS request. Returns [`Response`](#requests.Response "requests.Response") object. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **\*\*kwargs** – Optional arguments that `request` takes. Return type [requests.Response](#requests.Response "requests.Response") params Dictionary of querystring data to attach to each [`Request`](#requests.Request "requests.Request"). The dictionary values may be lists for representing multivalued query parameters. patch(*url*, *data=None*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.patch) Sends a PATCH request. Returns [`Response`](#requests.Response "requests.Response") object. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **data** – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the [`Request`](#requests.Request "requests.Request"). * **\*\*kwargs** – Optional arguments that `request` takes. Return type [requests.Response](#requests.Response "requests.Response") post(*url*, *data=None*, *json=None*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.post) Sends a POST request. Returns [`Response`](#requests.Response "requests.Response") object. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **data** – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the [`Request`](#requests.Request "requests.Request"). * **json** – (optional) json to send in the body of the [`Request`](#requests.Request "requests.Request"). * **\*\*kwargs** – Optional arguments that `request` takes. Return type [requests.Response](#requests.Response "requests.Response") prepare\_request(*request*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.prepare_request) Constructs a [`PreparedRequest`](#requests.PreparedRequest "requests.PreparedRequest") for transmission and returns it. The [`PreparedRequest`](#requests.PreparedRequest "requests.PreparedRequest") has settings merged from the [`Request`](#requests.Request "requests.Request") instance and those of the [`Session`](#requests.Session "requests.Session"). Parameters **request** – [`Request`](#requests.Request "requests.Request") instance to prepare with this session’s settings. Return type [requests.PreparedRequest](#requests.PreparedRequest "requests.PreparedRequest") proxies Dictionary mapping protocol or protocol and host to the URL of the proxy (e.g. {‘http’: ‘foo.bar:3128’, ‘http://host.name’: ‘foo.bar:4012’}) to be used on each [`Request`](#requests.Request "requests.Request"). put(*url*, *data=None*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.put) Sends a PUT request. Returns [`Response`](#requests.Response "requests.Response") object. Parameters * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **data** – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the [`Request`](#requests.Request "requests.Request"). * **\*\*kwargs** – Optional arguments that `request` takes. Return type [requests.Response](#requests.Response "requests.Response") rebuild\_auth(*prepared\_request*, *response*) When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. rebuild\_method(*prepared\_request*, *response*) When being redirected we may want to change the method of the request based on certain specs or browser behavior. rebuild\_proxies(*prepared\_request*, *proxies*) This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO\_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. Return type [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") request(*method*, *url*, *params=None*, *data=None*, *headers=None*, *cookies=None*, *files=None*, *auth=None*, *timeout=None*, *allow\_redirects=True*, *proxies=None*, *hooks=None*, *stream=None*, *verify=None*, *cert=None*, *json=None*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.request) Constructs a [`Request`](#requests.Request "requests.Request"), prepares it and sends it. Returns [`Response`](#requests.Response "requests.Response") object. Parameters * **method** – method for the new [`Request`](#requests.Request "requests.Request") object. * **url** – URL for the new [`Request`](#requests.Request "requests.Request") object. * **params** – (optional) Dictionary or bytes to be sent in the query string for the [`Request`](#requests.Request "requests.Request"). * **data** – (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the [`Request`](#requests.Request "requests.Request"). * **json** – (optional) json to send in the body of the [`Request`](#requests.Request "requests.Request"). * **headers** – (optional) Dictionary of HTTP Headers to send with the [`Request`](#requests.Request "requests.Request"). * **cookies** – (optional) Dict or CookieJar object to send with the [`Request`](#requests.Request "requests.Request"). * **files** – (optional) Dictionary of `'filename': file-like-objects` for multipart encoding upload. * **auth** – (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. * **timeout** ([float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)") *or* [tuple](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)")) – (optional) How long to wait for the server to send data before giving up, as a float, or a [(connect timeout, read timeout)](https://requests.readthedocs.io/en/latest/user/advanced/#timeouts) tuple. * **allow\_redirects** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – (optional) Set to True by default. * **proxies** – (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. * **stream** – (optional) whether to immediately download the response content. Defaults to `False`. * **verify** – (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to `True`. When set to `False`, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to `False` may be useful during local development or testing. * **cert** – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair. Return type [requests.Response](#requests.Response "requests.Response") resolve\_redirects(*resp*, *req*, *stream=False*, *timeout=None*, *verify=True*, *cert=None*, *proxies=None*, *yield\_requests=False*, *\*\*adapter\_kwargs*) Receives a Response. Returns a generator of Responses or Requests. send(*request*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/sessions/#Session.send) Send a given PreparedRequest. Return type [requests.Response](#requests.Response "requests.Response") should\_strip\_auth(*old\_url*, *new\_url*) Decide whether Authorization header should be removed when redirecting stream Stream response content default. trust\_env Trust environment settings for proxy configuration, default authentication and similar. verify SSL Verification default. Defaults to `True`, requiring requests to verify the TLS certificate at the remote end. If verify is set to `False`, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Only set this to `False` for testing. Lower-Level Classes ------------------- *class* requests.Request(*method=None*, *url=None*, *headers=None*, *files=None*, *data=None*, *params=None*, *auth=None*, *cookies=None*, *hooks=None*, *json=None*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#Request) A user-created [`Request`](#requests.Request "requests.Request") object. Used to prepare a [`PreparedRequest`](#requests.PreparedRequest "requests.PreparedRequest"), which is sent to the server. Parameters * **method** – HTTP method to use. * **url** – URL to send. * **headers** – dictionary of headers to send. * **files** – dictionary of {filename: fileobject} files to multipart upload. * **data** – the body to attach to the request. If a dictionary or list of tuples `[(key, value)]` is provided, form-encoding will take place. * **json** – json for the body to attach to the request (if files or data is not specified). * **params** – URL parameters to append to the URL. If a dictionary or list of tuples `[(key, value)]` is provided, form-encoding will take place. * **auth** – Auth handler or (user, pass) tuple. * **cookies** – dictionary or CookieJar of cookies to attach to this request. * **hooks** – dictionary of callback hooks, for internal usage. Usage: ``` >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> req.prepare() <PreparedRequest [GET]> ``` deregister\_hook(*event*, *hook*) Deregister a previously registered hook. Returns True if the hook existed, False if not. prepare()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#Request.prepare) Constructs a [`PreparedRequest`](#requests.PreparedRequest "requests.PreparedRequest") for transmission and returns it. register\_hook(*event*, *hook*) Properly register a hook. *class* requests.Response[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#Response) The [`Response`](#requests.Response "requests.Response") object, which contains a server’s response to an HTTP request. *property* apparent\_encoding The apparent encoding, provided by the charset\_normalizer or chardet libraries. close()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#Response.close) Releases the connection back to the pool. Once this method has been called the underlying `raw` object must not be accessed again. *Note: Should not normally need to be called explicitly.* *property* content Content of the response, in bytes. cookies A CookieJar of Cookies the server sent back. elapsed The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the `stream` keyword argument. encoding Encoding to decode with when accessing r.text. headers Case-insensitive Dictionary of Response Headers. For example, `headers['content-encoding']` will return the value of a `'Content-Encoding'` response header. history A list of [`Response`](#requests.Response "requests.Response") objects from the history of the Request. Any redirect responses will end up here. The list is sorted from the oldest to the most recent request. *property* is\_permanent\_redirect True if this Response one of the permanent versions of redirect. *property* is\_redirect True if this Response is a well-formed HTTP redirect that could have been processed automatically (by [`Session.resolve_redirects`](#requests.Session.resolve_redirects "requests.Session.resolve_redirects")). iter\_content(*chunk\_size=1*, *decode\_unicode=False*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#Response.iter_content) Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. chunk\_size must be of type int or None. A value of None will function differently depending on the value of `stream`. stream=True will read data as it arrives in whatever size the chunks are received. If stream=False, data is returned as a single chunk. If decode\_unicode is True, content will be decoded using the best available encoding based on the response. iter\_lines(*chunk\_size=512*, *decode\_unicode=False*, *delimiter=None*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#Response.iter_lines) Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. Note This method is not reentrant safe. json(*\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#Response.json) Returns the json-encoded content of a response, if any. Parameters **\*\*kwargs** – Optional arguments that `json.loads` takes. Raises **requests.exceptions.JSONDecodeError** – If the response body does not contain valid json. *property* links Returns the parsed header links of the response, if any. *property* next Returns a PreparedRequest for the next request in a redirect chain, if there is one. *property* ok Returns True if [`status_code`](#requests.Response.status_code "requests.Response.status_code") is less than 400, False if not. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is **not** a check to see if the response code is `200 OK`. raise\_for\_status()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#Response.raise_for_status) Raises [`HTTPError`](#requests.HTTPError "requests.HTTPError"), if one occurred. raw File-like object representation of response (for advanced usage). Use of `raw` requires that `stream=True` be set on the request. This requirement does not apply for use internally to Requests. reason Textual reason of responded HTTP Status, e.g. “Not Found” or “OK”. request The [`PreparedRequest`](#requests.PreparedRequest "requests.PreparedRequest") object to which this is a response. status\_code Integer Code of responded HTTP Status, e.g. 404 or 200. *property* text Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using `charset_normalizer` or `chardet`. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set `r.encoding` appropriately before accessing this property. url Final URL location of Response. Lower-Lower-Level Classes ------------------------- *class* requests.PreparedRequest[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#PreparedRequest) The fully mutable [`PreparedRequest`](#requests.PreparedRequest "requests.PreparedRequest") object, containing the exact bytes that will be sent to the server. Instances are generated from a [`Request`](#requests.Request "requests.Request") object, and should not be instantiated manually; doing so may produce undesirable effects. Usage: ``` >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> r = req.prepare() >>> r <PreparedRequest [GET]> >>> s = requests.Session() >>> s.send(r) <Response [200]> ``` body request body to send to the server. deregister\_hook(*event*, *hook*) Deregister a previously registered hook. Returns True if the hook existed, False if not. headers dictionary of HTTP headers. hooks dictionary of callback hooks, for internal usage. method HTTP verb to send to the server. *property* path\_url Build the path URL to use. prepare(*method=None*, *url=None*, *headers=None*, *files=None*, *data=None*, *params=None*, *auth=None*, *cookies=None*, *hooks=None*, *json=None*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#PreparedRequest.prepare) Prepares the entire request with the given parameters. prepare\_auth(*auth*, *url=''*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#PreparedRequest.prepare_auth) Prepares the given HTTP auth data. prepare\_body(*data*, *files*, *json=None*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#PreparedRequest.prepare_body) Prepares the given HTTP body data. prepare\_content\_length(*body*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#PreparedRequest.prepare_content_length) Prepare Content-Length header based on request method and body prepare\_cookies(*cookies*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#PreparedRequest.prepare_cookies) Prepares the given HTTP cookie data. This function eventually generates a `Cookie` header from the given cookies using cookielib. Due to cookielib’s design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the [`PreparedRequest`](#requests.PreparedRequest "requests.PreparedRequest") object. Any subsequent calls to `prepare_cookies` will have no actual effect, unless the “Cookie” header is removed beforehand. prepare\_headers(*headers*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#PreparedRequest.prepare_headers) Prepares the given HTTP headers. prepare\_hooks(*hooks*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#PreparedRequest.prepare_hooks) Prepares the given hooks. prepare\_method(*method*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#PreparedRequest.prepare_method) Prepares the given HTTP method. prepare\_url(*url*, *params*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/models/#PreparedRequest.prepare_url) Prepares the given HTTP URL. register\_hook(*event*, *hook*) Properly register a hook. url HTTP URL to send the request to. *class* requests.adapters.BaseAdapter[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#BaseAdapter) The Base Transport Adapter close()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#BaseAdapter.close) Cleans up adapter specific items. send(*request*, *stream=False*, *timeout=None*, *verify=True*, *cert=None*, *proxies=None*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#BaseAdapter.send) Sends PreparedRequest object. Returns Response object. Parameters * **request** – The `PreparedRequest` being sent. * **stream** – (optional) Whether to stream the request content. * **timeout** ([float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)") *or* [tuple](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)")) – (optional) How long to wait for the server to send data before giving up, as a float, or a [(connect timeout, read timeout)](https://requests.readthedocs.io/en/latest/user/advanced/#timeouts) tuple. * **verify** – (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use * **cert** – (optional) Any user-provided SSL certificate to be trusted. * **proxies** – (optional) The proxies dictionary to apply to the request. *class* requests.adapters.HTTPAdapter(*pool\_connections=10*, *pool\_maxsize=10*, *max\_retries=0*, *pool\_block=False*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#HTTPAdapter) The built-in HTTP Adapter for urllib3. Provides a general-case interface for Requests sessions to contact HTTP and HTTPS urls by implementing the Transport Adapter interface. This class will usually be created by the `Session` class under the covers. Parameters * **pool\_connections** – The number of urllib3 connection pools to cache. * **pool\_maxsize** – The maximum number of connections to save in the pool. * **max\_retries** – The maximum number of retries each connection should attempt. Note, this applies only to failed DNS lookups, socket connections and connection timeouts, never to requests where data has made it to the server. By default, Requests does not retry failed connections. If you need granular control over the conditions under which we retry a request, import urllib3’s `Retry` class and pass that instead. * **pool\_block** – Whether the connection pool should block for connections. Usage: ``` >>> import requests >>> s = requests.Session() >>> a = requests.adapters.HTTPAdapter(max_retries=3) >>> s.mount('http://', a) ``` add\_headers(*request*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#HTTPAdapter.add_headers) Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the [`HTTPAdapter`](#requests.adapters.HTTPAdapter "requests.adapters.HTTPAdapter"). This should not be called from user code, and is only exposed for use when subclassing the [`HTTPAdapter`](#requests.adapters.HTTPAdapter "requests.adapters.HTTPAdapter"). Parameters * **request** – The `PreparedRequest` to add headers to. * **kwargs** – The keyword arguments from the call to send(). build\_response(*req*, *resp*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#HTTPAdapter.build_response) Builds a [`Response`](#requests.Response "requests.Response") object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the [`HTTPAdapter`](#requests.adapters.HTTPAdapter "requests.adapters.HTTPAdapter") Parameters * **req** – The `PreparedRequest` used to generate the response. * **resp** – The urllib3 response object. Return type [requests.Response](#requests.Response "requests.Response") cert\_verify(*conn*, *url*, *verify*, *cert*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#HTTPAdapter.cert_verify) Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the [`HTTPAdapter`](#requests.adapters.HTTPAdapter "requests.adapters.HTTPAdapter"). Parameters * **conn** – The urllib3 connection object associated with the cert. * **url** – The requested URL. * **verify** – Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use * **cert** – The SSL certificate to verify. close()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#HTTPAdapter.close) Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections. get\_connection(*url*, *proxies=None*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#HTTPAdapter.get_connection) Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the [`HTTPAdapter`](#requests.adapters.HTTPAdapter "requests.adapters.HTTPAdapter"). Parameters * **url** – The URL to connect to. * **proxies** – (optional) A Requests-style dictionary of proxies used on this request. Return type urllib3.ConnectionPool init\_poolmanager(*connections*, *maxsize*, *block=False*, *\*\*pool\_kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#HTTPAdapter.init_poolmanager) Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the [`HTTPAdapter`](#requests.adapters.HTTPAdapter "requests.adapters.HTTPAdapter"). Parameters * **connections** – The number of urllib3 connection pools to cache. * **maxsize** – The maximum number of connections to save in the pool. * **block** – Block when no free connections are available. * **pool\_kwargs** – Extra keyword arguments used to initialize the Pool Manager. proxy\_headers(*proxy*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#HTTPAdapter.proxy_headers) Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the [`HTTPAdapter`](#requests.adapters.HTTPAdapter "requests.adapters.HTTPAdapter"). Parameters **proxy** – The url of the proxy being used for this request. Return type [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") proxy\_manager\_for(*proxy*, *\*\*proxy\_kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#HTTPAdapter.proxy_manager_for) Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the [`HTTPAdapter`](#requests.adapters.HTTPAdapter "requests.adapters.HTTPAdapter"). Parameters * **proxy** – The proxy to return a urllib3 ProxyManager for. * **proxy\_kwargs** – Extra keyword arguments used to configure the Proxy Manager. Returns ProxyManager Return type [urllib3.ProxyManager](https://urllib3.readthedocs.io/en/latest/reference/urllib3.poolmanager.html#urllib3.ProxyManager "(in urllib3 v2.0.0.dev0)") request\_url(*request*, *proxies*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#HTTPAdapter.request_url) Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the [`HTTPAdapter`](#requests.adapters.HTTPAdapter "requests.adapters.HTTPAdapter"). Parameters * **request** – The `PreparedRequest` being sent. * **proxies** – A dictionary of schemes or schemes and hosts to proxy URLs. Return type [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") send(*request*, *stream=False*, *timeout=None*, *verify=True*, *cert=None*, *proxies=None*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/adapters/#HTTPAdapter.send) Sends PreparedRequest object. Returns Response object. Parameters * **request** – The `PreparedRequest` being sent. * **stream** – (optional) Whether to stream the request content. * **timeout** ([float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)") *or* [tuple](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") *or* *urllib3 Timeout object*) – (optional) How long to wait for the server to send data before giving up, as a float, or a [(connect timeout, read timeout)](https://requests.readthedocs.io/en/latest/user/advanced/#timeouts) tuple. * **verify** – (optional) Either a boolean, in which case it controls whether we verify the server’s TLS certificate, or a string, in which case it must be a path to a CA bundle to use * **cert** – (optional) Any user-provided SSL certificate to be trusted. * **proxies** – (optional) The proxies dictionary to apply to the request. Return type [requests.Response](#requests.Response "requests.Response") Authentication -------------- *class* requests.auth.AuthBase[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/auth/#AuthBase) Base class that all auth implementations derive from *class* requests.auth.HTTPBasicAuth(*username*, *password*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/auth/#HTTPBasicAuth) Attaches HTTP Basic Authentication to the given Request object. *class* requests.auth.HTTPProxyAuth(*username*, *password*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/auth/#HTTPProxyAuth) Attaches HTTP Proxy Authentication to a given Request object. *class* requests.auth.HTTPDigestAuth(*username*, *password*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/auth/#HTTPDigestAuth) Attaches HTTP Digest Authentication to the given Request object. Encodings --------- requests.utils.get\_encodings\_from\_content(*content*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/utils/#get_encodings_from_content) Returns encodings from given content string. Parameters **content** – bytestring to extract encodings from. requests.utils.get\_encoding\_from\_headers(*headers*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/utils/#get_encoding_from_headers) Returns encodings from given HTTP Header Dict. Parameters **headers** – dictionary to extract encoding from. Return type [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") requests.utils.get\_unicode\_from\_response(*r*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/utils/#get_unicode_from_response) Returns the requested content back in unicode. Parameters **r** – Response object to get unicode content from. Tried: 1. charset from content-type 2. fall back and replace all unicode characters Return type [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Cookies ------- requests.utils.dict\_from\_cookiejar(*cj*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/utils/#dict_from_cookiejar) Returns a key/value dictionary from a CookieJar. Parameters **cj** – CookieJar object to extract cookies from. Return type [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") requests.utils.add\_dict\_to\_cookiejar(*cj*, *cookie\_dict*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/utils/#add_dict_to_cookiejar) Returns a CookieJar from a key/value dictionary. Parameters * **cj** – CookieJar to insert cookies into. * **cookie\_dict** – Dict of key/values to insert into CookieJar. Return type CookieJar requests.cookies.cookiejar\_from\_dict(*cookie\_dict*, *cookiejar=None*, *overwrite=True*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#cookiejar_from_dict) Returns a CookieJar from a key/value dictionary. Parameters * **cookie\_dict** – Dict of key/values to insert into CookieJar. * **cookiejar** – (optional) A cookiejar to add the cookies to. * **overwrite** – (optional) If False, will not replace cookies already in the jar with new ones. Return type CookieJar *class* requests.cookies.RequestsCookieJar(*policy=None*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar) Compatibility class; is a cookielib.CookieJar, but exposes a dict interface. This is the CookieJar we create by default for requests and sessions that don’t specify one, since some clients may expect response.cookies and session.cookies to support dict operations. Requests does not use the dict interface internally; it’s just for compatibility with external client code. All requests code should work out of the box with externally provided instances of `CookieJar`, e.g. `LWPCookieJar` and `FileCookieJar`. Unlike a regular CookieJar, this class is pickleable. Warning dictionary operations that are normally O(1) may be O(n). add\_cookie\_header(*request*) Add correct Cookie: header to request (urllib.request.Request object). The Cookie2 header is also added unless policy.hide\_cookie2 is true. clear(*domain=None*, *path=None*, *name=None*) Clear some cookies. Invoking this method without arguments will clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified path within that domain are removed. If given three arguments, then the cookie with the specified name, path and domain is removed. Raises KeyError if no matching cookie exists. clear\_expired\_cookies() Discard all expired cookies. You probably don’t need to call this method: expired cookies are never sent back to the server (provided you’re using DefaultCookiePolicy), this method is called by CookieJar itself every so often, and the .save() method won’t save expired cookies anyway (unless you ask otherwise by passing a true ignore\_expires argument). clear\_session\_cookies() Discard all session cookies. Note that the .save() method won’t save session cookies anyway, unless you ask otherwise by passing a true ignore\_discard argument. copy()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.copy) Return a copy of this RequestsCookieJar. extract\_cookies(*response*, *request*) Extract cookies from response, where allowable given the request. get(*name*, *default=None*, *domain=None*, *path=None*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.get) Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. Warning operation is O(n), not O(1). get\_dict(*domain=None*, *path=None*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.get_dict) Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements. Return type [dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") get\_policy()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.get_policy) Return the CookiePolicy instance used. items()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.items) Dict-like items() that returns a list of name-value tuples from the jar. Allows client-code to call `dict(RequestsCookieJar)` and get a vanilla python dict of key value pairs. See also keys() and values(). iteritems()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.iteritems) Dict-like iteritems() that returns an iterator of name-value tuples from the jar. See also iterkeys() and itervalues(). iterkeys()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.iterkeys) Dict-like iterkeys() that returns an iterator of names of cookies from the jar. See also itervalues() and iteritems(). itervalues()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.itervalues) Dict-like itervalues() that returns an iterator of values of cookies from the jar. See also iterkeys() and iteritems(). keys()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.keys) Dict-like keys() that returns a list of names of cookies from the jar. See also values() and items(). list\_domains()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.list_domains) Utility method to list all the domains in the jar. list\_paths()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.list_paths) Utility method to list all the paths in the jar. make\_cookies(*response*, *request*) Return sequence of Cookie objects extracted from response object. multiple\_domains()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.multiple_domains) Returns True if there are multiple domains in the jar. Returns False otherwise. Return type [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)") pop(*k*[, *d*]) → v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. popitem() → (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. set(*name*, *value*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.set) Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. set\_cookie(*cookie*, *\*args*, *\*\*kwargs*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.set_cookie) Set a cookie, without checking whether or not it should be set. set\_cookie\_if\_ok(*cookie*, *request*) Set a cookie if policy says it’s OK to do so. setdefault(*k*[, *d*]) → D.get(k,d), also set D[k]=d if k not in D update(*other*)[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.update) Updates this jar with cookies from another CookieJar or dict-like values()[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#RequestsCookieJar.values) Dict-like values() that returns a list of values of cookies from the jar. See also keys() and items(). *class* requests.cookies.CookieConflictError[[source]](https://requests.readthedocs.io/en/latest/_modules/requests/cookies/#CookieConflictError) There are two cookies that meet the criteria specified in the cookie jar. Use .get and .set and include domain and path args in order to be more specific. with\_traceback() Exception.with\_traceback(tb) – set self.\_\_traceback\_\_ to tb and return self. Status Code Lookup ------------------ requests.codes alias of <lookup ‘status\_codes’> The `codes` object defines a mapping from common names for HTTP statuses to their numerical codes, accessible either as attributes or as dictionary items. Example: ``` >>> import requests >>> requests.codes['temporary_redirect'] 307 >>> requests.codes.teapot 418 >>> requests.codes['\o/'] 200 ``` Some codes have multiple names, and both upper- and lower-case versions of the names are allowed. For example, `codes.ok`, `codes.OK`, and `codes.okay` all correspond to the HTTP status code 200. * 100: `continue` * 101: `switching_protocols` * 102: `processing` * 103: `checkpoint` * 122: `uri_too_long`, `request_uri_too_long` * 200: `ok`, `okay`, `all_ok`, `all_okay`, `all_good`, `\o/`, `✓` * 201: `created` * 202: `accepted` * 203: `non_authoritative_info`, `non_authoritative_information` * 204: `no_content` * 205: `reset_content`, `reset` * 206: `partial_content`, `partial` * 207: `multi_status`, `multiple_status`, `multi_stati`, `multiple_stati` * 208: `already_reported` * 226: `im_used` * 300: `multiple_choices` * 301: `moved_permanently`, `moved`, `\o-` * 302: `found` * 303: `see_other`, `other` * 304: `not_modified` * 305: `use_proxy` * 306: `switch_proxy` * 307: `temporary_redirect`, `temporary_moved`, `temporary` * 308: `permanent_redirect`, `resume_incomplete`, `resume` * 400: `bad_request`, `bad` * 401: `unauthorized` * 402: `payment_required`, `payment` * 403: `forbidden` * 404: `not_found`, `-o-` * 405: `method_not_allowed`, `not_allowed` * 406: `not_acceptable` * 407: `proxy_authentication_required`, `proxy_auth`, `proxy_authentication` * 408: `request_timeout`, `timeout` * 409: `conflict` * 410: `gone` * 411: `length_required` * 412: `precondition_failed`, `precondition` * 413: `request_entity_too_large` * 414: `request_uri_too_large` * 415: `unsupported_media_type`, `unsupported_media`, `media_type` * 416: `requested_range_not_satisfiable`, `requested_range`, `range_not_satisfiable` * 417: `expectation_failed` * 418: `im_a_teapot`, `teapot`, `i_am_a_teapot` * 421: `misdirected_request` * 422: `unprocessable_entity`, `unprocessable` * 423: `locked` * 424: `failed_dependency`, `dependency` * 425: `unordered_collection`, `unordered` * 426: `upgrade_required`, `upgrade` * 428: `precondition_required`, `precondition` * 429: `too_many_requests`, `too_many` * 431: `header_fields_too_large`, `fields_too_large` * 444: `no_response`, `none` * 449: `retry_with`, `retry` * 450: `blocked_by_windows_parental_controls`, `parental_controls` * 451: `unavailable_for_legal_reasons`, `legal_reasons` * 499: `client_closed_request` * 500: `internal_server_error`, `server_error`, `/o\`, `✗` * 501: `not_implemented` * 502: `bad_gateway` * 503: `service_unavailable`, `unavailable` * 504: `gateway_timeout` * 505: `http_version_not_supported`, `http_version` * 506: `variant_also_negotiates` * 507: `insufficient_storage` * 509: `bandwidth_limit_exceeded`, `bandwidth` * 510: `not_extended` * 511: `network_authentication_required`, `network_auth`, `network_authentication` Migrating to 1.x ---------------- This section details the main differences between 0.x and 1.x and is meant to ease the pain of upgrading. ### API Changes * `Response.json` is now a callable and not a property of a response. ``` import requests r = requests.get('https://api.github.com/events') r.json() # This *call* raises an exception if JSON decoding fails ``` * The `Session` API has changed. Sessions objects no longer take parameters. `Session` is also now capitalized, but it can still be instantiated with a lowercase `session` for backwards compatibility. ``` s = requests.Session() # formerly, session took parameters s.auth = auth s.headers.update(headers) r = s.get('https://httpbin.org/headers') ``` * All request hooks have been removed except ‘response’. * Authentication helpers have been broken out into separate modules. See [requests-oauthlib](https://github.com/requests/requests-oauthlib) and [requests-kerberos](https://github.com/requests/requests-kerberos). * The parameter for streaming requests was changed from `prefetch` to `stream` and the logic was inverted. In addition, `stream` is now required for raw response reading. ``` # in 0.x, passing prefetch=False would accomplish the same thing r = requests.get('https://api.github.com/events', stream=True) for chunk in r.iter_content(8192): ... ``` * The `config` parameter to the requests method has been removed. Some of these options are now configured on a `Session` such as keep-alive and maximum number of redirects. The verbosity option should be handled by configuring logging. ``` import requests import logging # Enabling debugging at http.client level (requests->urllib3->http.client) # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA. # the only thing missing will be the response.body which is not logged. try: # for Python 3 from http.client import HTTPConnection except ImportError: from httplib import HTTPConnection HTTPConnection.debuglevel = 1 logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests logging.getLogger().setLevel(logging.DEBUG) requests_log = logging.getLogger("urllib3") requests_log.setLevel(logging.DEBUG) requests_log.propagate = True requests.get('https://httpbin.org/headers') ``` ### Licensing One key difference that has nothing to do with the API is a change in the license from the [ISC](https://opensource.org/licenses/ISC) license to the [Apache 2.0](https://opensource.org/licenses/Apache-2.0) license. The Apache 2.0 license ensures that contributions to Requests are also covered by the Apache 2.0 license. Migrating to 2.x ---------------- Compared with the 1.0 release, there were relatively few backwards incompatible changes, but there are still a few issues to be aware of with this major release. For more details on the changes in this release including new APIs, links to the relevant GitHub issues and some of the bug fixes, read Cory’s [blog](https://lukasa.co.uk/2013/09/Requests_20/) on the subject. ### API Changes * There were a couple changes to how Requests handles exceptions. `RequestException` is now a subclass of `IOError` rather than `RuntimeError` as that more accurately categorizes the type of error. In addition, an invalid URL escape sequence now raises a subclass of `RequestException` rather than a `ValueError`. ``` requests.get('http://%zz/') # raises requests.exceptions.InvalidURL ``` Lastly, `httplib.IncompleteRead` exceptions caused by incorrect chunked encoding will now raise a Requests `ChunkedEncodingError` instead. * The proxy API has changed slightly. The scheme for a proxy URL is now required. ``` proxies = { "http": "10.10.1.10:3128", # use http://10.10.1.10:3128 instead } # In requests 1.x, this was legal, in requests 2.x, # this raises requests.exceptions.MissingSchema requests.get("http://example.org", proxies=proxies) ``` ### Behavioural Changes * Keys in the `headers` dictionary are now native strings on all Python versions, i.e. bytestrings on Python 2 and unicode on Python 3. If the keys are not native strings (unicode on Python 2 or bytestrings on Python 3) they will be converted to the native string type assuming UTF-8 encoding. * Values in the `headers` dictionary should always be strings. This has been the project’s position since before 1.0 but a recent change (since version 2.11.0) enforces this more strictly. It’s advised to avoid passing header values as unicode when possible.
programming_docs
apache_http_server Stopping and Restarting Apache HTTP Server Stopping and Restarting Apache HTTP Server ========================================== This document covers stopping and restarting Apache HTTP Server on Unix-like systems. Windows NT, 2000 and XP users should see [Running httpd as a Service](platform/windows#winsvc) and Windows 9x and ME users should see [Running httpd as a Console Application](platform/windows#wincons) for information on how to control httpd on those platforms. Introduction ------------ In order to stop or restart the Apache HTTP Server, you must send a signal to the running `[httpd](programs/httpd)` processes. There are two ways to send the signals. First, you can use the unix `kill` command to directly send signals to the processes. You will notice many `[httpd](programs/httpd)` executables running on your system, but you should not send signals to any of them except the parent, whose pid is in the `[PidFile](mod/mpm_common#pidfile)`. That is to say you shouldn't ever need to send signals to any process except the parent. There are four signals that you can send the parent: `[TERM](#term)`, `[USR1](#graceful)`, `[HUP](#hup)`, and `[WINCH](#gracefulstop)`, which will be described in a moment. To send a signal to the parent you should issue a command such as: ``` kill -TERM `cat /usr/local/apache2/logs/httpd.pid` ``` The second method of signaling the `[httpd](programs/httpd)` processes is to use the `-k` command line options: `stop`, `restart`, `graceful` and `graceful-stop`, as described below. These are arguments to the `[httpd](programs/httpd)` binary, but we recommend that you send them using the `[apachectl](programs/apachectl)` control script, which will pass them through to `[httpd](programs/httpd)`. After you have signaled `[httpd](programs/httpd)`, you can read about its progress by issuing: ``` tail -f /usr/local/apache2/logs/error_log ``` Modify those examples to match your `[ServerRoot](mod/core#serverroot)` and `[PidFile](mod/mpm_common#pidfile)` settings. Stop Now -------- Signal: TERM `apachectl -k stop` Sending the `TERM` or `stop` signal to the parent causes it to immediately attempt to kill off all of its children. It may take it several seconds to complete killing off its children. Then the parent itself exits. Any requests in progress are terminated, and no further requests are served. Graceful Restart ---------------- Signal: USR1 `apachectl -k graceful` The `USR1` or `graceful` signal causes the parent process to *advise* the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new *generation* of the configuration, which begins serving new requests immediately. This code is designed to always respect the process control directive of the MPMs, so the number of processes and threads available to serve clients will be maintained at the appropriate values throughout the restart process. Furthermore, it respects `[StartServers](mod/mpm_common#startservers)` in the following manner: if after one second at least `[StartServers](mod/mpm_common#startservers)` new children have not been created, then create enough to pick up the slack. Hence the code tries to maintain both the number of children appropriate for the current load on the server, and respect your wishes with the `[StartServers](mod/mpm_common#startservers)` parameter. Users of `[mod\_status](mod/mod_status)` will notice that the server statistics are **not** set to zero when a `USR1` is sent. The code was written to both minimize the time in which the server is unable to serve new requests (they will be queued up by the operating system, so they're not lost in any event) and to respect your tuning parameters. In order to do this it has to keep the *scoreboard* used to keep track of all children across generations. The status module will also use a `G` to indicate those children which are still serving requests started before the graceful restart was given. At present there is no way for a log rotation script using `USR1` to know for certain that all children writing the pre-restart log have finished. We suggest that you use a suitable delay after sending the `USR1` signal before you do anything with the old log. For example if most of your hits take less than 10 minutes to complete for users on low bandwidth links then you could wait 15 minutes before doing anything with the old log. When you issue a restart, a syntax check is first run, to ensure that there are no errors in the configuration files. If your configuration file has errors in it, you will get an error message about that syntax error, and the server will refuse to restart. This avoids the situation where the server halts and then cannot restart, leaving you with a non-functioning server. This still will not guarantee that the server will restart correctly. To check the semantics of the configuration files as well as the syntax, you can try starting `[httpd](programs/httpd)` as a non-root user. If there are no errors it will attempt to open its sockets and logs and fail because it's not root (or because the currently running `[httpd](programs/httpd)` already has those ports bound). If it fails for any other reason then it's probably a config file error and the error should be fixed before issuing the graceful restart. Restart Now ----------- Signal: HUP `apachectl -k restart` Sending the `HUP` or `restart` signal to the parent causes it to kill off its children like in `TERM`, but the parent doesn't exit. It re-reads its configuration files, and re-opens any log files. Then it spawns a new set of children and continues serving hits. Users of `[mod\_status](mod/mod_status)` will notice that the server statistics are set to zero when a `HUP` is sent. As with a graceful restart, a syntax check is run before the restart is attempted. If your configuration file has errors in it, the restart will not be attempted, and you will receive notification of the syntax error(s). Graceful Stop ------------- Signal: WINCH `apachectl -k graceful-stop` The `WINCH` or `graceful-stop` signal causes the parent process to *advise* the children to exit after their current request (or to exit immediately if they're not serving anything). The parent will then remove its `[PidFile](mod/mpm_common#pidfile)` and cease listening on all ports. The parent will continue to run, and monitor children which are handling requests. Once all children have finalised and exited or the timeout specified by the `[GracefulShutdownTimeout](mod/mpm_common#gracefulshutdowntimeout)` has been reached, the parent will also exit. If the timeout is reached, any remaining children will be sent the `TERM` signal to force them to exit. A `TERM` signal will immediately terminate the parent process and all children when in the "graceful" state. However as the `[PidFile](mod/mpm_common#pidfile)` will have been removed, you will not be able to use `apachectl` or `httpd` to send this signal. The `graceful-stop` signal allows you to run multiple identically configured instances of `[httpd](programs/httpd)` at the same time. This is a powerful feature when performing graceful upgrades of httpd, however it can also cause deadlocks and race conditions with some configurations. Care has been taken to ensure that on-disk files such as lock files (`[Mutex](mod/core#mutex)`) and Unix socket files (`[ScriptSock](mod/mod_cgid#scriptsock)`) contain the server PID, and should coexist without problem. However, if a configuration directive, third-party module or persistent CGI utilises any other on-disk lock or state files, care should be taken to ensure that multiple running instances of `[httpd](programs/httpd)` do not clobber each other's files. You should also be wary of other potential race conditions, such as using `[rotatelogs](programs/rotatelogs)` style piped logging. Multiple running instances of `[rotatelogs](programs/rotatelogs)` attempting to rotate the same logfiles at the same time may destroy each other's logfiles. apache_http_server Compiling and Installing Compiling and Installing ======================== This document covers compilation and installation of the Apache HTTP Server on Unix and Unix-like systems only. For compiling and installation on Windows, see [Using Apache HTTP Server with Microsoft Windows](platform/windows) and [Compiling Apache for Microsoft Windows](platform/win_compiling). For other platforms, see the [platform](platform/index) documentation. Apache httpd uses `libtool` and `autoconf` to create a build environment that looks like many other Open Source projects. If you are upgrading from one minor version to the next (for example, 2.4.8 to 2.4.9), please skip down to the [upgrading](#upgrading) section. Overview for the impatient -------------------------- Installing on Fedora/CentOS/Red Hat Enterprise Linux ``` sudo yum install httpd sudo systemctl enable httpd sudo systemctl start httpd ``` Newer releases of these distros use `dnf` rather than `yum`. See [the Fedora project's documentation](https://fedoraproject.org/wiki/Apache_HTTP_Server) for platform-specific notes. Installing on Ubuntu/Debian ``` sudo apt install apache2 sudo service apache2 start ``` See [Ubuntu's documentation](https://help.ubuntu.com/lts/serverguide/httpd.html) for platform-specific notes. Installing from source | | | | --- | --- | | [Download](#download) | Download the latest release from [http://httpd.apache.org/download.cgi](http://httpd.apache.org/download.cgi#apache24) | | [Extract](#extract) | ``` $ gzip -d httpd-NN.tar.gz $ tar xvf httpd-NN.tar $ cd httpd-NN ``` | | [Configure](#configure) | ``` $ ./configure --prefix=PREFIX ``` | | [Compile](#compile) | ``` $ make ``` | | [Install](#install) | ``` $ make install ``` | | [Customize](#customize) | ``` $ vi PREFIX/conf/httpd.conf ``` | | [Test](#test) | ``` $ PREFIX/bin/apachectl -k start ``` | *NN* must be replaced with the current version number, and *PREFIX* must be replaced with the filesystem path under which the server should be installed. If *PREFIX* is not specified, it defaults to `/usr/local/apache2`. Each section of the compilation and installation process is described in more detail below, beginning with the requirements for compiling and installing Apache httpd. Don't see your favorite platform mentioned here? [Come help us improve this doc.](http://httpd.apache.org/docs-project/) Requirements ------------ The following requirements exist for building Apache httpd: APR and APR-Util Make sure you have APR and APR-Util already installed on your system. If you don't, or prefer to not use the system-provided versions, download the latest versions of both APR and APR-Util from [Apache APR](http://apr.apache.org/), unpack them into `/httpd_source_tree_root/srclib/apr` and `/httpd_source_tree_root/srclib/apr-util` (be sure the directory names do not have version numbers; for example, the APR distribution must be under /httpd\_source\_tree\_root/srclib/apr/) and use `./configure`'s `--with-included-apr` option. On some platforms, you may have to install the corresponding `-dev` packages to allow httpd to build against your installed copy of APR and APR-Util. Perl-Compatible Regular Expressions Library (PCRE) This library is required but not longer bundled with httpd. Download the source code from [http://www.pcre.org](http://www.pcre.org/), or install a Port or Package. If your build system can't find the pcre-config script installed by the PCRE build, point to it using the `--with-pcre` parameter. On some platforms, you may have to install the corresponding `-dev` package to allow httpd to build against your installed copy of PCRE. Disk Space Make sure you have at least 50 MB of temporary free disk space available. After installation the server occupies approximately 10 MB of disk space. The actual disk space requirements will vary considerably based on your chosen configuration options, any third-party modules, and, of course, the size of the web site or sites that you have on the server. ANSI-C Compiler and Build System Make sure you have an ANSI-C compiler installed. The [GNU C compiler (GCC)](http://gcc.gnu.org/) from the [Free Software Foundation (FSF)](http://www.gnu.org/) is recommended. If you don't have GCC then at least make sure your vendor's compiler is ANSI compliant. In addition, your `PATH` must contain basic build tools such as `make`. Accurate time keeping Elements of the HTTP protocol are expressed as the time of day. So, it's time to investigate setting some time synchronization facility on your system. Usually the `ntpdate` or `xntpd` programs are used for this purpose which are based on the Network Time Protocol (NTP). See the [NTP homepage](http://www.ntp.org) for more details about NTP software and public time servers. [Perl 5](http://www.perl.org/) [OPTIONAL] For some of the support scripts like `[apxs](programs/apxs)` or `[dbmmanage](programs/dbmmanage)` (which are written in Perl) the Perl 5 interpreter is required (versions 5.003 or newer are sufficient). If no Perl 5 interpreter is found by the `[configure](programs/configure)` script, you will not be able to use the affected support scripts. Of course, you will still be able to build and use Apache httpd. Download -------- The Apache HTTP Server can be downloaded from the [Apache HTTP Server download site](http://httpd.apache.org/download.cgi), which lists several mirrors. Most users of Apache on unix-like systems will be better off downloading and compiling a source version. The build process (described below) is easy, and it allows you to customize your server to suit your needs. In addition, binary releases are often not up to date with the latest source releases. If you do download a binary, follow the instructions in the `INSTALL.bindist` file inside the distribution. After downloading, it is important to verify that you have a complete and unmodified version of the Apache HTTP Server. This can be accomplished by testing the downloaded tarball against the PGP signature. Details on how to do this are available on the [download page](http://httpd.apache.org/download.cgi#verify) and an extended example is available describing the [use of PGP](http://httpd.apache.org/dev/verification.html). Extract ------- Extracting the source from the Apache HTTP Server tarball is a simple matter of uncompressing, and then untarring: ``` $ gzip -d httpd-NN.tar.gz $ tar xvf httpd-NN.tar ``` This will create a new directory under the current directory containing the source code for the distribution. You should `cd` into that directory before proceeding with compiling the server. Configuring the source tree --------------------------- The next step is to configure the Apache source tree for your particular platform and personal requirements. This is done using the script `[configure](programs/configure)` included in the root directory of the distribution. (Developers downloading an unreleased version of the Apache source tree will need to have `autoconf` and `libtool` installed and will need to run `buildconf` before proceeding with the next steps. This is not necessary for official releases.) To configure the source tree using all the default options, simply type `./configure`. To change the default options, `[configure](programs/configure)` accepts a variety of variables and command line options. The most important option is the location `--prefix` where Apache is to be installed later, because Apache has to be configured for this location to work correctly. More fine-tuned control of the location of files is possible with additional [configure options](programs/configure#installationdirectories). Also at this point, you can specify which [features](programs/configure#optionalfeatures) you want included in Apache by enabling and disabling [modules](mod/index). Apache comes with a wide range of modules included by default. They will be compiled as [shared objects (DSOs)](dso) which can be loaded or unloaded at runtime. You can also choose to compile modules statically by using the option `--enable-module=static`. Additional modules are enabled using the `--enable-module` option, where module is the name of the module with the `mod_` string removed and with any underscore converted to a dash. Similarly, you can disable modules with the `--disable-module` option. Be careful when using these options, since `[configure](programs/configure)` cannot warn you if the module you specify does not exist; it will simply ignore the option. In addition, it is sometimes necessary to provide the `[configure](programs/configure)` script with extra information about the location of your compiler, libraries, or header files. This is done by passing either environment variables or command line options to `[configure](programs/configure)`. For more information, see the `[configure](programs/configure)` manual page. Or invoke `[configure](programs/configure)` using the `--help` option. For a short impression of what possibilities you have, here is a typical example which compiles Apache for the installation tree `/sw/pkg/apache` with a particular compiler and flags plus the two additional modules `[mod\_ldap](mod/mod_ldap)` and `[mod\_lua](mod/mod_lua)`: ``` $ CC="pgcc" CFLAGS="-O2" \ ./configure --prefix=/sw/pkg/apache \ --enable-ldap=shared \ --enable-lua=shared ``` When `[configure](programs/configure)` is run it will take several minutes to test for the availability of features on your system and build Makefiles which will later be used to compile the server. Details on all the different `[configure](programs/configure)` options are available on the `[configure](programs/configure)` manual page. Build ----- Now you can build the various parts which form the Apache package by simply running the command: ``` $ make ``` Please be patient here, since a base configuration takes several minutes to compile and the time will vary widely depending on your hardware and the number of modules that you have enabled. Install ------- Now it's time to install the package under the configured installation *PREFIX* (see `--prefix` option above) by running: ``` $ make install ``` This step will typically require root privileges, since *PREFIX* is usually a directory with restricted write permissions. If you are upgrading, the installation will not overwrite your configuration files or documents. Customize --------- Next, you can customize your Apache HTTP server by editing the [configuration files](configuring) under `*PREFIX*/conf/`. ``` $ vi PREFIX/conf/httpd.conf ``` Have a look at the Apache manual under `*PREFIX*/docs/manual/` or consult <http://httpd.apache.org/docs/2.4/> for the most recent version of this manual and a complete reference of available [configuration directives](https://httpd.apache.org/docs/2.4/en/mod/directives.html). Test ---- Now you can [start](invoking) your Apache HTTP server by immediately running: ``` $ PREFIX/bin/apachectl -k start ``` You should then be able to request your first document via the URL `http://localhost/`. The web page you see is located under the `[DocumentRoot](mod/core#documentroot)`, which will usually be `*PREFIX*/htdocs/`. Then [stop](stopping) the server again by running: ``` $ PREFIX/bin/apachectl -k stop ``` Upgrading --------- The first step in upgrading is to read the release announcement and the file `CHANGES` in the source distribution to find any changes that may affect your site. When changing between major releases (for example, from 2.0 to 2.2 or from 2.2 to 2.4), there will likely be major differences in the compile-time and run-time configuration that will require manual adjustments. All modules will also need to be upgraded to accommodate changes in the module API. Upgrading from one minor version to the next (for example, from 2.2.55 to 2.2.57) is easier. The `make install` process will not overwrite any of your existing documents, log files, or configuration files. In addition, the developers make every effort to avoid incompatible changes in the `[configure](programs/configure)` options, run-time configuration, or the module API between minor versions. In most cases you should be able to use an identical `[configure](programs/configure)` command line, an identical configuration file, and all of your modules should continue to work. To upgrade across minor versions, start by finding the file `config.nice` in the `build` directory of your installed server or at the root of the source tree for your old install. This will contain the exact `[configure](programs/configure)` command line that you used to configure the source tree. Then to upgrade from one version to the next, you need only copy the `config.nice` file to the source tree of the new version, edit it to make any desired changes, and then run: ``` $ ./config.nice $ make $ make install $ PREFIX/bin/apachectl -k graceful-stop $ PREFIX/bin/apachectl -k start ``` You should always test any new version in your environment before putting it into production. For example, you can install and run the new version along side the old one by using a different `--prefix` and a different port (by adjusting the `[Listen](mod/mpm_common#listen)` directive) to test for any incompatibilities before doing the final upgrade. You can pass additional arguments to `config.nice`, which will be appended to your original `[configure](programs/configure)` options: ``` $ ./config.nice --prefix=/home/test/apache --with-port=90 ``` Third-party packages -------------------- A large number of third parties provide their own packaged distributions of the Apache HTTP Server for installation on particular platforms. This includes the various Linux distributions, various third-party Windows packages, Mac OS X, Solaris, and many more. Our software license not only permits, but encourages, this kind of redistribution. However, it does result in a situation where the configuration layout and defaults on your installation of the server may differ from what is stated in the documentation. While unfortunate, this situation is not likely to change any time soon. A [description of these third-party distributions](http://wiki.apache.org/httpd/DistrosDefaultLayout) is maintained in the HTTP Server wiki, and should reflect the current state of these third-party distributions. However, you will need to familiarize yourself with your particular platform's package management and installation procedures.
programming_docs
apache_http_server Custom Error Responses Custom Error Responses ====================== Although the Apache HTTP Server provides generic error responses in the event of 4xx or 5xx HTTP status codes, these responses are rather stark, uninformative, and can be intimidating to site users. You may wish to provide custom error responses which are either friendlier, or in some language other than English, or perhaps which are styled more in line with your site layout. Customized error responses can be defined for any HTTP status code designated as an error condition - that is, any 4xx or 5xx status. Additionally, a set of values are provided, so that the error document can be customized further based on the values of these variables, using [Server Side Includes](howto/ssi). Or, you can have error conditions handled by a cgi program, or other dynamic handler (PHP, mod\_perl, etc) which makes use of these variables. Configuration ------------- Custom error documents are configured using the `[ErrorDocument](mod/core#errordocument)` directive, which may be used in global, virtualhost, or directory context. It may be used in .htaccess files if `[AllowOverride](mod/core#allowoverride)` is set to FileInfo. ``` ErrorDocument 500 "Sorry, our script crashed. Oh dear" ErrorDocument 500 /cgi-bin/crash-recover ErrorDocument 500 http://error.example.com/server_error.html ErrorDocument 404 /errors/not_found.html ErrorDocument 401 /subscription/how_to_subscribe.html ``` The syntax of the `ErrorDocument` directive is: ``` ErrorDocument <3-digit-code> <action> ``` where the action will be treated as: 1. A local URL to redirect to (if the action begins with a "/"). 2. An external URL to redirect to (if the action is a valid URL). 3. Text to be displayed (if none of the above). The text must be wrapped in quotes (") if it consists of more than one word. When redirecting to a local URL, additional environment variables are set so that the response can be further customized. They are not sent to external URLs. Available Variables ------------------- Redirecting to another URL can be useful, but only if some information can be passed which can then be used to explain or log the error condition more clearly. To achieve this, when the error redirect is sent, additional environment variables will be set, which will be generated from the headers provided to the original request by prepending 'REDIRECT\_' onto the original header name. This provides the error document the context of the original request. For example, you might receive, in addition to more usual environment variables, the following. ``` REDIRECT_HTTP_ACCEPT=*/*, image/gif, image/jpeg, image/png REDIRECT_HTTP_USER_AGENT=Mozilla/5.0 Fedora/3.5.8-1.fc12 Firefox/3.5.8 REDIRECT_PATH=.:/bin:/usr/local/bin:/sbin REDIRECT_QUERY_STRING= REDIRECT_REMOTE_ADDR=121.345.78.123 REDIRECT_REMOTE_HOST=client.example.com REDIRECT_SERVER_NAME=www.example.edu REDIRECT_SERVER_PORT=80 REDIRECT_SERVER_SOFTWARE=Apache/2.2.15 REDIRECT_URL=/cgi-bin/buggy.pl ``` `REDIRECT_` environment variables are created from the environment variables which existed prior to the redirect. They are renamed with a `REDIRECT_` prefix, *i.e.*, `HTTP_USER_AGENT` becomes `REDIRECT_HTTP_USER_AGENT`. `REDIRECT_URL`, `REDIRECT_STATUS`, and `REDIRECT_QUERY_STRING` are guaranteed to be set, and the other headers will be set only if they existed prior to the error condition. **None** of these will be set if the `[ErrorDocument](mod/core#errordocument)` target is an *external* redirect (anything starting with a scheme name like `http:`, even if it refers to the same host as the server). Customizing Error Responses --------------------------- If you point your `ErrorDocument` to some variety of dynamic handler such as a server-side include document, CGI script, or some variety of other handler, you may wish to use the available custom environment variables to customize this response. If the ErrorDocument specifies a local redirect to a CGI script, the script should include a "`Status:`" header field in its output in order to ensure the propagation all the way back to the client of the error condition that caused it to be invoked. For instance, a Perl ErrorDocument script might include the following: ``` ... print "Content-type: text/html\n"; printf "Status: %s Condition Intercepted\n", $ENV{"REDIRECT_STATUS"}; ... ``` If the script is dedicated to handling a particular error condition, such as `404 Not Found`, it can use the specific code and error text instead. Note that if the response contains `Location:` header (in order to issue a client-side redirect), the script *must* emit an appropriate `Status:` header (such as `302 Found`). Otherwise the `Location:` header may have no effect. Multi Language Custom Error Documents ------------------------------------- Provided with your installation of the Apache HTTP Server is a directory of custom error documents translated into 16 different languages. There's also a configuration file in the `conf/extra` configuration directory that can be included to enable this feature. In your server configuration file, you'll see a line such as: ``` # Multi-language error messages #Include conf/extra/httpd-multilang-errordoc.conf ``` Uncommenting this `Include` line will enable this feature, and provide language-negotiated error messages, based on the language preference set in the client browser. Additionally, these documents contain various of the `REDIRECT_` variables, so that additional information can be provided to the end-user about what happened, and what they can do now. These documents can be customized to whatever degree you wish to provide more useful information to users about your site, and what they can expect to find there. `[mod\_include](mod/mod_include)` and `[mod\_negotiation](mod/mod_negotiation)` must be enabled to use this feature. apache_http_server Issues Regarding DNS and Apache HTTP Server Issues Regarding DNS and Apache HTTP Server =========================================== This page could be summarized with the statement: don't configure Apache HTTP Server in such a way that it relies on DNS resolution for parsing of the configuration files. If httpd requires DNS resolution to parse the configuration files then your server may be subject to reliability problems (ie. it might not start up), or denial and theft of service attacks (including virtual hosts able to steal hits from other virtual hosts). A Simple Example ---------------- ``` # This is a misconfiguration example, do not use on your server <VirtualHost www.example.dom> ServerAdmin [email protected] DocumentRoot "/www/example" </VirtualHost> ``` In order for the server to function properly, it absolutely needs to have two pieces of information about each virtual host: the `[ServerName](mod/core#servername)` and at least one IP address that the server will bind and respond to. The above example does not include the IP address, so httpd must use DNS to find the address of `www.example.dom`. If for some reason DNS is not available at the time your server is parsing its config file, then this virtual host **will not be configured**. It won't be able to respond to any hits to this virtual host. Suppose that `www.example.dom` has address 192.0.2.1. Then consider this configuration snippet: ``` # This is a misconfiguration example, do not use on your server <VirtualHost 192.0.2.1> ServerAdmin [email protected] DocumentRoot "/www/example" </VirtualHost> ``` This time httpd needs to use reverse DNS to find the `ServerName` for this virtualhost. If that reverse lookup fails then it will partially disable the virtualhost. If the virtual host is name-based then it will effectively be totally disabled, but if it is IP-based then it will mostly work. However, if httpd should ever have to generate a full URL for the server which includes the server name (such as when a Redirect is issued), then it will fail to generate a valid URL. Here is a snippet that avoids both of these problems: ``` <VirtualHost 192.0.2.1> ServerName www.example.dom ServerAdmin [email protected] DocumentRoot "/www/example" </VirtualHost> ``` Denial of Service ----------------- Consider this configuration snippet: ``` <VirtualHost www.example1.dom> ServerAdmin [email protected] DocumentRoot "/www/example1" </VirtualHost> <VirtualHost www.example2.dom> ServerAdmin [email protected] DocumentRoot "/www/example2" </VirtualHost> ``` Suppose that you've assigned 192.0.2.1 to `www.example1.dom` and 192.0.2.2 to `www.example2.dom`. Furthermore, suppose that `example1.dom` has control of their own DNS. With this config you have put `example1.dom` into a position where they can steal all traffic destined to `example2.dom`. To do so, all they have to do is set `www.example1.dom` to 192.0.2.2. Since they control their own DNS you can't stop them from pointing the `www.example1.dom` record wherever they wish. Requests coming in to 192.0.2.2 (including all those where users typed in URLs of the form `http://www.example2.dom/whatever`) will all be served by the `example1.dom` virtual host. To better understand why this happens requires a more in-depth discussion of how httpd matches up incoming requests with the virtual host that will serve it. A rough document describing this [is available](vhosts/details). The "main server" Address ------------------------- [Name-based virtual host support](vhosts/name-based) requires httpd to know the IP address(es) of the host that `[httpd](programs/httpd)` is running on. To get this address it uses either the global `[ServerName](mod/core#servername)` (if present) or calls the C function `gethostname` (which should return the same as typing "hostname" at the command prompt). Then it performs a DNS lookup on this address. At present there is no way to avoid this lookup. If you fear that this lookup might fail because your DNS server is down then you can insert the hostname in `/etc/hosts` (where you probably already have it so that the machine can boot properly). Then ensure that your machine is configured to use `/etc/hosts` in the event that DNS fails. Depending on what OS you are using this might be accomplished by editing `/etc/resolv.conf`, or maybe `/etc/nsswitch.conf`. If your server doesn't have to perform DNS for any other reason then you might be able to get away with running httpd with the `HOSTRESORDER` environment variable set to "local". This all depends on what OS and resolver libraries you are using. It also affects CGIs unless you use `[mod\_env](mod/mod_env)` to control the environment. It's best to consult the man pages or FAQs for your OS. Tips to Avoid These Problems ---------------------------- * use IP addresses in `[VirtualHost](mod/core#virtualhost)` * use IP addresses in `[Listen](mod/mpm_common#listen)` * ensure all virtual hosts have an explicit `[ServerName](mod/core#servername)` * create a `<VirtualHost _default_:*>` server that has no pages to serve apache_http_server Caching Guide Caching Guide ============= This document supplements the `[mod\_cache](mod/mod_cache)`, `[mod\_cache\_disk](mod/mod_cache_disk)`, `[mod\_file\_cache](mod/mod_file_cache)` and [htcacheclean](programs/htcacheclean) reference documentation. It describes how to use the Apache HTTP Server's caching features to accelerate web and proxy serving, while avoiding common problems and misconfigurations. Introduction ------------ The Apache HTTP server offers a range of caching features that are designed to improve the performance of the server in various ways. Three-state RFC2616 HTTP caching `[mod\_cache](mod/mod_cache)` and its provider modules `[mod\_cache\_disk](mod/mod_cache_disk)` provide intelligent, HTTP-aware caching. The content itself is stored in the cache, and mod\_cache aims to honor all of the various HTTP headers and options that control the cacheability of content as described in [Section 13 of RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html). `[mod\_cache](mod/mod_cache)` is aimed at both simple and complex caching configurations, where you are dealing with proxied content, dynamic local content or have a need to speed up access to local files on a potentially slow disk. Two-state key/value shared object caching The [shared object cache API](socache) (socache) and its provider modules provide a server wide key/value based shared object cache. These modules are designed to cache low level data such as SSL sessions and authentication credentials. Backends allow the data to be stored server wide in shared memory, or datacenter wide in a cache such as memcache or distcache. Specialized file caching `[mod\_file\_cache](mod/mod_file_cache)` offers the ability to pre-load files into memory on server startup, and can improve access times and save file handles on files that are accessed often, as there is no need to go to disk on each request. To get the most from this document, you should be familiar with the basics of HTTP, and have read the Users' Guides to [Mapping URLs to the Filesystem](urlmapping) and [Content negotiation](content-negotiation). Three-state RFC2616 HTTP caching -------------------------------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_cache](mod/mod_cache)` * `[mod\_cache\_disk](mod/mod_cache_disk)` | * `[CacheEnable](mod/mod_cache#cacheenable)` * `[CacheDisable](mod/mod_cache#cachedisable)` * `[UseCanonicalName](mod/core#usecanonicalname)` * `[CacheNegotiatedDocs](mod/mod_negotiation#cachenegotiateddocs)` | The HTTP protocol contains built in support for an in-line caching mechanism [described by section 13 of RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html), and the `[mod\_cache](mod/mod_cache)` module can be used to take advantage of this. Unlike a simple two state key/value cache where the content disappears completely when no longer fresh, an HTTP cache includes a mechanism to retain stale content, and to ask the origin server whether this stale content has changed and if not, make it fresh again. An entry in an HTTP cache exists in one of three states: Fresh If the content is new enough (younger than its **freshness lifetime**), it is considered **fresh**. An HTTP cache is free to serve fresh content without making any calls to the origin server at all. Stale If the content is too old (older than its **freshness lifetime**), it is considered **stale**. An HTTP cache should contact the origin server and check whether the content is still fresh before serving stale content to a client. The origin server will either respond with replacement content if not still valid, or ideally, the origin server will respond with a code to tell the cache the content is still fresh, without the need to generate or send the content again. The content becomes fresh again and the cycle continues. The HTTP protocol does allow the cache to serve stale data under certain circumstances, such as when an attempt to freshen the data with an origin server has failed with a 5xx error, or when another request is already in the process of freshening the given entry. In these cases a `Warning` header is added to the response. Non Existent If the cache gets full, it reserves the option to delete content from the cache to make space. Content can be deleted at any time, and can be stale or fresh. The [htcacheclean](programs/htcacheclean) tool can be run on a once off basis, or deployed as a daemon to keep the size of the cache within the given size, or the given number of inodes. The tool attempts to delete stale content before attempting to delete fresh content. Full details of how HTTP caching works can be found in [Section 13 of RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html). ### Interaction with the Server The `[mod\_cache](mod/mod_cache)` module hooks into the server in two possible places depending on the value of the `[CacheQuickHandler](mod/mod_cache#cachequickhandler)` directive: Quick handler phase This phase happens very early on during the request processing, just after the request has been parsed. If the content is found within the cache, it is served immediately and almost all request processing is bypassed. In this scenario, the cache behaves as if it has been "bolted on" to the front of the server. This mode offers the best performance, as the majority of server processing is bypassed. This mode however also bypasses the authentication and authorization phases of server processing, so this mode should be chosen with care when this is important. Requests with an "Authorization" header (for example, HTTP Basic Authentication) are neither cacheable nor served from the cache when `[mod\_cache](mod/mod_cache)` is running in this phase. Normal handler phase This phase happens late in the request processing, after all the request phases have completed. In this scenario, the cache behaves as if it has been "bolted on" to the back of the server. This mode offers the most flexibility, as the potential exists for caching to occur at a precisely controlled point in the filter chain, and cached content can be filtered or personalized before being sent to the client. If the URL is not found within the cache, `[mod\_cache](mod/mod_cache)` will add a <filter> to the filter stack in order to record the response to the cache, and then stand down, allowing normal request processing to continue. If the content is determined to be cacheable, the content will be saved to the cache for future serving, otherwise the content will be ignored. If the content found within the cache is stale, the `[mod\_cache](mod/mod_cache)` module converts the request into a **conditional request**. If the origin server responds with a normal response, the normal response is cached, replacing the content already cached. If the origin server responds with a 304 Not Modified response, the content is marked as fresh again, and the cached content is served by the filter instead of saving it. ### Improving Cache Hits When a virtual host is known by one of many different server aliases, ensuring that `[UseCanonicalName](mod/core#usecanonicalname)` is set to `On` can dramatically improve the ratio of cache hits. This is because the hostname of the virtual-host serving the content is used within the cache key. With the setting set to `On` virtual-hosts with multiple server names or aliases will not produce differently cached entities, and instead content will be cached as per the canonical hostname. ### Freshness Lifetime Well formed content that is intended to be cached should declare an explicit freshness lifetime with the `Cache-Control` header's `max-age` or `s-maxage` fields, or by including an `Expires` header. At the same time, the origin server defined freshness lifetime can be overridden by a client when the client presents their own `Cache-Control` header within the request. In this case, the lowest freshness lifetime between request and response wins. When this freshness lifetime is missing from the request or the response, a default freshness lifetime is applied. The default freshness lifetime for cached entities is one hour, however this can be easily over-ridden by using the `[CacheDefaultExpire](mod/mod_cache#cachedefaultexpire)` directive. If a response does not include an `Expires` header but does include a `Last-Modified` header, `[mod\_cache](mod/mod_cache)` can infer a freshness lifetime based on a heuristic, which can be controlled through the use of the `[CacheLastModifiedFactor](mod/mod_cache#cachelastmodifiedfactor)` directive. For local content, or for remote content that does not define its own `Expires` header, `[mod\_expires](mod/mod_expires)` may be used to fine-tune the freshness lifetime by adding `max-age` and `Expires`. The maximum freshness lifetime may also be controlled by using the `[CacheMaxExpire](mod/mod_cache#cachemaxexpire)`. ### A Brief Guide to Conditional Requests When content expires from the cache and becomes stale, rather than pass on the original request, httpd will modify the request to make it conditional instead. When an `ETag` header exists in the original cached response, `[mod\_cache](mod/mod_cache)` will add an `If-None-Match` header to the request to the origin server. When a `Last-Modified` header exists in the original cached response, `[mod\_cache](mod/mod_cache)` will add an `If-Modified-Since` header to the request to the origin server. Performing either of these actions makes the request **conditional**. When a conditional request is received by an origin server, the origin server should check whether the ETag or the Last-Modified parameter has changed, as appropriate for the request. If not, the origin should respond with a terse "304 Not Modified" response. This signals to the cache that the stale content is still fresh should be used for subsequent requests until the content's new freshness lifetime is reached again. If the content has changed, then the content is served as if the request were not conditional to begin with. Conditional requests offer two benefits. Firstly, when making such a request to the origin server, if the content from the origin matches the content in the cache, this can be determined easily and without the overhead of transferring the entire resource. Secondly, a well designed origin server will be designed in such a way that conditional requests will be significantly cheaper to produce than a full response. For static files, typically all that is involved is a call to `stat()` or similar system call, to see if the file has changed in size or modification time. As such, even local content may still be served faster from the cache if it has not changed. Origin servers should make every effort to support conditional requests as is practical, however if conditional requests are not supported, the origin will respond as if the request was not conditional, and the cache will respond as if the content had changed and save the new content to the cache. In this case, the cache will behave like a simple two state cache, where content is effectively either fresh or deleted. ### What Can be Cached? The full definition of which responses can be cached by an HTTP cache is defined in [RFC2616 Section 13.4 Response Cacheability](http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4), and can be summed up as follows: 1. Caching must be enabled for this URL. See the `[CacheEnable](mod/mod_cache#cacheenable)` and `[CacheDisable](mod/mod_cache#cachedisable)` directives. 2. If the response has an HTTP status code other than 200, 203, 300, 301 or 410 it must also specify an "Expires" or "Cache-Control" header. 3. The request must be a HTTP GET request. 4. If the response contains an "Authorization:" header, it must also contain an "s-maxage", "must-revalidate" or "public" option in the "Cache-Control:" header, or it won't be cached. 5. If the URL included a query string (e.g. from a HTML form GET method) it will not be cached unless the response specifies an explicit expiration by including an "Expires:" header or the max-age or s-maxage directive of the "Cache-Control:" header, as per RFC2616 sections 13.9 and 13.2.1. 6. If the response has a status of 200 (OK), the response must also include at least one of the "Etag", "Last-Modified" or the "Expires" headers, or the max-age or s-maxage directive of the "Cache-Control:" header, unless the `[CacheIgnoreNoLastMod](mod/mod_cache#cacheignorenolastmod)` directive has been used to require otherwise. 7. If the response includes the "private" option in a "Cache-Control:" header, it will not be stored unless the `[CacheStorePrivate](mod/mod_cache#cachestoreprivate)` has been used to require otherwise. 8. Likewise, if the response includes the "no-store" option in a "Cache-Control:" header, it will not be stored unless the `[CacheStoreNoStore](mod/mod_cache#cachestorenostore)` has been used. 9. A response will not be stored if it includes a "Vary:" header containing the match-all "\*". ### What Should Not be Cached? It should be up to the client creating the request, or the origin server constructing the response to decide whether or not the content should be cacheable or not by correctly setting the `Cache-Control` header, and `[mod\_cache](mod/mod_cache)` should be left alone to honor the wishes of the client or server as appropriate. Content that is time sensitive, or which varies depending on the particulars of the request that are not covered by HTTP negotiation, should not be cached. This content should declare itself uncacheable using the `Cache-Control` header. If content changes often, expressed by a freshness lifetime of minutes or seconds, the content can still be cached, however it is highly desirable that the origin server supports **conditional requests** correctly to ensure that full responses do not have to be generated on a regular basis. Content that varies based on client provided request headers can be cached through intelligent use of the `Vary` response header. ### Variable/Negotiated Content When the origin server is designed to respond with different content based on the value of headers in the request, for example to serve multiple languages at the same URL, HTTP's caching mechanism makes it possible to cache multiple variants of the same page at the same URL. This is done by the origin server adding a `Vary` header to indicate which headers must be taken into account by a cache when determining whether two variants are different from one another. If for example, a response is received with a vary header such as; ``` Vary: negotiate,accept-language,accept-charset ``` `[mod\_cache](mod/mod_cache)` will only serve the cached content to requesters with accept-language and accept-charset headers matching those of the original request. Multiple variants of the content can be cached side by side, `[mod\_cache](mod/mod_cache)` uses the `Vary` header and the corresponding values of the request headers listed by `Vary` to decide on which of many variants to return to the client. Cache Setup Examples -------------------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_cache](mod/mod_cache)` * `[mod\_cache\_disk](mod/mod_cache_disk)` * `[mod\_cache\_socache](mod/mod_cache_socache)` * `[mod\_socache\_memcache](mod/mod_socache_memcache)` | * `[CacheEnable](mod/mod_cache#cacheenable)` * `[CacheRoot](mod/mod_cache_disk#cacheroot)` * `[CacheDirLevels](mod/mod_cache_disk#cachedirlevels)` * `[CacheDirLength](mod/mod_cache_disk#cachedirlength)` * `[CacheSocache](mod/mod_cache_socache#cachesocache)` | ### Caching to Disk The `[mod\_cache](mod/mod_cache)` module relies on specific backend store implementations in order to manage the cache, and for caching to disk `[mod\_cache\_disk](mod/mod_cache_disk)` is provided to support this. Typically the module will be configured as so; ``` CacheRoot "/var/cache/apache/" CacheEnable disk / CacheDirLevels 2 CacheDirLength 1 ``` Importantly, as the cached files are locally stored, operating system in-memory caching will typically be applied to their access also. So although the files are stored on disk, if they are frequently accessed it is likely the operating system will ensure that they are actually served from memory. ### Understanding the Cache-Store To store items in the cache, `[mod\_cache\_disk](mod/mod_cache_disk)` creates a 22 character hash of the URL being requested. This hash incorporates the hostname, protocol, port, path and any CGI arguments to the URL, as well as elements defined by the Vary header to ensure that multiple URLs do not collide with one another. Each character may be any one of 64-different characters, which mean that overall there are 64^22 possible hashes. For example, a URL might be hashed to `xyTGxSMO2b68mBCykqkp1w`. This hash is used as a prefix for the naming of the files specific to that URL within the cache, however first it is split up into directories as per the `[CacheDirLevels](mod/mod_cache_disk#cachedirlevels)` and `[CacheDirLength](mod/mod_cache_disk#cachedirlength)` directives. `[CacheDirLevels](mod/mod_cache_disk#cachedirlevels)` specifies how many levels of subdirectory there should be, and `[CacheDirLength](mod/mod_cache_disk#cachedirlength)` specifies how many characters should be in each directory. With the example settings given above, the hash would be turned into a filename prefix as `/var/cache/apache/x/y/TGxSMO2b68mBCykqkp1w`. The overall aim of this technique is to reduce the number of subdirectories or files that may be in a particular directory, as most file-systems slow down as this number increases. With setting of "1" for `[CacheDirLength](mod/mod_cache_disk#cachedirlength)` there can at most be 64 subdirectories at any particular level. With a setting of 2 there can be 64 \* 64 subdirectories, and so on. Unless you have a good reason not to, using a setting of "1" for `[CacheDirLength](mod/mod_cache_disk#cachedirlength)` is recommended. Setting `[CacheDirLevels](mod/mod_cache_disk#cachedirlevels)` depends on how many files you anticipate to store in the cache. With the setting of "2" used in the above example, a grand total of 4096 subdirectories can ultimately be created. With 1 million files cached, this works out at roughly 245 cached URLs per directory. Each URL uses at least two files in the cache-store. Typically there is a ".header" file, which includes meta-information about the URL, such as when it is due to expire and a ".data" file which is a verbatim copy of the content to be served. In the case of a content negotiated via the "Vary" header, a ".vary" directory will be created for the URL in question. This directory will have multiple ".data" files corresponding to the differently negotiated content. ### Maintaining the Disk Cache The `[mod\_cache\_disk](mod/mod_cache_disk)` module makes no attempt to regulate the amount of disk space used by the cache, although it will gracefully stand down on any disk error and behave as if the cache was never present. Instead, provided with httpd is the [htcacheclean](programs/htcacheclean) tool which allows you to clean the cache periodically. Determining how frequently to run [htcacheclean](programs/htcacheclean) and what target size to use for the cache is somewhat complex and trial and error may be needed to select optimal values. [htcacheclean](programs/htcacheclean) has two modes of operation. It can be run as persistent daemon, or periodically from cron. [htcacheclean](programs/htcacheclean) can take up to an hour or more to process very large (tens of gigabytes) caches and if you are running it from cron it is recommended that you determine how long a typical run takes, to avoid running more than one instance at a time. It is also recommended that an appropriate "nice" level is chosen for htcacheclean so that the tool does not cause excessive disk io while the server is running. Figure 1: Typical cache growth / clean sequence. Because `[mod\_cache\_disk](mod/mod_cache_disk)` does not itself pay attention to how much space is used you should ensure that [htcacheclean](programs/htcacheclean) is configured to leave enough "grow room" following a clean. ### Caching to memcached Using the `[mod\_cache\_socache](mod/mod_cache_socache)` module, `[mod\_cache](mod/mod_cache)` can cache data from a variety of implementations (aka: "providers"). Using the `[mod\_socache\_memcache](mod/mod_socache_memcache)` module, for example, one can specify that [memcached](http://memcached.org) is to be used as the the backend storage mechanism. Typically the module will be configured as so: ``` CacheEnable socache / CacheSocache memcache:memcd.example.com:11211 ``` Additional `memcached` servers can be specified by appending them to the end of the `CacheSocache memcache:` line separated by commas: ``` CacheEnable socache / CacheSocache memcache:mem1.example.com:11211,mem2.example.com:11212 ``` This format is also used with the other various `[mod\_cache\_socache](mod/mod_cache_socache)` providers. For example: ``` CacheEnable socache / CacheSocache shmcb:/path/to/datafile(512000) ``` ``` CacheEnable socache / CacheSocache dbm:/path/to/datafile ``` General Two-state Key/Value Shared Object Caching ------------------------------------------------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_authn\_socache](mod/mod_authn_socache)` * `[mod\_socache\_dbm](mod/mod_socache_dbm)` * `[mod\_socache\_dc](mod/mod_socache_dc)` * `[mod\_socache\_memcache](mod/mod_socache_memcache)` * `[mod\_socache\_shmcb](mod/mod_socache_shmcb)` * `[mod\_ssl](mod/mod_ssl)` | * `[AuthnCacheSOCache](mod/mod_authn_socache#authncachesocache)` * `[SSLSessionCache](mod/mod_ssl#sslsessioncache)` * `[SSLStaplingCache](mod/mod_ssl#sslstaplingcache)` | The Apache HTTP server offers a low level shared object cache for caching information such as SSL sessions, or authentication credentials, within the <socache> interface. Additional modules are provided for each implementation, offering the following backends: `[mod\_socache\_dbm](mod/mod_socache_dbm)` DBM based shared object cache. `[mod\_socache\_dc](mod/mod_socache_dc)` Distcache based shared object cache. `[mod\_socache\_memcache](mod/mod_socache_memcache)` Memcache based shared object cache. `[mod\_socache\_shmcb](mod/mod_socache_shmcb)` Shared memory based shared object cache. ### Caching Authentication Credentials | Related Modules | Related Directives | | --- | --- | | * `[mod\_authn\_socache](mod/mod_authn_socache)` | * `[AuthnCacheSOCache](mod/mod_authn_socache#authncachesocache)` | The `[mod\_authn\_socache](mod/mod_authn_socache)` module allows the result of authentication to be cached, relieving load on authentication backends. ### Caching SSL Sessions | Related Modules | Related Directives | | --- | --- | | * `[mod\_ssl](mod/mod_ssl)` | * `[SSLSessionCache](mod/mod_ssl#sslsessioncache)` * `[SSLStaplingCache](mod/mod_ssl#sslstaplingcache)` | The `[mod\_ssl](mod/mod_ssl)` module uses the `socache` interface to provide a session cache and a stapling cache. Specialized File Caching ------------------------ | Related Modules | Related Directives | | --- | --- | | * `[mod\_file\_cache](mod/mod_file_cache)` | * `[CacheFile](mod/mod_file_cache#cachefile)` * `[MMapFile](mod/mod_file_cache#mmapfile)` | On platforms where a filesystem might be slow, or where file handles are expensive, the option exists to pre-load files into memory on startup. On systems where opening files is slow, the option exists to open the file on startup and cache the file handle. These options can help on systems where access to static files is slow. ### File-Handle Caching The act of opening a file can itself be a source of delay, particularly on network filesystems. By maintaining a cache of open file descriptors for commonly served files, httpd can avoid this delay. Currently httpd provides one implementation of File-Handle Caching. #### CacheFile The most basic form of caching present in httpd is the file-handle caching provided by `[mod\_file\_cache](mod/mod_file_cache)`. Rather than caching file-contents, this cache maintains a table of open file descriptors. Files to be cached in this manner are specified in the configuration file using the `[CacheFile](mod/mod_file_cache#cachefile)` directive. The `[CacheFile](mod/mod_file_cache#cachefile)` directive instructs httpd to open the file when it is started and to re-use this file-handle for all subsequent access to this file. ``` CacheFile /usr/local/apache2/htdocs/index.html ``` If you intend to cache a large number of files in this manner, you must ensure that your operating system's limit for the number of open files is set appropriately. Although using `[CacheFile](mod/mod_file_cache#cachefile)` does not cause the file-contents to be cached per-se, it does mean that if the file changes while httpd is running these changes will not be picked up. The file will be consistently served as it was when httpd was started. If the file is removed while httpd is running, it will continue to maintain an open file descriptor and serve the file as it was when httpd was started. This usually also means that although the file will have been deleted, and not show up on the filesystem, extra free space will not be recovered until httpd is stopped and the file descriptor closed. ### In-Memory Caching Serving directly from system memory is universally the fastest method of serving content. Reading files from a disk controller or, even worse, from a remote network is orders of magnitude slower. Disk controllers usually involve physical processes, and network access is limited by your available bandwidth. Memory access on the other hand can take mere nano-seconds. System memory isn't cheap though, byte for byte it's by far the most expensive type of storage and it's important to ensure that it is used efficiently. By caching files in memory you decrease the amount of memory available on the system. As we'll see, in the case of operating system caching, this is not so much of an issue, but when using httpd's own in-memory caching it is important to make sure that you do not allocate too much memory to a cache. Otherwise the system will be forced to swap out memory, which will likely degrade performance. #### Operating System Caching Almost all modern operating systems cache file-data in memory managed directly by the kernel. This is a powerful feature, and for the most part operating systems get it right. For example, on Linux, let's look at the difference in the time it takes to read a file for the first time and the second time; ``` colm@coroebus:~$ time cat testfile > /dev/null real 0m0.065s user 0m0.000s sys 0m0.001s colm@coroebus:~$ time cat testfile > /dev/null real 0m0.003s user 0m0.003s sys 0m0.000s ``` Even for this small file, there is a huge difference in the amount of time it takes to read the file. This is because the kernel has cached the file contents in memory. By ensuring there is "spare" memory on your system, you can ensure that more and more file-contents will be stored in this cache. This can be a very efficient means of in-memory caching, and involves no extra configuration of httpd at all. Additionally, because the operating system knows when files are deleted or modified, it can automatically remove file contents from the cache when necessary. This is a big advantage over httpd's in-memory caching which has no way of knowing when a file has changed. Despite the performance and advantages of automatic operating system caching there are some circumstances in which in-memory caching may be better performed by httpd. #### MMapFile Caching `[mod\_file\_cache](mod/mod_file_cache)` provides the `[MMapFile](mod/mod_file_cache#mmapfile)` directive, which allows you to have httpd map a static file's contents into memory at start time (using the mmap system call). httpd will use the in-memory contents for all subsequent accesses to this file. ``` MMapFile /usr/local/apache2/htdocs/index.html ``` As with the `[CacheFile](mod/mod_file_cache#cachefile)` directive, any changes in these files will not be picked up by httpd after it has started. The `[MMapFile](mod/mod_file_cache#mmapfile)` directive does not keep track of how much memory it allocates, so you must ensure not to over-use the directive. Each httpd child process will replicate this memory, so it is critically important to ensure that the files mapped are not so large as to cause the system to swap memory. Security Considerations ----------------------- ### Authorization and Access Control Using `[mod\_cache](mod/mod_cache)` in its default state where `[CacheQuickHandler](mod/mod_cache#cachequickhandler)` is set to `On` is very much like having a caching reverse-proxy bolted to the front of the server. Requests will be served by the caching module unless it determines that the origin server should be queried just as an external cache would, and this drastically changes the security model of httpd. As traversing a filesystem hierarchy to examine potential `.htaccess` files would be a very expensive operation, partially defeating the point of caching (to speed up requests), `[mod\_cache](mod/mod_cache)` makes no decision about whether a cached entity is authorised for serving. In other words; if `[mod\_cache](mod/mod_cache)` has cached some content, it will be served from the cache as long as that content has not expired. If, for example, your configuration permits access to a resource by IP address you should ensure that this content is not cached. You can do this by using the `[CacheDisable](mod/mod_cache#cachedisable)` directive, or `[mod\_expires](mod/mod_expires)`. Left unchecked, `[mod\_cache](mod/mod_cache)` - very much like a reverse proxy - would cache the content when served and then serve it to any client, on any IP address. When the `[CacheQuickHandler](mod/mod_cache#cachequickhandler)` directive is set to `Off`, the full set of request processing phases are executed and the security model remains unchanged. ### Local exploits As requests to end-users can be served from the cache, the cache itself can become a target for those wishing to deface or interfere with content. It is important to bear in mind that the cache must at all times be writable by the user which httpd is running as. This is in stark contrast to the usually recommended situation of maintaining all content unwritable by the Apache user. If the Apache user is compromised, for example through a flaw in a CGI process, it is possible that the cache may be targeted. When using `[mod\_cache\_disk](mod/mod_cache_disk)`, it is relatively easy to insert or modify a cached entity. This presents a somewhat elevated risk in comparison to the other types of attack it is possible to make as the Apache user. If you are using `[mod\_cache\_disk](mod/mod_cache_disk)` you should bear this in mind - ensure you upgrade httpd when security upgrades are announced and run CGI processes as a non-Apache user using [suEXEC](suexec) if possible. ### Cache Poisoning When running httpd as a caching proxy server, there is also the potential for so-called cache poisoning. Cache Poisoning is a broad term for attacks in which an attacker causes the proxy server to retrieve incorrect (and usually undesirable) content from the origin server. For example if the DNS servers used by your system running httpd are vulnerable to DNS cache poisoning, an attacker may be able to control where httpd connects to when requesting content from the origin server. Another example is so-called HTTP request-smuggling attacks. This document is not the correct place for an in-depth discussion of HTTP request smuggling (instead, try your favourite search engine) however it is important to be aware that it is possible to make a series of requests, and to exploit a vulnerability on an origin webserver such that the attacker can entirely control the content retrieved by the proxy. ### Denial of Service / Cachebusting The Vary mechanism allows multiple variants of the same URL to be cached side by side. Depending on header values provided by the client, the cache will select the correct variant to return to the client. This mechanism can become a problem when an attempt is made to vary on a header that is known to contain a wide range of possible values under normal use, for example the `User-Agent` header. Depending on the popularity of the particular web site thousands or millions of duplicate cache entries could be created for the same URL, crowding out other entries in the cache. In other cases, there may be a need to change the URL of a particular resource on every request, usually by adding a "cachebuster" string to the URL. If this content is declared cacheable by a server for a significant freshness lifetime, these entries can crowd out legitimate entries in a cache. While `[mod\_cache](mod/mod_cache)` provides a `[CacheIgnoreURLSessionIdentifiers](mod/mod_cache#cacheignoreurlsessionidentifiers)` directive, this directive should be used with care to ensure that downstream proxy or browser caches aren't subjected to the same denial of service issue.
programming_docs
apache_http_server Apache HTTP Server Version 2.4 Documentation Apache HTTP Server Version 2.4 Documentation ============================================ Release Notes ------------- * [New features with Apache 2.3/2.4](https://httpd.apache.org/docs/2.4/en/new_features_2_4.html) * [New features with Apache 2.1/2.2](https://httpd.apache.org/docs/2.4/en/new_features_2_2.html) * [New features with Apache 2.0](https://httpd.apache.org/docs/2.4/en/new_features_2_0.html) * [Upgrading to 2.4 from 2.2](https://httpd.apache.org/docs/2.4/en/upgrading.html) * [Apache License](https://httpd.apache.org/docs/2.4/en/license.html) Reference Manual ---------------- * [Compiling and Installing](install) * [Starting](invoking) * [Stopping or Restarting](stopping) * [Run-time Configuration Directives](https://httpd.apache.org/docs/2.4/en/mod/quickreference.html) * [Modules](mod/index) * [Multi-Processing Modules (MPMs)](mpm) * [Filters](filter) * [Handlers](handler) * [Expression parser](expr) * [Override Class Index for .htaccess](mod/overrides) * [Server and Supporting Programs](programs/index) * [Glossary](https://httpd.apache.org/docs/2.4/en/glossary.html) Users' Guide ------------ * [Getting Started](getting-started) * [Binding to Addresses and Ports](bind) * [Configuration Files](configuring) * [Configuration Sections](sections) * [Content Caching](caching) * [Content Negotiation](content-negotiation) * [Dynamic Shared Objects (DSO)](dso) * [Environment Variables](env) * [Log Files](logs) * [Mapping URLs to the Filesystem](urlmapping) * [Performance Tuning](misc/perf-tuning) * [Security Tips](misc/security_tips) * [Server-Wide Configuration](server-wide) * [SSL/TLS Encryption](ssl/index) * [Suexec Execution for CGI](suexec) * [URL Rewriting with mod\_rewrite](rewrite/index) * [Virtual Hosts](vhosts/index) How-To / Tutorials ------------------ * [Authentication and Authorization](howto/auth) * [Access Control](howto/access) * [CGI: Dynamic Content](howto/cgi) * [.htaccess files](howto/htaccess) * [Server Side Includes (SSI)](howto/ssi) * [Per-user Web Directories (public\_html)](howto/public_html) * [Reverse proxy setup guide](howto/reverse_proxy) * [HTTP/2 guide](howto/http2) Platform Specific Notes ----------------------- * [Microsoft Windows](platform/windows) * [RPM-based Systems (Redhat / CentOS / Fedora)](platform/rpm) * [Novell NetWare](platform/netware) * [EBCDIC Port](platform/ebcdic) Other Topics ------------ * [Frequently Asked Questions](http://wiki.apache.org/httpd/FAQ) * [Sitemap](https://httpd.apache.org/docs/2.4/en/sitemap.html) * [Documentation for Developers](https://httpd.apache.org/docs/2.4/en/developer/) * [Helping with the documentation](http://httpd.apache.org/docs-project/) * [Other Notes](misc/index) * [Wiki](http://wiki.apache.org/httpd/) apache_http_server Dynamic Shared Object (DSO) Support Dynamic Shared Object (DSO) Support =================================== The Apache HTTP Server is a modular program where the administrator can choose the functionality to include in the server by selecting a set of modules. Modules will be compiled as Dynamic Shared Objects (DSOs) that exist separately from the main `[httpd](programs/httpd)` binary file. DSO modules may be compiled at the time the server is built, or they may be compiled and added at a later time using the Apache Extension Tool (`[apxs](programs/apxs)`). Alternatively, the modules can be statically compiled into the `[httpd](programs/httpd)` binary when the server is built. This document describes how to use DSO modules as well as the theory behind their use. Implementation -------------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_so](mod/mod_so)` | * `[LoadModule](mod/mod_so#loadmodule)` | The DSO support for loading individual Apache httpd modules is based on a module named `[mod\_so](mod/mod_so)` which must be statically compiled into the Apache httpd core. It is the only module besides `[core](mod/core)` which cannot be put into a DSO itself. Practically all other distributed Apache httpd modules will then be placed into a DSO. After a module is compiled into a DSO named `mod_foo.so` you can use `[mod\_so](mod/mod_so)`'s `[LoadModule](mod/mod_so#loadmodule)` directive in your `httpd.conf` file to load this module at server startup or restart. The DSO builds for individual modules can be disabled via `[configure](programs/configure)`'s `--enable-mods-static` option as discussed in the [install documentation](install). To simplify this creation of DSO files for Apache httpd modules (especially for third-party modules) a support program named `[apxs](programs/apxs)` (APache eXtenSion) is available. It can be used to build DSO based modules *outside of* the Apache httpd source tree. The idea is simple: When installing Apache HTTP Server the `[configure](programs/configure)`'s `make install` procedure installs the Apache httpd C header files and puts the platform-dependent compiler and linker flags for building DSO files into the `[apxs](programs/apxs)` program. This way the user can use `[apxs](programs/apxs)` to compile his Apache httpd module sources without the Apache httpd distribution source tree and without having to fiddle with the platform-dependent compiler and linker flags for DSO support. Usage Summary ------------- To give you an overview of the DSO features of Apache HTTP Server 2.x, here is a short and concise summary: 1. Build and install a *distributed* Apache httpd module, say `mod_foo.c`, into its own DSO `mod_foo.so`: ``` $ ./configure --prefix=/path/to/install --enable-foo $ make install ``` 2. Configure Apache HTTP Server with all modules enabled. Only a basic set will be loaded during server startup. You can change the set of loaded modules by activating or deactivating the `[LoadModule](mod/mod_so#loadmodule)` directives in `httpd.conf`. ``` $ ./configure --enable-mods-shared=all $ make install ``` 3. Some modules are only useful for developers and will not be build. when using the module set *all*. To build all available modules including developer modules use *reallyall*. In addition the `[LoadModule](mod/mod_so#loadmodule)` directives for all built modules can be activated via the configure option `--enable-load-all-modules`. ``` $ ./configure --enable-mods-shared=reallyall --enable-load-all-modules $ make install ``` 4. Build and install a *third-party* Apache httpd module, say `mod_foo.c`, into its own DSO `mod_foo.so` *outside of* the Apache httpd source tree using `[apxs](programs/apxs)`: ``` $ cd /path/to/3rdparty $ apxs -cia mod_foo.c ``` In all cases, once the shared module is compiled, you must use a `[LoadModule](mod/mod_so#loadmodule)` directive in `httpd.conf` to tell Apache httpd to activate the module. See the [apxs documentation](programs/apxs) for more details. Background ---------- On modern Unix derivatives there exists a mechanism called dynamic linking/loading of *Dynamic Shared Objects* (DSO) which provides a way to build a piece of program code in a special format for loading it at run-time into the address space of an executable program. This loading can usually be done in two ways: automatically by a system program called `ld.so` when an executable program is started or manually from within the executing program via a programmatic system interface to the Unix loader through the system calls `dlopen()/dlsym()`. In the first way the DSO's are usually called *shared libraries* or *DSO libraries* and named `libfoo.so` or `libfoo.so.1.2`. They reside in a system directory (usually `/usr/lib`) and the link to the executable program is established at build-time by specifying `-lfoo` to the linker command. This hard-codes library references into the executable program file so that at start-time the Unix loader is able to locate `libfoo.so` in `/usr/lib`, in paths hard-coded via linker-options like `-R` or in paths configured via the environment variable `LD_LIBRARY_PATH`. It then resolves any (yet unresolved) symbols in the executable program which are available in the DSO. Symbols in the executable program are usually not referenced by the DSO (because it's a reusable library of general code) and hence no further resolving has to be done. The executable program has no need to do anything on its own to use the symbols from the DSO because the complete resolving is done by the Unix loader. (In fact, the code to invoke `ld.so` is part of the run-time startup code which is linked into every executable program which has been bound non-static). The advantage of dynamic loading of common library code is obvious: the library code needs to be stored only once, in a system library like `libc.so`, saving disk space for every program. In the second way the DSO's are usually called *shared objects* or *DSO files* and can be named with an arbitrary extension (although the canonical name is `foo.so`). These files usually stay inside a program-specific directory and there is no automatically established link to the executable program where they are used. Instead the executable program manually loads the DSO at run-time into its address space via `dlopen()`. At this time no resolving of symbols from the DSO for the executable program is done. But instead the Unix loader automatically resolves any (yet unresolved) symbols in the DSO from the set of symbols exported by the executable program and its already loaded DSO libraries (especially all symbols from the ubiquitous `libc.so`). This way the DSO gets knowledge of the executable program's symbol set as if it had been statically linked with it in the first place. Finally, to take advantage of the DSO's API the executable program has to resolve particular symbols from the DSO via `dlsym()` for later use inside dispatch tables *etc.* In other words: The executable program has to manually resolve every symbol it needs to be able to use it. The advantage of such a mechanism is that optional program parts need not be loaded (and thus do not spend memory) until they are needed by the program in question. When required, these program parts can be loaded dynamically to extend the base program's functionality. Although this DSO mechanism sounds straightforward there is at least one difficult step here: The resolving of symbols from the executable program for the DSO when using a DSO to extend a program (the second way). Why? Because "reverse resolving" DSO symbols from the executable program's symbol set is against the library design (where the library has no knowledge about the programs it is used by) and is neither available under all platforms nor standardized. In practice the executable program's global symbols are often not re-exported and thus not available for use in a DSO. Finding a way to force the linker to export all global symbols is the main problem one has to solve when using DSO for extending a program at run-time. The shared library approach is the typical one, because it is what the DSO mechanism was designed for, hence it is used for nearly all types of libraries the operating system provides. Advantages and Disadvantages ---------------------------- The above DSO based features have the following advantages: * The server package is more flexible at run-time because the server process can be assembled at run-time via `[LoadModule](mod/mod_so#loadmodule)` `httpd.conf` configuration directives instead of `[configure](programs/configure)` options at build-time. For instance, this way one is able to run different server instances (standard & SSL version, minimalistic & dynamic version [mod\_perl, mod\_php], *etc.*) with only one Apache httpd installation. * The server package can be easily extended with third-party modules even after installation. This is a great benefit for vendor package maintainers, who can create an Apache httpd core package and additional packages containing extensions like PHP, mod\_perl, mod\_security, *etc.* * Easier Apache httpd module prototyping, because with the DSO/`[apxs](programs/apxs)` pair you can both work outside the Apache httpd source tree and only need an `apxs -i` command followed by an `apachectl restart` to bring a new version of your currently developed module into the running Apache HTTP Server. DSO has the following disadvantages: * The server is approximately 20% slower at startup time because of the symbol resolving overhead the Unix loader now has to do. * The server is approximately 5% slower at execution time under some platforms, because position independent code (PIC) sometimes needs complicated assembler tricks for relative addressing, which are not necessarily as fast as absolute addressing. * Because DSO modules cannot be linked against other DSO-based libraries (`ld -lfoo`) on all platforms (for instance a.out-based platforms usually don't provide this functionality while ELF-based platforms do) you cannot use the DSO mechanism for all types of modules. Or in other words, modules compiled as DSO files are restricted to only use symbols from the Apache httpd core, from the C library (`libc`) and all other dynamic or static libraries used by the Apache httpd core, or from static library archives (`libfoo.a`) containing position independent code. The only chances to use other code is to either make sure the httpd core itself already contains a reference to it or loading the code yourself via `dlopen()`. apache_http_server Apache's Handler Use Apache's Handler Use ==================== This document describes the use of Apache's Handlers. What is a Handler ----------------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_actions](mod/mod_actions)` * `[mod\_asis](mod/mod_asis)` * `[mod\_cgi](mod/mod_cgi)` * `[mod\_imagemap](mod/mod_imagemap)` * `[mod\_info](mod/mod_info)` * `[mod\_mime](mod/mod_mime)` * `[mod\_negotiation](mod/mod_negotiation)` * `[mod\_status](mod/mod_status)` | * `[Action](mod/mod_actions#action)` * `[AddHandler](mod/mod_mime#addhandler)` * `[RemoveHandler](mod/mod_mime#removehandler)` * `[SetHandler](mod/core#sethandler)` | A "handler" is an internal Apache representation of the action to be performed when a file is called. Generally, files have implicit handlers, based on the file type. Normally, all files are simply served by the server, but certain file types are "handled" separately. Handlers may also be configured explicitly, based on either filename extensions or on location, without relation to file type. This is advantageous both because it is a more elegant solution, and because it also allows for both a type **and** a handler to be associated with a file. (See also [Files with Multiple Extensions](mod/mod_mime#multipleext).) Handlers can either be built into the server or included in a module, or they can be added with the `[Action](mod/mod_actions#action)` directive. The built-in handlers in the standard distribution are as follows: * **default-handler**: Send the file using the `default_handler()`, which is the handler used by default to handle static content. (core) * **send-as-is**: Send file with HTTP headers as is. (`[mod\_asis](mod/mod_asis)`) * **cgi-script**: Treat the file as a CGI script. (`[mod\_cgi](mod/mod_cgi)`) * **imap-file**: Parse as an imagemap rule file. (`[mod\_imagemap](mod/mod_imagemap)`) * **server-info**: Get the server's configuration information. (`[mod\_info](mod/mod_info)`) * **server-status**: Get the server's status report. (`[mod\_status](mod/mod_status)`) * **type-map**: Parse as a type map file for content negotiation. (`[mod\_negotiation](mod/mod_negotiation)`) Examples -------- ### Modifying static content using a CGI script The following directives will cause requests for files with the `html` extension to trigger the launch of the `footer.pl` CGI script. ``` Action add-footer /cgi-bin/footer.pl AddHandler add-footer .html ``` Then the CGI script is responsible for sending the originally requested document (pointed to by the `PATH_TRANSLATED` environment variable) and making whatever modifications or additions are desired. ### Files with HTTP headers The following directives will enable the `send-as-is` handler, which is used for files which contain their own HTTP headers. All files in the `/web/htdocs/asis/` directory will be processed by the `send-as-is` handler, regardless of their filename extensions. ``` <Directory "/web/htdocs/asis"> SetHandler send-as-is </Directory> ``` Programmer's Note ----------------- In order to implement the handler features, an addition has been made to the [Apache API](https://httpd.apache.org/docs/2.4/en/developer/API.html) that you may wish to make use of. Specifically, a new record has been added to the `request_rec` structure: ``` char *handler ``` If you wish to have your module engage a handler, you need only to set `r->handler` to the name of the handler at any time prior to the `invoke_handler` stage of the request. Handlers are implemented as they were before, albeit using the handler name instead of a content type. While it is not necessary, the naming convention for handlers is to use a dash-separated word, with no slashes, so as to not invade the media type name-space. apache_http_server Starting Apache Starting Apache =============== On Windows, Apache is normally run as a service. For details, see [Running Apache as a Service](platform/windows#winsvc). On Unix, the `[httpd](programs/httpd)` program is run as a daemon that executes continuously in the background to handle requests. This document describes how to invoke `[httpd](programs/httpd)`. How Apache Starts ----------------- If the `[Listen](mod/mpm_common#listen)` specified in the configuration file is default of 80 (or any other port below 1024), then it is necessary to have root privileges in order to start apache, so that it can bind to this privileged port. Once the server has started and performed a few preliminary activities such as opening its log files, it will launch several *child* processes which do the work of listening for and answering requests from clients. The main `httpd` process continues to run as the root user, but the child processes run as a less privileged user. This is controlled by the selected [Multi-Processing Module](mpm). The recommended method of invoking the `[httpd](programs/httpd)` executable is to use the `[apachectl](programs/apachectl)` control script. This script sets certain environment variables that are necessary for `[httpd](programs/httpd)` to function correctly under some operating systems, and then invokes the `[httpd](programs/httpd)` binary. `[apachectl](programs/apachectl)` will pass through any command line arguments, so any `[httpd](programs/httpd)` options may also be used with `[apachectl](programs/apachectl)`. You may also directly edit the `[apachectl](programs/apachectl)` script by changing the `HTTPD` variable near the top to specify the correct location of the `[httpd](programs/httpd)` binary and any command-line arguments that you wish to be *always* present. The first thing that `[httpd](programs/httpd)` does when it is invoked is to locate and read the [configuration file](configuring) `httpd.conf`. The location of this file is set at compile-time, but it is possible to specify its location at run time using the `-f` command-line option as in ``` /usr/local/apache2/bin/apachectl -f /usr/local/apache2/conf/httpd.conf ``` If all goes well during startup, the server will detach from the terminal and the command prompt will return almost immediately. This indicates that the server is up and running. You can then use your browser to connect to the server and view the test page in the `[DocumentRoot](mod/core#documentroot)` directory. Errors During Start-up ---------------------- If Apache suffers a fatal problem during startup, it will write a message describing the problem either to the console or to the `[ErrorLog](mod/core#errorlog)` before exiting. One of the most common error messages is "`Unable to bind to Port ...`". This message is usually caused by either: * Trying to start the server on a privileged port when not logged in as the root user; or * Trying to start the server when there is another instance of Apache or some other web server already bound to the same Port. For further trouble-shooting instructions, consult the Apache [FAQ](http://wiki.apache.org/httpd/FAQ). Starting at Boot-Time --------------------- If you want your server to continue running after a system reboot, you should add a call to `[apachectl](programs/apachectl)` to your system startup files (typically `rc.local` or a file in an `rc.N` directory). This will start Apache as root. Before doing this ensure that your server is properly configured for security and access restrictions. The `[apachectl](programs/apachectl)` script is designed to act like a standard SysV init script; it can take the arguments `start`, `restart`, and `stop` and translate them into the appropriate signals to `[httpd](programs/httpd)`. So you can often simply link `[apachectl](programs/apachectl)` into the appropriate init directory. But be sure to check the exact requirements of your system. Additional Information ---------------------- Additional information about the command-line options of `[httpd](programs/httpd)` and `[apachectl](programs/apachectl)` as well as other support programs included with the server is available on the [Server and Supporting Programs](programs/index) page. There is also documentation on all the [modules](mod/index) included with the Apache distribution and the [directives](https://httpd.apache.org/docs/2.4/en/mod/directives.html) that they provide.
programming_docs
apache_http_server Multi-Processing Modules (MPMs) Multi-Processing Modules (MPMs) =============================== This document describes what a Multi-Processing Module is and how they are used by the Apache HTTP Server. Introduction ------------ The Apache HTTP Server is designed to be a powerful and flexible web server that can work on a very wide variety of platforms in a range of different environments. Different platforms and different environments often require different features, or may have different ways of implementing the same feature most efficiently. Apache httpd has always accommodated a wide variety of environments through its modular design. This design allows the webmaster to choose which features will be included in the server by selecting which modules to load either at compile-time or at run-time. Apache HTTP Server 2.0 extends this modular design to the most basic functions of a web server. The server ships with a selection of Multi-Processing Modules (MPMs) which are responsible for binding to network ports on the machine, accepting requests, and dispatching children to handle the requests. Extending the modular design to this level of the server allows two important benefits: * Apache httpd can more cleanly and efficiently support a wide variety of operating systems. In particular, the Windows version of the server is now much more efficient, since `[mpm\_winnt](mod/mpm_winnt)` can use native networking features in place of the POSIX layer used in Apache httpd 1.3. This benefit also extends to other operating systems that implement specialized MPMs. * The server can be better customized for the needs of the particular site. For example, sites that need a great deal of scalability can choose to use a threaded MPM like `[worker](mod/worker)` or `[event](mod/event)`, while sites requiring stability or compatibility with older software can use a `[prefork](mod/prefork)`. At the user level, MPMs appear much like other Apache httpd modules. The main difference is that one and only one MPM must be loaded into the server at any time. The list of available MPMs appears on the [module index page](mod/index). MPM Defaults ------------ The following table lists the default MPMs for various operating systems. This will be the MPM selected if you do not make another choice at compile-time. | | | | --- | --- | | Netware | `mpm_netware` | | OS/2 | `mpmt_os2` | | Unix | `[prefork](mod/prefork)`, `[worker](mod/worker)`, or `[event](mod/event)`, depending on platform capabilities | | Windows | `mpm_winnt` | Here, 'Unix' is used to mean Unix-like operating systems, such as Linux, BSD, Solaris, Mac OS X, etc. In the case of Unix, the decision as to which MPM is installed is based on two questions: 1. Does the system support threads? 2. Does the system support thread-safe polling (Specifically, the kqueue and epoll functions)? If the answer to both questions is 'yes', the default MPM is `[event](mod/event)`. If The answer to #1 is 'yes', but the answer to #2 is 'no', the default will be `[worker](mod/worker)`. If the answer to both questions is 'no', then the default MPM will be `[prefork](mod/prefork)`. In practical terms, this means that the default will almost always be `[event](mod/event)`, as all modern operating systems support these two features. Building an MPM as a static module ---------------------------------- MPMs can be built as static modules on all platforms. A single MPM is chosen at build time and linked into the server. The server must be rebuilt in order to change the MPM. To override the default MPM choice, use the `--with-mpm=*NAME*` option of the `[configure](programs/configure)` script. *NAME* is the name of the desired MPM. Once the server has been compiled, it is possible to determine which MPM was chosen by using `./httpd -l`. This command will list every module that is compiled into the server, including the MPM. Building an MPM as a DSO module ------------------------------- On Unix and similar platforms, MPMs can be built as DSO modules and dynamically loaded into the server in the same manner as other DSO modules. Building MPMs as DSO modules allows the MPM to be changed by updating the `[LoadModule](mod/mod_so#loadmodule)` directive for the MPM instead of by rebuilding the server. ``` LoadModule mpm_prefork_module modules/mod_mpm_prefork.so ``` Attempting to `[LoadModule](mod/mod_so#loadmodule)` more than one MPM will result in a startup failure with the following error. ``` AH00534: httpd: Configuration error: More than one MPM loaded. ``` This feature is enabled using the `--enable-mpms-shared` option of the `[configure](programs/configure)` script. With argument `*all*`, all possible MPMs for the platform will be installed. Alternately, a list of MPMs can be specified as the argument. The default MPM, either selected automatically or specified with the `--with-mpm` option of the `[configure](programs/configure)` script, will be loaded in the generated server configuration file. Edit the `[LoadModule](mod/mod_so#loadmodule)` directive to select a different MPM. apache_http_server Binding to Addresses and Ports Binding to Addresses and Ports ============================== Configuring Apache HTTP Server to listen on specific addresses and ports. Overview -------- | Related Modules | Related Directives | | --- | --- | | * `[core](mod/core)` * `[mpm\_common](mod/mpm_common)` | * `[<VirtualHost>](mod/core#virtualhost)` * `[Listen](mod/mpm_common#listen)` | When httpd starts, it binds to some port and address on the local machine and waits for incoming requests. By default, it listens to all addresses on the machine. However, it may need to be told to listen on specific ports, or only on selected addresses, or a combination of both. This is often combined with the [Virtual Host](vhosts/index) feature, which determines how `httpd` responds to different IP addresses, hostnames and ports. The `[Listen](mod/mpm_common#listen)` directive tells the server to accept incoming requests only on the specified port(s) or address-and-port combinations. If only a port number is specified in the `[Listen](mod/mpm_common#listen)` directive, the server listens to the given port on all interfaces. If an IP address is given as well as a port, the server will listen on the given port and interface. Multiple `[Listen](mod/mpm_common#listen)` directives may be used to specify a number of addresses and ports to listen on. The server will respond to requests from any of the listed addresses and ports. For example, to make the server accept connections on both port 80 and port 8000, on all interfaces, use: ``` Listen 80 Listen 8000 ``` To make the server accept connections on port 80 for one interface, and port 8000 on another, use ``` Listen 192.0.2.1:80 Listen 192.0.2.5:8000 ``` IPv6 addresses must be enclosed in square brackets, as in the following example: ``` Listen [2001:db8::a00:20ff:fea7:ccea]:80 ``` Overlapping `[Listen](mod/mpm_common#listen)` directives will result in a fatal error which will prevent the server from starting up. ``` (48)Address already in use: make_sock: could not bind to address [::]:80 ``` See [the discussion in the wiki](http://wiki.apache.org/httpd/CouldNotBindToAddress) for further troubleshooting tips. Changing Listen configuration on restart ---------------------------------------- When httpd is restarted, special consideration must be made for changes to `[Listen](mod/mpm_common#listen)` directives. During a restart, httpd keeps ports bound (as in the original configuration) to avoid generating "Connection refused" errors for any new attempts to connect to the server. If changes are made to the set of `[Listen](mod/mpm_common#listen)` directives used which conflict with the old configuration, configuration will fail and the server will terminate. For example, changing from configuration: ``` Listen 127.0.0.1:80 ``` to the following may fail, because binding to port 80 across all addresses conflicts with binding to port 80 on just 127.0.0.1. ``` Listen 80 ``` To have such configuration changes take effect, it is necessary to stop and then start the server. Special IPv6 Considerations --------------------------- A growing number of platforms implement IPv6, and [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary") supports IPv6 on most of these platforms, allowing httpd to allocate IPv6 sockets, and to handle requests sent over IPv6. One complicating factor for httpd administrators is whether or not an IPv6 socket can handle both IPv4 connections and IPv6 connections. Handling IPv4 connections with an IPv6 socket uses IPv4-mapped IPv6 addresses, which are allowed by default on most platforms, but are disallowed by default on FreeBSD, NetBSD, and OpenBSD, in order to match the system-wide policy on those platforms. On systems where it is disallowed by default, a special `[configure](programs/configure)` parameter can change this behavior for httpd. On the other hand, on some platforms, such as Linux and Tru64, the **only** way to handle both IPv6 and IPv4 is to use mapped addresses. If you want `httpd` to handle IPv4 and IPv6 connections with a minimum of sockets, which requires using IPv4-mapped IPv6 addresses, specify the `--enable-v4-mapped` `[configure](programs/configure)` option. `--enable-v4-mapped` is the default on all platforms except FreeBSD, NetBSD, and OpenBSD, so this is probably how your httpd was built. If you want httpd to handle IPv4 connections only, regardless of what your platform and APR will support, specify an IPv4 address on all `[Listen](mod/mpm_common#listen)` directives, as in the following examples: ``` Listen 0.0.0.0:80 Listen 192.0.2.1:80 ``` If your platform supports it and you want httpd to handle IPv4 and IPv6 connections on separate sockets (i.e., to disable IPv4-mapped addresses), specify the `--disable-v4-mapped` `[configure](programs/configure)` option. `--disable-v4-mapped` is the default on FreeBSD, NetBSD, and OpenBSD. Specifying the protocol with Listen ----------------------------------- The optional second protocol argument of `[Listen](mod/mpm_common#listen)` is not required for most configurations. If not specified, `https` is the default for port 443 and `http` the default for all other ports. The protocol is used to determine which module should handle a request, and to apply protocol specific optimizations with the `[AcceptFilter](mod/core#acceptfilter)` directive. You only need to set the protocol if you are running on non-standard ports. For example, running an `https` site on port 8443: ``` Listen 192.170.2.1:8443 https ``` How This Works With Virtual Hosts --------------------------------- The `[Listen](mod/mpm_common#listen)` directive does not implement Virtual Hosts - it only tells the main server what addresses and ports to listen on. If no `[<VirtualHost>](mod/core#virtualhost)` directives are used, the server will behave in the same way for all accepted requests. However, `[<VirtualHost>](mod/core#virtualhost)` can be used to specify a different behavior for one or more of the addresses or ports. To implement a VirtualHost, the server must first be told to listen to the address and port to be used. Then a `[<VirtualHost>](mod/core#virtualhost)` section should be created for the specified address and port to set the behavior of this virtual host. Note that if the `[<VirtualHost>](mod/core#virtualhost)` is set for an address and port that the server is not listening to, it cannot be accessed. apache_http_server Configuration Sections Configuration Sections ====================== Directives in the [configuration files](configuring) may apply to the entire server, or they may be restricted to apply only to particular directories, files, hosts, or URLs. This document describes how to use configuration section containers or `.htaccess` files to change the scope of other configuration directives. Types of Configuration Section Containers ----------------------------------------- | Related Modules | Related Directives | | --- | --- | | * `[core](mod/core)` * `[mod\_version](mod/mod_version)` * `[mod\_proxy](mod/mod_proxy)` | * `[<Directory>](mod/core#directory)` * `[<DirectoryMatch>](mod/core#directorymatch)` * `[<Files>](mod/core#files)` * `[<FilesMatch>](mod/core#filesmatch)` * `[<If>](mod/core#if)` * `[<IfDefine>](mod/core#ifdefine)` * `[<IfModule>](mod/core#ifmodule)` * `[<IfVersion>](mod/mod_version#ifversion)` * `[<Location>](mod/core#location)` * `[<LocationMatch>](mod/core#locationmatch)` * `[<MDomainSet>](mod/mod_md#mdomainsetsection)` * `[<Proxy>](mod/mod_proxy#proxy)` * `[<ProxyMatch>](mod/mod_proxy#proxymatch)` * `[<VirtualHost>](mod/core#virtualhost)` | There are two basic types of containers. Most containers are evaluated for each request. The enclosed directives are applied only for those requests that match the containers. The `[<IfDefine>](mod/core#ifdefine)`, `[<IfModule>](mod/core#ifmodule)`, and `[<IfVersion>](mod/mod_version#ifversion)` containers, on the other hand, are evaluated only at server startup and restart. If their conditions are true at startup, then the enclosed directives will apply to all requests. If the conditions are not true, the enclosed directives will be ignored. The `[<IfDefine>](mod/core#ifdefine)` directive encloses directives that will only be applied if an appropriate parameter is defined on the `[httpd](programs/httpd)` command line. For example, with the following configuration, all requests will be redirected to another site only if the server is started using `httpd -DClosedForNow`: ``` <IfDefine ClosedForNow> Redirect "/" "http://otherserver.example.com/" </IfDefine> ``` The `[<IfModule>](mod/core#ifmodule)` directive is very similar, except it encloses directives that will only be applied if a particular module is available in the server. The module must either be statically compiled in the server, or it must be dynamically compiled and its `[LoadModule](mod/mod_so#loadmodule)` line must be earlier in the configuration file. This directive should only be used if you need your configuration file to work whether or not certain modules are installed. It should not be used to enclose directives that you want to work all the time, because it can suppress useful error messages about missing modules. In the following example, the `[MimeMagicFile](mod/mod_mime_magic#mimemagicfile)` directive will be applied only if `[mod\_mime\_magic](mod/mod_mime_magic)` is available. ``` <IfModule mod_mime_magic.c> MimeMagicFile "conf/magic" </IfModule> ``` The `[<IfVersion>](mod/mod_version#ifversion)` directive is very similar to `[<IfDefine>](mod/core#ifdefine)` and `[<IfModule>](mod/core#ifmodule)`, except it encloses directives that will only be applied if a particular version of the server is executing. This module is designed for the use in test suites and large networks which have to deal with different httpd versions and different configurations. ``` <IfVersion >= 2.4> # this happens only in versions greater or # equal 2.4.0. </IfVersion> ``` `[<IfDefine>](mod/core#ifdefine)`, `[<IfModule>](mod/core#ifmodule)`, and the `[<IfVersion>](mod/mod_version#ifversion)` can apply negative conditions by preceding their test with "!". Also, these sections can be nested to achieve more complex restrictions. Filesystem, Webspace, and Boolean Expressions --------------------------------------------- The most commonly used configuration section containers are the ones that change the configuration of particular places in the filesystem or webspace. First, it is important to understand the difference between the two. The filesystem is the view of your disks as seen by your operating system. For example, in a default install, Apache httpd resides at `/usr/local/apache2` in the Unix filesystem or `"c:/Program Files/Apache Group/Apache2"` in the Windows filesystem. (Note that forward slashes should always be used as the path separator in Apache httpd configuration files, even for Windows.) In contrast, the webspace is the view of your site as delivered by the web server and seen by the client. So the path `/dir/` in the webspace corresponds to the path `/usr/local/apache2/htdocs/dir/` in the filesystem of a default Apache httpd install on Unix. The webspace need not map directly to the filesystem, since webpages may be generated dynamically from databases or other locations. ### Filesystem Containers The `[<Directory>](mod/core#directory)` and `[<Files>](mod/core#files)` directives, along with their [regex](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") counterparts, apply directives to parts of the filesystem. Directives enclosed in a `[<Directory>](mod/core#directory)` section apply to the named filesystem directory and all subdirectories of that directory (as well as the files in those directories). The same effect can be obtained using [.htaccess files](howto/htaccess). For example, in the following configuration, directory indexes will be enabled for the `/var/web/dir1` directory and all subdirectories. ``` <Directory "/var/web/dir1"> Options +Indexes </Directory> ``` Directives enclosed in a `[<Files>](mod/core#files)` section apply to any file with the specified name, regardless of what directory it lies in. So for example, the following configuration directives will, when placed in the main section of the configuration file, deny access to any file named `private.html` regardless of where it is found. ``` <Files "private.html"> Require all denied </Files> ``` To address files found in a particular part of the filesystem, the `[<Files>](mod/core#files)` and `[<Directory>](mod/core#directory)` sections can be combined. For example, the following configuration will deny access to `/var/web/dir1/private.html`, `/var/web/dir1/subdir2/private.html`, `/var/web/dir1/subdir3/private.html`, and any other instance of `private.html` found under the `/var/web/dir1/` directory. ``` <Directory "/var/web/dir1"> <Files "private.html"> Require all denied </Files> </Directory> ``` ### Webspace Containers The `[<Location>](mod/core#location)` directive and its [regex](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") counterpart, on the other hand, change the configuration for content in the webspace. For example, the following configuration prevents access to any URL-path that begins in /private. In particular, it will apply to requests for `http://yoursite.example.com/private`, `http://yoursite.example.com/private123`, and `http://yoursite.example.com/private/dir/file.html` as well as any other requests starting with the `/private` string. ``` <LocationMatch "^/private"> Require all denied </LocationMatch> ``` The `[<Location>](mod/core#location)` directive need not have anything to do with the filesystem. For example, the following example shows how to map a particular URL to an internal Apache HTTP Server handler provided by `[mod\_status](mod/mod_status)`. No file called `server-status` needs to exist in the filesystem. ``` <Location "/server-status"> SetHandler server-status </Location> ``` ### Overlapping Webspace In order to have two overlapping URLs one has to consider the order in which certain sections or directives are evaluated. For `[<Location>](mod/core#location)` this would be: ``` <Location "/foo"> </Location> <Location "/foo/bar"> </Location> ``` `[<Alias>](mod/mod_alias#alias)`es on the other hand, are mapped vice-versa: ``` Alias "/foo/bar" "/srv/www/uncommon/bar" Alias "/foo" "/srv/www/common/foo" ``` The same is true for the `[ProxyPass](mod/mod_proxy#proxypass)` directives: ``` ProxyPass "/special-area" "http://special.example.com" smax=5 max=10 ProxyPass "/" "balancer://mycluster/" stickysession=JSESSIONID|jsessionid nofailover=On ``` ### Wildcards and Regular Expressions The `[<Directory>](mod/core#directory)`, `[<Files>](mod/core#files)`, and `[<Location>](mod/core#location)` directives can each use shell-style wildcard characters as in `fnmatch` from the C standard library. The character "\*" matches any sequence of characters, "?" matches any single character, and "[*seq*]" matches any character in *seq*. The "/" character will not be matched by any wildcard; it must be specified explicitly. If even more flexible matching is required, each container has a regular expression (regex) counterpart `[<DirectoryMatch>](mod/core#directorymatch)`, `[<FilesMatch>](mod/core#filesmatch)`, and `[<LocationMatch>](mod/core#locationmatch)` that allow perl-compatible [regular expressions](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") to be used in choosing the matches. But see the section below on configuration merging to find out how using regex sections will change how directives are applied. A non-regex wildcard section that changes the configuration of all user directories could look as follows: ``` <Directory "/home/*/public_html"> Options Indexes </Directory> ``` Using regex sections, we can deny access to many types of image files at once: ``` <FilesMatch "\.(?i:gif|jpe?g|png)$"> Require all denied </FilesMatch> ``` Regular expressions containing **named groups and backreferences** are added to the environment with the corresponding name in uppercase. This allows elements of filename paths and URLs to be referenced from within [expressions](expr) and modules like `[mod\_rewrite](mod/mod_rewrite)`. ``` <DirectoryMatch "^/var/www/combined/(?<SITENAME>[^/]+)"> Require ldap-group "cn=%{env:MATCH_SITENAME},ou=combined,o=Example" </DirectoryMatch> ``` ### Boolean expressions The `[<If>](mod/core#if)` directive change the configuration depending on a condition which can be expressed by a boolean expression. For example, the following configuration denies access if the HTTP Referer header does not start with "http://www.example.com/". ``` <If "!(%{HTTP_REFERER} -strmatch 'http://www.example.com/*')"> Require all denied </If> ``` ### What to use When Choosing between filesystem containers and webspace containers is actually quite easy. When applying directives to objects that reside in the filesystem always use `[<Directory>](mod/core#directory)` or `[<Files>](mod/core#files)`. When applying directives to objects that do not reside in the filesystem (such as a webpage generated from a database), use `[<Location>](mod/core#location)`. It is important to never use `[<Location>](mod/core#location)` when trying to restrict access to objects in the filesystem. This is because many different webspace locations (URLs) could map to the same filesystem location, allowing your restrictions to be circumvented. For example, consider the following configuration: ``` <Location "/dir/"> Require all denied </Location> ``` This works fine if the request is for `http://yoursite.example.com/dir/`. But what if you are on a case-insensitive filesystem? Then your restriction could be easily circumvented by requesting `http://yoursite.example.com/DIR/`. The `[<Directory>](mod/core#directory)` directive, in contrast, will apply to any content served from that location, regardless of how it is called. (An exception is filesystem links. The same directory can be placed in more than one part of the filesystem using symbolic links. The `[<Directory>](mod/core#directory)` directive will follow the symbolic link without resetting the pathname. Therefore, for the highest level of security, symbolic links should be disabled with the appropriate `[Options](mod/core#options)` directive.) If you are, perhaps, thinking that none of this applies to you because you use a case-sensitive filesystem, remember that there are many other ways to map multiple webspace locations to the same filesystem location. Therefore you should always use the filesystem containers when you can. There is, however, one exception to this rule. Putting configuration restrictions in a `<Location "/">` section is perfectly safe because this section will apply to all requests regardless of the specific URL. ### Nesting of sections Some section types can be nested inside other section types. On the one hand, `[<Files>](mod/core#files)` can be used inside `[<Directory>](mod/core#directory)`. On the other hand, `[<If>](mod/core#if)` can be used inside `[<Directory>](mod/core#directory)`, `[<Location>](mod/core#location)`, and `[<Files>](mod/core#files)` sections (but not inside another `[<If>](mod/core#if)`). The regex counterparts of the named section behave identically. Nested sections are merged after non-nested sections of the same type. Virtual Hosts ------------- The `[<VirtualHost>](mod/core#virtualhost)` container encloses directives that apply to specific hosts. This is useful when serving multiple hosts from the same machine with a different configuration for each. For more information, see the [Virtual Host Documentation](vhosts/index). Proxy ----- The `[<Proxy>](mod/mod_proxy#proxy)` and `[<ProxyMatch>](mod/mod_proxy#proxymatch)` containers apply enclosed configuration directives only to sites accessed through `[mod\_proxy](mod/mod_proxy)`'s proxy server that match the specified URL. For example, the following configuration will allow only a subset of clients to access the `www.example.com` website using the proxy server: ``` <Proxy "http://www.example.com/*"> Require host yournetwork.example.com </Proxy> ``` What Directives are Allowed? ---------------------------- To find out what directives are allowed in what types of configuration sections, check the Context of the directive. Everything that is allowed in `[<Directory>](mod/core#directory)` sections is also syntactically allowed in `[<DirectoryMatch>](mod/core#directorymatch)`, `[<Files>](mod/core#files)`, `[<FilesMatch>](mod/core#filesmatch)`, `[<Location>](mod/core#location)`, `[<LocationMatch>](mod/core#locationmatch)`, `[<Proxy>](mod/mod_proxy#proxy)`, and `[<ProxyMatch>](mod/mod_proxy#proxymatch)` sections. There are some exceptions, however: * The `[AllowOverride](mod/core#allowoverride)` directive works only in `[<Directory>](mod/core#directory)` sections. * The `FollowSymLinks` and `SymLinksIfOwnerMatch` `[Options](mod/core#options)` work only in `[<Directory>](mod/core#directory)` sections or `.htaccess` files. * The `[Options](mod/core#options)` directive cannot be used in `[<Files>](mod/core#files)` and `[<FilesMatch>](mod/core#filesmatch)` sections. How the sections are merged --------------------------- The configuration sections are applied in a very particular order. Since this can have important effects on how configuration directives are interpreted, it is important to understand how this works. The order of merging is: 1. `[<Directory>](mod/core#directory)` (except regular expressions) and `.htaccess` done simultaneously (with `.htaccess`, if allowed, overriding `[<Directory>](mod/core#directory)`) 2. `[<DirectoryMatch>](mod/core#directorymatch)` (and `<Directory "~">`) 3. `[<Files>](mod/core#files)` and `[<FilesMatch>](mod/core#filesmatch)` done simultaneously 4. `[<Location>](mod/core#location)` and `[<LocationMatch>](mod/core#locationmatch)` done simultaneously 5. `[<If>](mod/core#if)` Some important remarks: * Apart from `[<Directory>](mod/core#directory)`, within each group the sections are processed in the order they appear in the configuration files. For example, a request for */foo/bar* will match `<Location "/foo/bar">` and `<Location "/foo">` (group 4 in this case): both sections will be evaluated but in the order they appear in the configuration files. * `[<Directory>](mod/core#directory)` (group 1 above) is processed in the order shortest directory component to longest. For example, `<Directory "/var/web/dir">` will be processed before `<Directory "/var/web/dir/subdir">`. * If multiple `[<Directory>](mod/core#directory)` sections apply to the same directory they are processed in the configuration file order. * Configurations included via the `[Include](mod/core#include)` directive will be treated as if they were inside the including file at the location of the `[Include](mod/core#include)` directive. * Sections inside `[<VirtualHost>](mod/core#virtualhost)` sections are applied *after* the corresponding sections outside the virtual host definition. This allows virtual hosts to override the main server configuration. * When the request is served by `[mod\_proxy](mod/mod_proxy)`, the `[<Proxy>](mod/mod_proxy#proxy)` container takes the place of the `[<Directory>](mod/core#directory)` container in the processing order. **Technical Note** There is actually a `<Location>`/`<LocationMatch>` sequence performed just before the name translation phase (where `Aliases` and `DocumentRoots` are used to map URLs to filenames). The results of this sequence are completely thrown away after the translation has completed. ### Relationship between modules and configuration sections One question that often arises after reading how configuration sections are merged is related to how and when directives of specific modules like `[mod\_rewrite](mod/mod_rewrite)` are processed. The answer is not trivial and needs a bit of background. Each httpd module manages its own configuration, and each of its directives in httpd.conf specify one piece of configuration in a particular context. httpd does not execute a command as it is read. At runtime, the core of httpd iterates over the defined configuration sections in the order described above to determine which ones apply to the current request. When the first section matches, it is considered the current configuration for this request. If a subsequent section matches too, then each module with a directive in either of the sections is given a chance to merge its configuration between the two sections. The result is a third configuration, and the process goes on until all the configuration sections are evaluated. After the above step, the "real" processing of the HTTP request begins: each module has a chance to run and perform whatever tasks they like. They can retrieve their own final merged configuration from the core of the httpd to determine how they should act. An example can help to visualize the whole process. The following configuration uses the `[Header](mod/mod_headers#header)` directive of `[mod\_headers](mod/mod_headers)` to set a specific HTTP header. What value will httpd set in the `CustomHeaderName` header for a request to `/example/index.html` ? ``` <Directory "/"> Header set CustomHeaderName one <FilesMatch ".*"> Header set CustomHeaderName three </FilesMatch> </Directory> <Directory "/example"> Header set CustomHeaderName two </Directory> ``` * `Directory` "/" matches and an initial configuration to set the `CustomHeaderName` header with the value `one` is created. * `Directory` "/example" matches, and since `[mod\_headers](mod/mod_headers)` specifies in its code to override in case of a merge, a new configuration is created to set the `CustomHeaderName` header with the value `two`. * `FilesMatch` ".\*" matches and another merge opportunity arises, causing the `CustomHeaderName` header to be set with the value `three`. * Eventually during the next steps of the HTTP request processing `[mod\_headers](mod/mod_headers)` will be called and it will receive the configuration to set the `CustomHeaderName` header with the value `three`. `[mod\_headers](mod/mod_headers)` normally uses this configuration to perform its job, namely setting the foo header. This does not mean that a module can't perform a more complex action like discarding directives because not needed or deprecated, etc.. This is true for .htaccess too since they have the same priority as `Directory` in the merge order. The important concept to understand is that configuration sections like `Directory` and `FilesMatch` are not comparable to module specific directives like `[Header](mod/mod_headers#header)` or `[RewriteRule](mod/mod_rewrite#rewriterule)` because they operate on different levels. ### Some useful examples Below is an artificial example to show the order of merging. Assuming they all apply to the request, the directives in this example will be applied in the order A > B > C > D > E. ``` <Location "/"> E </Location> <Files "f.html"> D </Files> <VirtualHost *> <Directory "/a/b"> B </Directory> </VirtualHost> <DirectoryMatch "^.*b$"> C </DirectoryMatch> <Directory "/a/b"> A </Directory> ``` For a more concrete example, consider the following. Regardless of any access restrictions placed in `[<Directory>](mod/core#directory)` sections, the `[<Location>](mod/core#location)` section will be evaluated last and will allow unrestricted access to the server. In other words, order of merging is important, so be careful! ``` <Location "/"> Require all granted </Location> # Whoops! This <Directory> section will have no effect <Directory "/"> <RequireAll> Require all granted Require not host badguy.example.com </RequireAll> </Directory> ```
programming_docs
apache_http_server Content Negotiation Content Negotiation =================== Apache HTTPD supports content negotiation as described in the HTTP/1.1 specification. It can choose the best representation of a resource based on the browser-supplied preferences for media type, languages, character set and encoding. It also implements a couple of features to give more intelligent handling of requests from browsers that send incomplete negotiation information. Content negotiation is provided by the `[mod\_negotiation](mod/mod_negotiation)` module, which is compiled in by default. About Content Negotiation ------------------------- A resource may be available in several different representations. For example, it might be available in different languages or different media types, or a combination. One way of selecting the most appropriate choice is to give the user an index page, and let them select. However it is often possible for the server to choose automatically. This works because browsers can send, as part of each request, information about what representations they prefer. For example, a browser could indicate that it would like to see information in French, if possible, else English will do. Browsers indicate their preferences by headers in the request. To request only French representations, the browser would send ``` Accept-Language: fr ``` Note that this preference will only be applied when there is a choice of representations and they vary by language. As an example of a more complex request, this browser has been configured to accept French and English, but prefer French, and to accept various media types, preferring HTML over plain text or other text types, and preferring GIF or JPEG over other media types, but also allowing any other media type as a last resort: ``` Accept-Language: fr; q=1.0, en; q=0.5 Accept: text/html; q=1.0, text/*; q=0.8, image/gif; q=0.6, image/jpeg; q=0.6, image/*; q=0.5, */*; q=0.1 ``` httpd supports 'server driven' content negotiation, as defined in the HTTP/1.1 specification. It fully supports the `Accept`, `Accept-Language`, `Accept-Charset` and `Accept-Encoding` request headers. httpd also supports 'transparent' content negotiation, which is an experimental negotiation protocol defined in RFC 2295 and RFC 2296. It does not offer support for 'feature negotiation' as defined in these RFCs. A **resource** is a conceptual entity identified by a URI (RFC 2396). An HTTP server like Apache HTTP Server provides access to **representations** of the resource(s) within its namespace, with each representation in the form of a sequence of bytes with a defined media type, character set, encoding, etc. Each resource may be associated with zero, one, or more than one representation at any given time. If multiple representations are available, the resource is referred to as **negotiable** and each of its representations is termed a **variant**. The ways in which the variants for a negotiable resource vary are called the **dimensions** of negotiation. Negotiation in httpd -------------------- In order to negotiate a resource, the server needs to be given information about each of the variants. This is done in one of two ways: * Using a type map (*i.e.*, a `*.var` file) which names the files containing the variants explicitly, or * Using a 'MultiViews' search, where the server does an implicit filename pattern match and chooses from among the results. ### Using a type-map file A type map is a document which is associated with the handler named `type-map` (or, for backwards-compatibility with older httpd configurations, the [MIME-type](https://httpd.apache.org/docs/2.4/en/glossary.html#mime-type "see glossary") `application/x-type-map`). Note that to use this feature, you must have a handler set in the configuration that defines a file suffix as `type-map`; this is best done with ``` AddHandler type-map .var ``` in the server configuration file. Type map files should have the same name as the resource which they are describing, followed by the extension `.var`. In the examples shown below, the resource is named `foo`, so the type map file is named `foo.var`. This file should have an entry for each available variant; these entries consist of contiguous HTTP-format header lines. Entries for different variants are separated by blank lines. Blank lines are illegal within an entry. It is conventional to begin a map file with an entry for the combined entity as a whole (although this is not required, and if present will be ignored). An example map file is shown below. URIs in this file are relative to the location of the type map file. Usually, these files will be located in the same directory as the type map file, but this is not required. You may provide absolute or relative URIs for any file located on the same server as the map file. ``` URI: foo URI: foo.en.html Content-type: text/html Content-language: en URI: foo.fr.de.html Content-type: text/html;charset=iso-8859-2 Content-language: fr, de ``` Note also that a typemap file will take precedence over the filename's extension, even when Multiviews is on. If the variants have different source qualities, that may be indicated by the "qs" parameter to the media type, as in this picture (available as JPEG, GIF, or ASCII-art): ``` URI: foo URI: foo.jpeg Content-type: image/jpeg; qs=0.8 URI: foo.gif Content-type: image/gif; qs=0.5 URI: foo.txt Content-type: text/plain; qs=0.01 ``` qs values can vary in the range 0.000 to 1.000. Note that any variant with a qs value of 0.000 will never be chosen. Variants with no 'qs' parameter value are given a qs factor of 1.0. The qs parameter indicates the relative 'quality' of this variant compared to the other available variants, independent of the client's capabilities. For example, a JPEG file is usually of higher source quality than an ASCII file if it is attempting to represent a photograph. However, if the resource being represented is an original ASCII art, then an ASCII representation would have a higher source quality than a JPEG representation. A qs value is therefore specific to a given variant depending on the nature of the resource it represents. The full list of headers recognized is available in the [mod\_negotiation typemap](mod/mod_negotiation#typemaps) documentation. ### Multiviews `MultiViews` is a per-directory option, meaning it can be set with an `[Options](mod/core#options)` directive within a `[<Directory>](mod/core#directory)`, `[<Location>](mod/core#location)` or `[<Files>](mod/core#files)` section in `httpd.conf`, or (if `[AllowOverride](mod/core#allowoverride)` is properly set) in `.htaccess` files. Note that `Options All` does not set `MultiViews`; you have to ask for it by name. The effect of `MultiViews` is as follows: if the server receives a request for `/some/dir/foo`, if `/some/dir` has `MultiViews` enabled, and `/some/dir/foo` does *not* exist, then the server reads the directory looking for files named foo.\*, and effectively fakes up a type map which names all those files, assigning them the same media types and content-encodings it would have if the client had asked for one of them by name. It then chooses the best match to the client's requirements. `MultiViews` may also apply to searches for the file named by the `[DirectoryIndex](mod/mod_dir#directoryindex)` directive, if the server is trying to index a directory. If the configuration files specify ``` DirectoryIndex index ``` then the server will arbitrate between `index.html` and `index.html3` if both are present. If neither are present, and `index.cgi` is there, the server will run it. If one of the files found when reading the directory does not have an extension recognized by `mod_mime` to designate its Charset, Content-Type, Language, or Encoding, then the result depends on the setting of the `[MultiViewsMatch](mod/mod_mime#multiviewsmatch)` directive. This directive determines whether handlers, filters, and other extension types can participate in MultiViews negotiation. The Negotiation Methods ----------------------- After httpd has obtained a list of the variants for a given resource, either from a type-map file or from the filenames in the directory, it invokes one of two methods to decide on the 'best' variant to return, if any. It is not necessary to know any of the details of how negotiation actually takes place in order to use httpd's content negotiation features. However the rest of this document explains the methods used for those interested. There are two negotiation methods: 1. **Server driven negotiation with the httpd algorithm** is used in the normal case. The httpd algorithm is explained in more detail below. When this algorithm is used, httpd can sometimes 'fiddle' the quality factor of a particular dimension to achieve a better result. The ways httpd can fiddle quality factors is explained in more detail below. 2. **Transparent content negotiation** is used when the browser specifically requests this through the mechanism defined in RFC 2295. This negotiation method gives the browser full control over deciding on the 'best' variant, the result is therefore dependent on the specific algorithms used by the browser. As part of the transparent negotiation process, the browser can ask httpd to run the 'remote variant selection algorithm' defined in RFC 2296. ### Dimensions of Negotiation | Dimension | Notes | | --- | --- | | Media Type | Browser indicates preferences with the `Accept` header field. Each item can have an associated quality factor. Variant description can also have a quality factor (the "qs" parameter). | | Language | Browser indicates preferences with the `Accept-Language` header field. Each item can have a quality factor. Variants can be associated with none, one or more than one language. | | Encoding | Browser indicates preference with the `Accept-Encoding` header field. Each item can have a quality factor. | | Charset | Browser indicates preference with the `Accept-Charset` header field. Each item can have a quality factor. Variants can indicate a charset as a parameter of the media type. | ### httpd Negotiation Algorithm httpd can use the following algorithm to select the 'best' variant (if any) to return to the browser. This algorithm is not further configurable. It operates as follows: 1. First, for each dimension of the negotiation, check the appropriate *Accept\** header field and assign a quality to each variant. If the *Accept\** header for any dimension implies that this variant is not acceptable, eliminate it. If no variants remain, go to step 4. 2. Select the 'best' variant by a process of elimination. Each of the following tests is applied in order. Any variants not selected at each test are eliminated. After each test, if only one variant remains, select it as the best match and proceed to step 3. If more than one variant remains, move on to the next test. 1. Multiply the quality factor from the `Accept` header with the quality-of-source factor for this variants media type, and select the variants with the highest value. 2. Select the variants with the highest language quality factor. 3. Select the variants with the best language match, using either the order of languages in the `Accept-Language` header (if present), or else the order of languages in the `LanguagePriority` directive (if present). 4. Select the variants with the highest 'level' media parameter (used to give the version of text/html media types). 5. Select variants with the best charset media parameters, as given on the `Accept-Charset` header line. Charset ISO-8859-1 is acceptable unless explicitly excluded. Variants with a `text/*` media type but not explicitly associated with a particular charset are assumed to be in ISO-8859-1. 6. Select those variants which have associated charset media parameters that are *not* ISO-8859-1. If there are no such variants, select all variants instead. 7. Select the variants with the best encoding. If there are variants with an encoding that is acceptable to the user-agent, select only these variants. Otherwise if there is a mix of encoded and non-encoded variants, select only the unencoded variants. If either all variants are encoded or all variants are not encoded, select all variants. 8. Select the variants with the smallest content length. 9. Select the first variant of those remaining. This will be either the first listed in the type-map file, or when variants are read from the directory, the one whose file name comes first when sorted using ASCII code order. 3. The algorithm has now selected one 'best' variant, so return it as the response. The HTTP response header `Vary` is set to indicate the dimensions of negotiation (browsers and caches can use this information when caching the resource). End. 4. To get here means no variant was selected (because none are acceptable to the browser). Return a 406 status (meaning "No acceptable representation") with a response body consisting of an HTML document listing the available variants. Also set the HTTP `Vary` header to indicate the dimensions of variance. Fiddling with Quality Values ---------------------------- httpd sometimes changes the quality values from what would be expected by a strict interpretation of the httpd negotiation algorithm above. This is to get a better result from the algorithm for browsers which do not send full or accurate information. Some of the most popular browsers send `Accept` header information which would otherwise result in the selection of the wrong variant in many cases. If a browser sends full and correct information these fiddles will not be applied. ### Media Types and Wildcards The `Accept:` request header indicates preferences for media types. It can also include 'wildcard' media types, such as "image/\*" or "\*/\*" where the \* matches any string. So a request including: ``` Accept: image/*, */* ``` would indicate that any type starting "image/" is acceptable, as is any other type. Some browsers routinely send wildcards in addition to explicit types they can handle. For example: ``` Accept: text/html, text/plain, image/gif, image/jpeg, */* ``` The intention of this is to indicate that the explicitly listed types are preferred, but if a different representation is available, that is ok too. Using explicit quality values, what the browser really wants is something like: ``` Accept: text/html, text/plain, image/gif, image/jpeg, */*; q=0.01 ``` The explicit types have no quality factor, so they default to a preference of 1.0 (the highest). The wildcard \*/\* is given a low preference of 0.01, so other types will only be returned if no variant matches an explicitly listed type. If the `Accept:` header contains *no* q factors at all, httpd sets the q value of "\*/\*", if present, to 0.01 to emulate the desired behavior. It also sets the q value of wildcards of the format "type/\*" to 0.02 (so these are preferred over matches against "\*/\*". If any media type on the `Accept:` header contains a q factor, these special values are *not* applied, so requests from browsers which send the explicit information to start with work as expected. ### Language Negotiation Exceptions New in httpd 2.0, some exceptions have been added to the negotiation algorithm to allow graceful fallback when language negotiation fails to find a match. When a client requests a page on your server, but the server cannot find a single page that matches the `Accept-language` sent by the browser, the server will return either a "No Acceptable Variant" or "Multiple Choices" response to the client. To avoid these error messages, it is possible to configure httpd to ignore the `Accept-language` in these cases and provide a document that does not explicitly match the client's request. The `[ForceLanguagePriority](mod/mod_negotiation#forcelanguagepriority)` directive can be used to override one or both of these error messages and substitute the servers judgement in the form of the `[LanguagePriority](mod/mod_negotiation#languagepriority)` directive. The server will also attempt to match language-subsets when no other match can be found. For example, if a client requests documents with the language `en-GB` for British English, the server is not normally allowed by the HTTP/1.1 standard to match that against a document that is marked as simply `en`. (Note that it is almost surely a configuration error to include `en-GB` and not `en` in the `Accept-Language` header, since it is very unlikely that a reader understands British English, but doesn't understand English in general. Unfortunately, many current clients have default configurations that resemble this.) However, if no other language match is possible and the server is about to return a "No Acceptable Variants" error or fallback to the `[LanguagePriority](mod/mod_negotiation#languagepriority)`, the server will ignore the subset specification and match `en-GB` against `en` documents. Implicitly, httpd will add the parent language to the client's acceptable language list with a very low quality value. But note that if the client requests "en-GB; q=0.9, fr; q=0.8", and the server has documents designated "en" and "fr", then the "fr" document will be returned. This is necessary to maintain compliance with the HTTP/1.1 specification and to work effectively with properly configured clients. In order to support advanced techniques (such as cookies or special URL-paths) to determine the user's preferred language, since httpd 2.0.47 `[mod\_negotiation](mod/mod_negotiation)` recognizes the [environment variable](env) `prefer-language`. If it exists and contains an appropriate language tag, `[mod\_negotiation](mod/mod_negotiation)` will try to select a matching variant. If there's no such variant, the normal negotiation process applies. ### Example ``` SetEnvIf Cookie "language=(.+)" prefer-language=$1 Header append Vary cookie ``` Extensions to Transparent Content Negotiation --------------------------------------------- httpd extends the transparent content negotiation protocol (RFC 2295) as follows. A new `{encoding ..}` element is used in variant lists to label variants which are available with a specific content-encoding only. The implementation of the RVSA/1.0 algorithm (RFC 2296) is extended to recognize encoded variants in the list, and to use them as candidate variants whenever their encodings are acceptable according to the `Accept-Encoding` request header. The RVSA/1.0 implementation does not round computed quality factors to 5 decimal places before choosing the best variant. Note on hyperlinks and naming conventions ----------------------------------------- If you are using language negotiation you can choose between different naming conventions, because files can have more than one extension, and the order of the extensions is normally irrelevant (see the [mod\_mime](mod/mod_mime#multipleext) documentation for details). A typical file has a MIME-type extension (*e.g.*, `html`), maybe an encoding extension (*e.g.*, `gz`), and of course a language extension (*e.g.*, `en`) when we have different language variants of this file. Examples: * foo.en.html * foo.html.en * foo.en.html.gz Here some more examples of filenames together with valid and invalid hyperlinks: | Filename | Valid hyperlink | Invalid hyperlink | | --- | --- | --- | | *foo.html.en* | foo foo.html | - | | *foo.en.html* | foo | foo.html | | *foo.html.en.gz* | foo foo.html | foo.gz foo.html.gz | | *foo.en.html.gz* | foo | foo.html foo.html.gz foo.gz | | *foo.gz.html.en* | foo foo.gz foo.gz.html | foo.html | | *foo.html.gz.en* | foo foo.html foo.html.gz | foo.gz | Looking at the table above, you will notice that it is always possible to use the name without any extensions in a hyperlink (*e.g.*, `foo`). The advantage is that you can hide the actual type of a document rsp. file and can change it later, *e.g.*, from `html` to `shtml` or `cgi` without changing any hyperlink references. If you want to continue to use a MIME-type in your hyperlinks (*e.g.* `foo.html`) the language extension (including an encoding extension if there is one) must be on the right hand side of the MIME-type extension (*e.g.*, `foo.html.en`). Note on Caching --------------- When a cache stores a representation, it associates it with the request URL. The next time that URL is requested, the cache can use the stored representation. But, if the resource is negotiable at the server, this might result in only the first requested variant being cached and subsequent cache hits might return the wrong response. To prevent this, httpd normally marks all responses that are returned after content negotiation as non-cacheable by HTTP/1.0 clients. httpd also supports the HTTP/1.1 protocol features to allow caching of negotiated responses. For requests which come from a HTTP/1.0 compliant client (either a browser or a cache), the directive `[CacheNegotiatedDocs](mod/mod_negotiation#cachenegotiateddocs)` can be used to allow caching of responses which were subject to negotiation. This directive can be given in the server config or virtual host, and takes no arguments. It has no effect on requests from HTTP/1.1 clients. For HTTP/1.1 clients, httpd sends a `Vary` HTTP response header to indicate the negotiation dimensions for the response. Caches can use this information to determine whether a subsequent request can be served from the local copy. To encourage a cache to use the local copy regardless of the negotiation dimensions, set the `force-no-vary` [environment variable](env#special).
programming_docs
apache_http_server Mapping URLs to Filesystem Locations Mapping URLs to Filesystem Locations ==================================== This document explains how the Apache HTTP Server uses the URL of a request to determine the filesystem location from which to serve a file. Related Modules and Directives ------------------------------ | Related Modules | Related Directives | | --- | --- | | * `[mod\_actions](mod/mod_actions)` * `[mod\_alias](mod/mod_alias)` * `[mod\_autoindex](mod/mod_autoindex)` * `[mod\_dir](mod/mod_dir)` * `[mod\_imagemap](mod/mod_imagemap)` * `[mod\_negotiation](mod/mod_negotiation)` * `[mod\_proxy](mod/mod_proxy)` * `[mod\_rewrite](mod/mod_rewrite)` * `[mod\_speling](mod/mod_speling)` * `[mod\_userdir](mod/mod_userdir)` * `[mod\_vhost\_alias](mod/mod_vhost_alias)` | * `[Alias](mod/mod_alias#alias)` * `[AliasMatch](mod/mod_alias#aliasmatch)` * `[CheckSpelling](mod/mod_speling#checkspelling)` * `[DirectoryIndex](mod/mod_dir#directoryindex)` * `[DocumentRoot](mod/core#documentroot)` * `[ErrorDocument](mod/core#errordocument)` * `[Options](mod/core#options)` * `[ProxyPass](mod/mod_proxy#proxypass)` * `[ProxyPassReverse](mod/mod_proxy#proxypassreverse)` * `[ProxyPassReverseCookieDomain](mod/mod_proxy#proxypassreversecookiedomain)` * `[ProxyPassReverseCookiePath](mod/mod_proxy#proxypassreversecookiepath)` * `[Redirect](mod/mod_alias#redirect)` * `[RedirectMatch](mod/mod_alias#redirectmatch)` * `[RewriteCond](mod/mod_rewrite#rewritecond)` * `[RewriteRule](mod/mod_rewrite#rewriterule)` * `[ScriptAlias](mod/mod_alias#scriptalias)` * `[ScriptAliasMatch](mod/mod_alias#scriptaliasmatch)` * `[UserDir](mod/mod_userdir#userdir)` | DocumentRoot ------------ In deciding what file to serve for a given request, httpd's default behavior is to take the URL-Path for the request (the part of the URL following the hostname and port) and add it to the end of the `[DocumentRoot](mod/core#documentroot)` specified in your configuration files. Therefore, the files and directories underneath the `[DocumentRoot](mod/core#documentroot)` make up the basic document tree which will be visible from the web. For example, if `[DocumentRoot](mod/core#documentroot)` were set to `/var/www/html` then a request for `http://www.example.com/fish/guppies.html` would result in the file `/var/www/html/fish/guppies.html` being served to the requesting client. If a directory is requested (i.e. a path ending with `/`), the file served from that directory is defined by the `[DirectoryIndex](mod/mod_dir#directoryindex)` directive. For example, if `DocumentRoot` were set as above, and you were to set: ``` DirectoryIndex index.html index.php ``` Then a request for `http://www.example.com/fish/` will cause httpd to attempt to serve the file `/var/www/html/fish/index.html`. In the event that that file does not exist, it will next attempt to serve the file `/var/www/html/fish/index.php`. If neither of these files existed, the next step is to attempt to provide a directory index, if `[mod\_autoindex](mod/mod_autoindex)` is loaded and configured to permit that. httpd is also capable of [Virtual Hosting](vhosts/index), where the server receives requests for more than one host. In this case, a different `[DocumentRoot](mod/core#documentroot)` can be specified for each virtual host, or alternatively, the directives provided by the module `[mod\_vhost\_alias](mod/mod_vhost_alias)` can be used to dynamically determine the appropriate place from which to serve content based on the requested IP address or hostname. The `[DocumentRoot](mod/core#documentroot)` directive is set in your main server configuration file (`httpd.conf`) and, possibly, once per additional [Virtual Host](vhosts/index) you create. Files Outside the DocumentRoot ------------------------------ There are frequently circumstances where it is necessary to allow web access to parts of the filesystem that are not strictly underneath the `[DocumentRoot](mod/core#documentroot)`. httpd offers several different ways to accomplish this. On Unix systems, symbolic links can bring other parts of the filesystem under the `[DocumentRoot](mod/core#documentroot)`. For security reasons, httpd will follow symbolic links only if the `[Options](mod/core#options)` setting for the relevant directory includes `FollowSymLinks` or `SymLinksIfOwnerMatch`. Alternatively, the `[Alias](mod/mod_alias#alias)` directive will map any part of the filesystem into the web space. For example, with ``` Alias "/docs" "/var/web" ``` the URL `http://www.example.com/docs/dir/file.html` will be served from `/var/web/dir/file.html`. The `[ScriptAlias](mod/mod_alias#scriptalias)` directive works the same way, with the additional effect that all content located at the target path is treated as [CGI](https://httpd.apache.org/docs/2.4/en/glossary.html#cgi "see glossary") scripts. For situations where you require additional flexibility, you can use the `[AliasMatch](mod/mod_alias#aliasmatch)` and `[ScriptAliasMatch](mod/mod_alias#scriptaliasmatch)` directives to do powerful [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") based matching and substitution. For example, ``` ScriptAliasMatch "^/~([a-zA-Z0-9]+)/cgi-bin/(.+)" "/home/$1/cgi-bin/$2" ``` will map a request to `http://example.com/~user/cgi-bin/script.cgi` to the path `/home/user/cgi-bin/script.cgi` and will treat the resulting file as a CGI script. User Directories ---------------- Traditionally on Unix systems, the home directory of a particular *user* can be referred to as `~user/`. The module `[mod\_userdir](mod/mod_userdir)` extends this idea to the web by allowing files under each user's home directory to be accessed using URLs such as the following. `http://www.example.com/~user/file.html` For security reasons, it is inappropriate to give direct access to a user's home directory from the web. Therefore, the `[UserDir](mod/mod_userdir#userdir)` directive specifies a directory underneath the user's home directory where web files are located. Using the default setting of `Userdir public_html`, the above URL maps to a file at a directory like `/home/user/public_html/file.html` where `/home/user/` is the user's home directory as specified in `/etc/passwd`. There are also several other forms of the `Userdir` directive which you can use on systems where `/etc/passwd` does not contain the location of the home directory. Some people find the "~" symbol (which is often encoded on the web as `%7e`) to be awkward and prefer to use an alternate string to represent user directories. This functionality is not supported by mod\_userdir. However, if users' home directories are structured in a regular way, then it is possible to use the `[AliasMatch](mod/mod_alias#aliasmatch)` directive to achieve the desired effect. For example, to make `http://www.example.com/upages/user/file.html` map to `/home/user/public_html/file.html`, use the following `AliasMatch` directive: ``` AliasMatch "^/upages/([a-zA-Z0-9]+)(/(.*))?$" "/home/$1/public_html/$3" ``` URL Redirection --------------- The configuration directives discussed in the above sections tell httpd to get content from a specific place in the filesystem and return it to the client. Sometimes, it is desirable instead to inform the client that the requested content is located at a different URL, and instruct the client to make a new request with the new URL. This is called *redirection* and is implemented by the `[Redirect](mod/mod_alias#redirect)` directive. For example, if the contents of the directory `/foo/` under the `[DocumentRoot](mod/core#documentroot)` are moved to the new directory `/bar/`, you can instruct clients to request the content at the new location as follows: ``` Redirect permanent "/foo/" "http://www.example.com/bar/" ``` This will redirect any URL-Path starting in `/foo/` to the same URL path on the `www.example.com` server with `/bar/` substituted for `/foo/`. You can redirect clients to any server, not only the origin server. httpd also provides a `[RedirectMatch](mod/mod_alias#redirectmatch)` directive for more complicated rewriting problems. For example, to redirect requests for the site home page to a different site, but leave all other requests alone, use the following configuration: ``` RedirectMatch permanent "^/$" "http://www.example.com/startpage.html" ``` Alternatively, to temporarily redirect all pages on one site to a particular page on another site, use the following: ``` RedirectMatch temp ".*" "http://othersite.example.com/startpage.html" ``` Reverse Proxy ------------- httpd also allows you to bring remote documents into the URL space of the local server. This technique is called *reverse proxying* because the web server acts like a proxy server by fetching the documents from a remote server and returning them to the client. It is different from normal (forward) proxying because, to the client, it appears the documents originate at the reverse proxy server. In the following example, when clients request documents under the `/foo/` directory, the server fetches those documents from the `/bar/` directory on `internal.example.com` and returns them to the client as if they were from the local server. ``` ProxyPass "/foo/" "http://internal.example.com/bar/" ProxyPassReverse "/foo/" "http://internal.example.com/bar/" ProxyPassReverseCookieDomain internal.example.com public.example.com ProxyPassReverseCookiePath "/foo/" "/bar/" ``` The `[ProxyPass](mod/mod_proxy#proxypass)` configures the server to fetch the appropriate documents, while the `[ProxyPassReverse](mod/mod_proxy#proxypassreverse)` directive rewrites redirects originating at `internal.example.com` so that they target the appropriate directory on the local server. Similarly, the `[ProxyPassReverseCookieDomain](mod/mod_proxy#proxypassreversecookiedomain)` and `[ProxyPassReverseCookiePath](mod/mod_proxy#proxypassreversecookiepath)` rewrite cookies set by the backend server. It is important to note, however, that links inside the documents will not be rewritten. So any absolute links on `internal.example.com` will result in the client breaking out of the proxy server and requesting directly from `internal.example.com`. You can modify these links (and other content) in a page as it is being served to the client using `[mod\_substitute](mod/mod_substitute)`. ``` Substitute "s/internal\.example\.com/www.example.com/i" ``` For more sophisticated rewriting of links in HTML and XHTML, the `[mod\_proxy\_html](mod/mod_proxy_html)` module is also available. It allows you to create maps of URLs that need to be rewritten, so that complex proxying scenarios can be handled. Rewriting Engine ---------------- When even more powerful substitution is required, the rewriting engine provided by `[mod\_rewrite](mod/mod_rewrite)` can be useful. The directives provided by this module can use characteristics of the request such as browser type or source IP address in deciding from where to serve content. In addition, mod\_rewrite can use external database files or programs to determine how to handle a request. The rewriting engine is capable of performing all three types of mappings discussed above: internal redirects (aliases), external redirects, and proxying. Many practical examples employing mod\_rewrite are discussed in the [detailed mod\_rewrite documentation](rewrite/index). File Not Found -------------- Inevitably, URLs will be requested for which no matching file can be found in the filesystem. This can happen for several reasons. In some cases, it can be a result of moving documents from one location to another. In this case, it is best to use [URL redirection](#redirect) to inform clients of the new location of the resource. In this way, you can assure that old bookmarks and links will continue to work, even though the resource is at a new location. Another common cause of "File Not Found" errors is accidental mistyping of URLs, either directly in the browser, or in HTML links. httpd provides the module `[mod\_speling](mod/mod_speling)` (sic) to help with this problem. When this module is activated, it will intercept "File Not Found" errors and look for a resource with a similar filename. If one such file is found, mod\_speling will send an HTTP redirect to the client informing it of the correct location. If several "close" files are found, a list of available alternatives will be presented to the client. An especially useful feature of mod\_speling, is that it will compare filenames without respect to case. This can help systems where users are unaware of the case-sensitive nature of URLs and the unix filesystem. But using mod\_speling for anything more than the occasional URL correction can place additional load on the server, since each "incorrect" request is followed by a URL redirection and a new request from the client. `[mod\_dir](mod/mod_dir)` provides `[FallbackResource](mod/mod_dir#fallbackresource)`, which can be used to map virtual URIs to a real resource, which then serves them. This is a very useful replacement for `[mod\_rewrite](mod/mod_rewrite)` when implementing a 'front controller' If all attempts to locate the content fail, httpd returns an error page with HTTP status code 404 (file not found). The appearance of this page is controlled with the `[ErrorDocument](mod/core#errordocument)` directive and can be customized in a flexible manner as discussed in the [Custom error responses](custom-error) document. Other URL Mapping Modules ------------------------- Other modules available for URL mapping include: * `[mod\_actions](mod/mod_actions)` - Maps a request to a CGI script based on the request method, or resource MIME type. * `[mod\_dir](mod/mod_dir)` - Provides basic mapping of a trailing slash into an index file such as `index.html`. * `[mod\_imagemap](mod/mod_imagemap)` - Maps a request to a URL based on where a user clicks on an image embedded in a HTML document. * `[mod\_negotiation](mod/mod_negotiation)` - Selects an appropriate document based on client preferences such as language or content compression. apache_http_server Shared Object Cache in Apache HTTP Server Shared Object Cache in Apache HTTP Server ========================================= The Shared Object Cache provides a means to share simple data across all a server's workers, regardless of [thread and process models](mpm). It is used where the advantages of sharing data across processes outweigh the performance overhead of inter-process communication. Shared Object Cache Providers ----------------------------- The shared object cache as such is an abstraction. Five different modules implement it. To use the cache, one or more of these modules must be present, and configured. The only configuration required is to select which cache provider to use. This is the responsibility of modules using the cache, and they enable selection using directives such as `[CacheSocache](mod/mod_cache_socache#cachesocache)`, `[AuthnCacheSOCache](mod/mod_authn_socache#authncachesocache)`, `[SSLSessionCache](mod/mod_ssl#sslsessioncache)`, and `[SSLStaplingCache](mod/mod_ssl#sslstaplingcache)`. Currently available providers are: "dbm" (`[mod\_socache\_dbm](mod/mod_socache_dbm)`) This makes use of a DBM hash file. The choice of underlying DBM used may be configurable if the installed APR version supports multiple DBM implementations. "dc" (`[mod\_socache\_dc](mod/mod_socache_dc)`) This makes use of the [distcache](http://distcache.sourceforge.net/) distributed session caching libraries. "memcache" (`[mod\_socache\_memcache](mod/mod_socache_memcache)`) This makes use of the [memcached](http://memcached.org/) high-performance, distributed memory object caching system. "redis" (`[mod\_socache\_redis](mod/mod_socache_redis)`) This makes use of the [Redis](http://redis.io/) high-performance, distributed memory object caching system. "shmcb" (`[mod\_socache\_shmcb](mod/mod_socache_shmcb)`) This makes use of a high-performance cyclic buffer inside a shared memory segment. The API provides the following functions: const char \*create(ap\_socache\_instance\_t \*\*instance, const char \*arg, apr\_pool\_t \*tmp, apr\_pool\_t \*p); Create a session cache based on the given configuration string. The instance pointer returned in the instance parameter will be passed as the first argument to subsequent invocations. apr\_status\_t init(ap\_socache\_instance\_t \*instance, const char \*cname, const struct ap\_socache\_hints \*hints, server\_rec \*s, apr\_pool\_t \*pool) Initialize the cache. The cname must be of maximum length 16 characters, and uniquely identifies the consumer of the cache within the server; using the module name is recommended, e.g. "mod\_ssl-sess". This string may be used within a filesystem path so use of only alphanumeric [a-z0-9\_-] characters is recommended. If hints is non-NULL, it gives a set of hints for the provider. Return APR error code. void destroy(ap\_socache\_instance\_t \*instance, server\_rec \*s) Destroy a given cache instance object. apr\_status\_t store(ap\_socache\_instance\_t \*instance, server\_rec \*s, const unsigned char \*id, unsigned int idlen, apr\_time\_t expiry, unsigned char \*data, unsigned int datalen, apr\_pool\_t \*pool) Store an object in a cache instance. apr\_status\_t retrieve(ap\_socache\_instance\_t \*instance, server\_rec \*s, const unsigned char \*id, unsigned int idlen, unsigned char \*data, unsigned int \*datalen, apr\_pool\_t \*pool) Retrieve a cached object. apr\_status\_t remove(ap\_socache\_instance\_t \*instance, server\_rec \*s, const unsigned char \*id, unsigned int idlen, apr\_pool\_t \*pool) Remove an object from the cache. void status(ap\_socache\_instance\_t \*instance, request\_rec \*r, int flags) Dump the status of a cache instance for mod\_status. apr\_status\_t iterate(ap\_socache\_instance\_t \*instance, server\_rec \*s, void \*userctx, ap\_socache\_iterator\_t \*iterator, apr\_pool\_t \*pool) Dump all cached objects through an iterator callback. apache_http_server Environment Variables in Apache Environment Variables in Apache =============================== There are two kinds of environment variables that affect the Apache HTTP Server. First, there are the environment variables controlled by the underlying operating system. These are set before the server starts. They can be used in expansions in configuration files, and can optionally be passed to CGI scripts and SSI using the PassEnv directive. Second, the Apache HTTP Server provides a mechanism for storing information in named variables that are also called *environment variables*. This information can be used to control various operations such as logging or access control. The variables are also used as a mechanism to communicate with external programs such as CGI scripts. This document discusses different ways to manipulate and use these variables. Although these variables are referred to as *environment variables*, they are not the same as the environment variables controlled by the underlying operating system. Instead, these variables are stored and manipulated in an internal Apache structure. They only become actual operating system environment variables when they are provided to CGI scripts and Server Side Include scripts. If you wish to manipulate the operating system environment under which the server itself runs, you must use the standard environment manipulation mechanisms provided by your operating system shell. Setting Environment Variables ----------------------------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_cache](mod/mod_cache)` * `[mod\_env](mod/mod_env)` * `[mod\_rewrite](mod/mod_rewrite)` * `[mod\_setenvif](mod/mod_setenvif)` * `[mod\_unique\_id](mod/mod_unique_id)` | * `[BrowserMatch](mod/mod_setenvif#browsermatch)` * `[BrowserMatchNoCase](mod/mod_setenvif#browsermatchnocase)` * `[PassEnv](mod/mod_env#passenv)` * `[RewriteRule](mod/mod_rewrite#rewriterule)` * `[SetEnv](mod/mod_env#setenv)` * `[SetEnvIf](mod/mod_setenvif#setenvif)` * `[SetEnvIfNoCase](mod/mod_setenvif#setenvifnocase)` * `[UnsetEnv](mod/mod_env#unsetenv)` | ### Basic Environment Manipulation The most basic way to set an environment variable in Apache is using the unconditional `[SetEnv](mod/mod_env#setenv)` directive. Variables may also be passed from the environment of the shell which started the server using the `[PassEnv](mod/mod_env#passenv)` directive. ### Conditional Per-Request Settings For additional flexibility, the directives provided by `[mod\_setenvif](mod/mod_setenvif)` allow environment variables to be set on a per-request basis, conditional on characteristics of particular requests. For example, a variable could be set only when a specific browser (User-Agent) is making a request, or only when a specific Referer [sic] header is found. Even more flexibility is available through the `[mod\_rewrite](mod/mod_rewrite)`'s `[RewriteRule](mod/mod_rewrite#rewriterule)` which uses the `[E=...]` option to set environment variables. ### Unique Identifiers Finally, `[mod\_unique\_id](mod/mod_unique_id)` sets the environment variable `UNIQUE_ID` for each request to a value which is guaranteed to be unique across "all" requests under very specific conditions. ### Standard CGI Variables In addition to all environment variables set within the Apache configuration and passed from the shell, CGI scripts and SSI pages are provided with a set of environment variables containing meta-information about the request as required by the [CGI specification](http://www.ietf.org/rfc/rfc3875). ### Some Caveats * It is not possible to override or change the standard CGI variables using the environment manipulation directives. * When `[suexec](programs/suexec)` is used to launch CGI scripts, the environment will be cleaned down to a set of *safe* variables before CGI scripts are launched. The list of *safe* variables is defined at compile-time in `suexec.c`. * For portability reasons, the names of environment variables may contain only letters, numbers, and the underscore character. In addition, the first character may not be a number. Characters which do not match this restriction will be replaced by an underscore when passed to CGI scripts and SSI pages. * A special case are HTTP headers which are passed to CGI scripts and the like via environment variables (see below). They are converted to uppercase and only dashes are replaced with underscores; if the header contains any other (invalid) character, the whole header is silently dropped. See [below](#fixheader) for a workaround. * The `[SetEnv](mod/mod_env#setenv)` directive runs late during request processing meaning that directives such as `[SetEnvIf](mod/mod_setenvif#setenvif)` and `[RewriteCond](mod/mod_rewrite#rewritecond)` will not see the variables set with it. * When the server looks up a path via an internal [subrequest](https://httpd.apache.org/docs/2.4/en/glossary.html#subrequest "see glossary") such as looking for a `[DirectoryIndex](mod/mod_dir#directoryindex)` or generating a directory listing with `[mod\_autoindex](mod/mod_autoindex)`, per-request environment variables are *not* inherited in the subrequest. Additionally, `[SetEnvIf](mod/mod_setenvif#setenvif)` directives are not separately evaluated in the subrequest due to the API phases `[mod\_setenvif](mod/mod_setenvif)` takes action in. Using Environment Variables --------------------------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_authz\_host](mod/mod_authz_host)` * `[mod\_cgi](mod/mod_cgi)` * `[mod\_ext\_filter](mod/mod_ext_filter)` * `[mod\_headers](mod/mod_headers)` * `[mod\_include](mod/mod_include)` * `[mod\_log\_config](mod/mod_log_config)` * `[mod\_rewrite](mod/mod_rewrite)` | * `[Require](mod/mod_authz_core#require)` * `[CustomLog](mod/mod_log_config#customlog)` * `[Allow](mod/mod_access_compat#allow)` * `[Deny](mod/mod_access_compat#deny)` * `[ExtFilterDefine](mod/mod_ext_filter#extfilterdefine)` * `[Header](mod/mod_headers#header)` * `[LogFormat](mod/mod_log_config#logformat)` * `[RewriteCond](mod/mod_rewrite#rewritecond)` * `[RewriteRule](mod/mod_rewrite#rewriterule)` | ### CGI Scripts One of the primary uses of environment variables is to communicate information to CGI scripts. As discussed above, the environment passed to CGI scripts includes standard meta-information about the request in addition to any variables set within the Apache configuration. For more details, see the [CGI tutorial](howto/cgi). ### SSI Pages Server-parsed (SSI) documents processed by `[mod\_include](mod/mod_include)`'s `INCLUDES` filter can print environment variables using the `echo` element, and can use environment variables in flow control elements to makes parts of a page conditional on characteristics of a request. Apache also provides SSI pages with the standard CGI environment variables as discussed above. For more details, see the [SSI tutorial](howto/ssi). ### Access Control Access to the server can be controlled based on environment variables using the `Require env` and `Require not env` directives. In combination with `[SetEnvIf](mod/mod_setenvif#setenvif)`, this allows for flexible control of access to the server based on characteristics of the client. For example, you can use these directives to deny access to a particular browser (User-Agent). ### Conditional Logging Environment variables can be logged in the access log using the `[LogFormat](mod/mod_log_config#logformat)` option `%e`. In addition, the decision on whether or not to log requests can be made based on the status of environment variables using the conditional form of the `[CustomLog](mod/mod_log_config#customlog)` directive. In combination with `[SetEnvIf](mod/mod_setenvif#setenvif)` this allows for flexible control of which requests are logged. For example, you can choose not to log requests for filenames ending in `gif`, or you can choose to only log requests from clients which are outside your subnet. ### Conditional Response Headers The `[Header](mod/mod_headers#header)` directive can use the presence or absence of an environment variable to determine whether or not a certain HTTP header will be placed in the response to the client. This allows, for example, a certain response header to be sent only if a corresponding header is received in the request from the client. ### External Filter Activation External filters configured by `[mod\_ext\_filter](mod/mod_ext_filter)` using the `[ExtFilterDefine](mod/mod_ext_filter#extfilterdefine)` directive can by activated conditional on an environment variable using the `disableenv=` and `enableenv=` options. ### URL Rewriting The `%{ENV:*variable*}` form of *TestString* in the `[RewriteCond](mod/mod_rewrite#rewritecond)` allows `[mod\_rewrite](mod/mod_rewrite)`'s rewrite engine to make decisions conditional on environment variables. Note that the variables accessible in `[mod\_rewrite](mod/mod_rewrite)` without the `ENV:` prefix are not actually environment variables. Rather, they are variables special to `[mod\_rewrite](mod/mod_rewrite)` which cannot be accessed from other modules. Special Purpose Environment Variables ------------------------------------- Interoperability problems have led to the introduction of mechanisms to modify the way Apache behaves when talking to particular clients. To make these mechanisms as flexible as possible, they are invoked by defining environment variables, typically with `[BrowserMatch](mod/mod_setenvif#browsermatch)`, though `[SetEnv](mod/mod_env#setenv)` and `[PassEnv](mod/mod_env#passenv)` could also be used, for example. ### downgrade-1.0 This forces the request to be treated as a HTTP/1.0 request even if it was in a later dialect. ### force-gzip If you have the `DEFLATE` filter activated, this environment variable will ignore the accept-encoding setting of your browser and will send compressed output unconditionally. ### force-no-vary This causes any `Vary` fields to be removed from the response header before it is sent back to the client. Some clients don't interpret this field correctly; setting this variable can work around this problem. Setting this variable also implies **force-response-1.0**. ### force-response-1.0 This forces an HTTP/1.0 response to clients making an HTTP/1.0 request. It was originally implemented as a result of a problem with AOL's proxies. Some HTTP/1.0 clients may not behave correctly when given an HTTP/1.1 response, and this can be used to interoperate with them. ### gzip-only-text/html When set to a value of "1", this variable disables the `DEFLATE` output filter provided by `[mod\_deflate](mod/mod_deflate)` for content-types other than `text/html`. If you'd rather use statically compressed files, `[mod\_negotiation](mod/mod_negotiation)` evaluates the variable as well (not only for gzip, but for all encodings that differ from "identity"). ### no-gzip When set, the `DEFLATE` filter of `[mod\_deflate](mod/mod_deflate)` will be turned off and `[mod\_negotiation](mod/mod_negotiation)` will refuse to deliver encoded resources. ### no-cache *Available in versions 2.2.12 and later* When set, `[mod\_cache](mod/mod_cache)` will not save an otherwise cacheable response. This environment variable does not influence whether a response already in the cache will be served for the current request. ### nokeepalive This disables `[KeepAlive](mod/core#keepalive)` when set. ### prefer-language This influences `[mod\_negotiation](mod/mod_negotiation)`'s behaviour. If it contains a language tag (such as `en`, `ja` or `x-klingon`), `[mod\_negotiation](mod/mod_negotiation)` tries to deliver a variant with that language. If there's no such variant, the normal [negotiation](content-negotiation) process applies. ### redirect-carefully This forces the server to be more careful when sending a redirect to the client. This is typically used when a client has a known problem handling redirects. This was originally implemented as a result of a problem with Microsoft's WebFolders software which has a problem handling redirects on directory resources via DAV methods. ### suppress-error-charset *Available in versions after 2.0.54* When Apache issues a redirect in response to a client request, the response includes some actual text to be displayed in case the client can't (or doesn't) automatically follow the redirection. Apache ordinarily labels this text according to the character set which it uses, which is ISO-8859-1. However, if the redirection is to a page that uses a different character set, some broken browser versions will try to use the character set from the redirection text rather than the actual page. This can result in Greek, for instance, being incorrectly rendered. Setting this environment variable causes Apache to omit the character set for the redirection text, and these broken browsers will then correctly use that of the destination page. **Security note** Sending error pages without a specified character set may allow a cross-site-scripting attack for existing browsers (MSIE) which do not follow the HTTP/1.1 specification and attempt to "guess" the character set from the content. Such browsers can be easily fooled into using the UTF-7 character set, and UTF-7 content from input data (such as the request-URI) will not be escaped by the usual escaping mechanisms designed to prevent cross-site-scripting attacks. ### force-proxy-request-1.0, proxy-nokeepalive, proxy-sendchunked, proxy-sendcl, proxy-chain-auth, proxy-interim-response, proxy-initial-not-pooled These directives alter the protocol behavior of `[mod\_proxy](mod/mod_proxy)`. See the `[mod\_proxy](mod/mod_proxy)` and `[mod\_proxy\_http](mod/mod_proxy_http)` documentation for more details. Examples -------- ### Passing broken headers to CGI scripts Starting with version 2.4, Apache is more strict about how HTTP headers are converted to environment variables in `[mod\_cgi](mod/mod_cgi)` and other modules: Previously any invalid characters in header names were simply translated to underscores. This allowed for some potential cross-site-scripting attacks via header injection (see [Unusual Web Bugs](http://events.ccc.de/congress/2007/Fahrplan/events/2212.en.html), slide 19/20). If you have to support a client which sends broken headers and which can't be fixed, a simple workaround involving `[mod\_setenvif](mod/mod_setenvif)` and `[mod\_headers](mod/mod_headers)` allows you to still accept these headers: ``` # # The following works around a client sending a broken Accept_Encoding # header. # SetEnvIfNoCase ^Accept.Encoding$ ^(.*)$ fix_accept_encoding=$1 RequestHeader set Accept-Encoding %{fix_accept_encoding}e env=fix_accept_encoding ``` ### Changing protocol behavior with misbehaving clients Earlier versions recommended that the following lines be included in httpd.conf to deal with known client problems. Since the affected clients are no longer seen in the wild, this configuration is likely no-longer necessary. ``` # # The following directives modify normal HTTP response behavior. # The first directive disables keepalive for Netscape 2.x and browsers that # spoof it. There are known problems with these browser implementations. # The second directive is for Microsoft Internet Explorer 4.0b2 # which has a broken HTTP/1.1 implementation and does not properly # support keepalive when it is used on 301 or 302 (redirect) responses. # BrowserMatch "Mozilla/2" nokeepalive BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 # # The following directive disables HTTP/1.1 responses to browsers which # are in violation of the HTTP/1.0 spec by not being able to understand a # basic 1.1 response. # BrowserMatch "RealPlayer 4\.0" force-response-1.0 BrowserMatch "Java/1\.0" force-response-1.0 BrowserMatch "JDK/1\.0" force-response-1.0 ``` ### Do not log requests for images in the access log This example keeps requests for images from appearing in the access log. It can be easily modified to prevent logging of particular directories, or to prevent logging of requests coming from particular hosts. ``` SetEnvIf Request_URI \.gif image-request SetEnvIf Request_URI \.jpg image-request SetEnvIf Request_URI \.png image-request CustomLog "logs/access_log" common env=!image-request ``` ### Prevent "Image Theft" This example shows how to keep people not on your server from using images on your server as inline-images on their pages. This is not a recommended configuration, but it can work in limited circumstances. We assume that all your images are in a directory called `/web/images`. ``` SetEnvIf Referer "^http://www\.example\.com/" local_referal # Allow browsers that do not send Referer info SetEnvIf Referer "^$" local_referal <Directory "/web/images"> Require env local_referal </Directory> ``` For more information about this technique, see the "[Keeping Your Images from Adorning Other Sites](http://www.serverwatch.com/tutorials/article.php/1132731)" tutorial on ServerWatch.
programming_docs
apache_http_server Getting Started Getting Started =============== If you're completely new to the Apache HTTP Server, or even to running a website at all, you might not know where to start, or what questions to ask. This document walks you through the basics. Clients, Servers, and URLs -------------------------- Addresses on the Web are expressed with URLs - Uniform Resource Locators - which specify a protocol (e.g. `http`), a servername (e.g. `www.apache.org`), a URL-path (e.g. `/docs/current/getting-started.html`), and possibly a query string (e.g. `?arg=value`) used to pass additional arguments to the server. A client (e.g., a web browser) connects to a server (e.g., your Apache HTTP Server), with the specified protocol, and makes a **request** for a resource using the URL-path. The URL-path may represent any number of things on the server. It may be a file (like `getting-started.html`) a handler (like [server-status](mod/mod_status)) or some kind of program file (like `index.php`). We'll discuss this more below in the [Web Site Content](#content) section. The server will send a **response** consisting of a status code and, optionally, a response body. The status code indicates whether the request was successful, and, if not, what kind of error condition there was. This tells the client what it should do with the response. You can read about the possible response codes in [HTTP Server wiki](http://wiki.apache.org/httpd/CommonHTTPStatusCodes). Details of the transaction, and any error conditions, are written to log files. This is discussed in greater detail below in the [Logs Files and Troubleshooting](#logs) section. Hostnames and DNS ----------------- In order to connect to a server, the client will first have to resolve the servername to an IP address - the location on the Internet where the server resides. Thus, in order for your web server to be reachable, it is necessary that the servername be in DNS. If you don't know how to do this, you'll need to contact your network administrator, or Internet service provider, to perform this step for you. More than one hostname may point to the same IP address, and more than one IP address can be attached to the same physical server. Thus, you can run more than one web site on the same physical server, using a feature called [virtual hosts](vhosts/index). If you are testing a server that is not Internet-accessible, you can put host names in your hosts file in order to do local resolution. For example, you might want to put a record in your hosts file to map a request for `www.example.com` to your local system, for testing purposes. This entry would look like: ``` 127.0.0.1 www.example.com ``` A hosts file will probably be located at `/etc/hosts` or `C:\Windows\system32\drivers\etc\hosts`. You can read more about the hosts file at [Wikipedia.org/wiki/Hosts\_(file)](http://en.wikipedia.org/wiki/Hosts_(file)), and more about DNS at [Wikipedia.org/wiki/Domain\_Name\_System](http://en.wikipedia.org/wiki/Domain_Name_System). Configuration Files and Directives ---------------------------------- The Apache HTTP Server is configured via simple text files. These files may be located any of a variety of places, depending on how exactly you installed the server. Common locations for these files may be found [in the httpd wiki](http://wiki.apache.org/httpd/DistrosDefaultLayout). If you installed httpd from source, the default location of the configuration files is `/usr/local/apache2/conf`. The default configuration file is usually called `httpd.conf`. This, too, can vary in third-party distributions of the server. The configuration is frequently broken into multiple smaller files, for ease of management. These files are loaded via the `[Include](mod/core#include)` directive. The names or locations of these sub-files are not magical, and may vary greatly from one installation to another. Arrange and subdivide these files as makes the most sense to **you**. If the file arrangement you have by default doesn't make sense to you, feel free to rearrange it. The server is configured by placing [configuration directives](https://httpd.apache.org/docs/2.4/en/mod/quickreference.html) in these configuration files. A directive is a keyword followed by one or more arguments that set its value. The question of "*Where should I put that directive?*" is generally answered by considering where you want a directive to be effective. If it is a global setting, it should appear in the configuration file, outside of any `[<Directory>](mod/core#directory)`, `[<Location>](mod/core#location)`, `[<VirtualHost>](mod/core#virtualhost)`, or other section. If it is to apply only to a particular directory, then it should go inside a `[<Directory>](mod/core#directory)` section referring to that directory, and so on. See the [Configuration Sections](sections) document for further discussion of these sections. In addition to the main configuration files, certain directives may go in `.htaccess` files located in the content directories. `.htaccess` files are primarily for people who do not have access to the main server configuration file(s). You can read more about `.htaccess` files in the [`.htaccess` howto](howto/htaccess). Web Site Content ---------------- Web site content can take many different forms, but may be broadly divided into static and dynamic content. Static content is things like HTML files, image files, CSS files, and other files that reside in the filesystem. The `[DocumentRoot](mod/core#documentroot)` directive specifies where in your filesystem you should place these files. This directive is either set globally, or per virtual host. Look in your configuration file(s) to determine how this is set for your server. Typically, a document called `index.html` will be served when a directory is requested without a file name being specified. For example, if `DocumentRoot` is set to `/var/www/html` and a request is made for `http://www.example.com/work/`, the file `/var/www/html/work/index.html` will be served to the client. Dynamic content is anything that is generated at request time, and may change from one request to another. There are numerous ways that dynamic content may be generated. Various [handlers](handler) are available to generate content. [CGI programs](howto/cgi) may be written to generate content for your site. Third-party modules like mod\_php may be used to write code that does a variety of things. Many third-party applications, written using a variety of languages and tools, are available for download and installation on your Apache HTTP Server. Support of these third-party things is beyond the scope of this documentation, and you should find their documentation or other support forums to answer your questions about them. Log Files and Troubleshooting ----------------------------- As an Apache HTTP Server administrator, your most valuable assets are the log files, and, in particular, the error log. Troubleshooting any problem without the error log is like driving with your eyes closed. The location of the error log is defined by the `[ErrorLog](mod/core#errorlog)` directive, which may be set globally, or per virtual host. Entries in the error log tell you what went wrong, and when. They often also tell you how to fix it. Each error log message contains an error code, which you can search for online for even more detailed descriptions of how to address the problem. You can also configure your error log to contain a log ID which you can then correlate to an access log entry, so that you can determine what request caused the error condition. You can read more about logging in the [logs documentation](logs). What's next? ------------ Once you have the prerequisites under your belt, it's time to move on. This document covers only the bare basics. We hope that this gets you started, but there are many other things that you might need to know. * [Download](http://httpd.apache.org/download.cgi) * [Install](install) * [Configure](configuring) * [Start](invoking) * [Frequently Asked Questions](http://wiki.apache.org/httpd/FAQ) apache_http_server Configuration Files Configuration Files =================== This document describes the files used to configure Apache HTTP Server. Main Configuration Files ------------------------ | Related Modules | Related Directives | | --- | --- | | * `[mod\_mime](mod/mod_mime)` | * `[<IfDefine>](mod/core#ifdefine)` * `[Include](mod/core#include)` * `[TypesConfig](mod/mod_mime#typesconfig)` | Apache HTTP Server is configured by placing [directives](https://httpd.apache.org/docs/2.4/en/mod/directives.html) in plain text configuration files. The main configuration file is usually called `httpd.conf`. The location of this file is set at compile-time, but may be overridden with the `-f` command line flag. In addition, other configuration files may be added using the `[Include](mod/core#include)` directive, and wildcards can be used to include many configuration files. Any directive may be placed in any of these configuration files. Changes to the main configuration files are only recognized by httpd when it is started or restarted. The server also reads a file containing mime document types; the filename is set by the `[TypesConfig](mod/mod_mime#typesconfig)` directive, and is `mime.types` by default. Syntax of the Configuration Files --------------------------------- httpd configuration files contain one directive per line. The backslash "\" may be used as the last character on a line to indicate that the directive continues onto the next line. There must be no other characters or white space between the backslash and the end of the line. Arguments to directives are separated by whitespace. If an argument contains spaces, you must enclose that argument in quotes. Directives in the configuration files are case-insensitive, but arguments to directives are often case sensitive. Lines that begin with the hash character "#" are considered comments, and are ignored. Comments may **not** be included on the same line as a configuration directive. White space occurring before a directive is ignored, so you may indent directives for clarity. Blank lines are also ignored. The values of variables defined with the `[Define](mod/core#define)` of or shell environment variables can be used in configuration file lines using the syntax `${VAR}`. If "VAR" is the name of a valid variable, the value of that variable is substituted into that spot in the configuration file line, and processing continues as if that text were found directly in the configuration file. Variables defined with `[Define](mod/core#define)` take precedence over shell environment variables. If the "VAR" variable is not found, the characters `${VAR}` are left unchanged, and a warning is logged. Variable names may not contain colon ":" characters, to avoid clashes with `[RewriteMap](mod/mod_rewrite#rewritemap)`'s syntax. Only shell environment variables defined before the server is started can be used in expansions. Environment variables defined in the configuration file itself, for example with `[SetEnv](mod/mod_env#setenv)`, take effect too late to be used for expansions in the configuration file. The maximum length of a line in normal configuration files, after variable substitution and joining any continued lines, is approximately 16 MiB. In [.htaccess files](configuring#htaccess), the maximum length is 8190 characters. You can check your configuration files for syntax errors without starting the server by using `apachectl configtest` or the `-t` command line option. You can use `[mod\_info](mod/mod_info)`'s `-DDUMP_CONFIG` to dump the configuration with all included files and environment variables resolved and all comments and non-matching `[<IfDefine>](mod/core#ifdefine)` and `[<IfModule>](mod/core#ifmodule)` sections removed. However, the output does not reflect the merging or overriding that may happen for repeated directives. Modules ------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_so](mod/mod_so)` | * `[<IfModule>](mod/core#ifmodule)` * `[LoadModule](mod/mod_so#loadmodule)` | httpd is a modular server. This implies that only the most basic functionality is included in the core server. Extended features are available through [modules](mod/index) which can be loaded into httpd. By default, a base set of modules is included in the server at compile-time. If the server is compiled to use [dynamically loaded](dso) modules, then modules can be compiled separately and added at any time using the `[LoadModule](mod/mod_so#loadmodule)` directive. Otherwise, httpd must be recompiled to add or remove modules. Configuration directives may be included conditional on a presence of a particular module by enclosing them in an `[<IfModule>](mod/core#ifmodule)` block. However, `<IfModule>` blocks are not required, and in some cases may mask the fact that you're missing an important module. To see which modules are currently compiled into the server, you can use the `-l` command line option. You can also see what modules are loaded dynamically using the `-M` command line option. Scope of Directives ------------------- | Related Modules | Related Directives | | --- | --- | | | * `[<Directory>](mod/core#directory)` * `[<DirectoryMatch>](mod/core#directorymatch)` * `[<Files>](mod/core#files)` * `[<FilesMatch>](mod/core#filesmatch)` * `[<Location>](mod/core#location)` * `[<LocationMatch>](mod/core#locationmatch)` * `[<VirtualHost>](mod/core#virtualhost)` | Directives placed in the main configuration files apply to the entire server. If you wish to change the configuration for only a part of the server, you can scope your directives by placing them in `[<Directory>](mod/core#directory)`, `[<DirectoryMatch>](mod/core#directorymatch)`, `[<Files>](mod/core#files)`, `[<FilesMatch>](mod/core#filesmatch)`, `[<Location>](mod/core#location)`, and `[<LocationMatch>](mod/core#locationmatch)` sections. These sections limit the application of the directives which they enclose to particular filesystem locations or URLs. They can also be nested, allowing for very fine grained configuration. httpd has the capability to serve many different websites simultaneously. This is called [Virtual Hosting](vhosts/index). Directives can also be scoped by placing them inside `[<VirtualHost>](mod/core#virtualhost)` sections, so that they will only apply to requests for a particular website. Although most directives can be placed in any of these sections, some directives do not make sense in some contexts. For example, directives controlling process creation can only be placed in the main server context. To find which directives can be placed in which sections, check the Context of the directive. For further information, we provide details on [How Directory, Location and Files sections work](sections). .htaccess Files --------------- | Related Modules | Related Directives | | --- | --- | | | * `[AccessFileName](mod/core#accessfilename)` * `[AllowOverride](mod/core#allowoverride)` | httpd allows for decentralized management of configuration via special files placed inside the web tree. The special files are usually called `.htaccess`, but any name can be specified in the `[AccessFileName](mod/core#accessfilename)` directive. Directives placed in `.htaccess` files apply to the directory where you place the file, and all sub-directories. The `.htaccess` files follow the same syntax as the main configuration files. Since `.htaccess` files are read on every request, changes made in these files take immediate effect. To find which directives can be placed in `.htaccess` files, check the Context of the directive. The server administrator further controls what directives may be placed in `.htaccess` files by configuring the `[AllowOverride](mod/core#allowoverride)` directive in the main configuration files. For more information on `.htaccess` files, see the [.htaccess tutorial](howto/htaccess). apache_http_server Expressions in Apache HTTP Server Expressions in Apache HTTP Server ================================= Historically, there are several syntax variants for expressions used to express a condition in the different modules of the Apache HTTP Server. There is some ongoing effort to only use a single variant, called *ap\_expr*, for all configuration directives. This document describes the *ap\_expr* expression parser. The *ap\_expr* expression is intended to replace most other expression variants in HTTPD. For example, the deprecated `[SSLRequire](mod/mod_ssl#sslrequire)` expressions can be replaced by [Require expr](mod/mod_authz_core#reqexpr). Grammar in Backus-Naur Form notation ------------------------------------ [Backus-Naur Form](http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form) (BNF) is a notation technique for context-free grammars, often used to describe the syntax of languages used in computing. In most cases, expressions are used to express boolean values. For these, the starting point in the BNF is `expr`. However, a few directives like `[LogMessage](mod/mod_log_debug#logmessage)` accept expressions that evaluate to a string value. For those, the starting point in the BNF is `string`. > > ``` > expr ::= "**true**" | "**false**" > | "**!**" expr > | expr "**&&**" expr > | expr "**||**" expr > | "**(**" expr "**)**" > | comp > > comp ::= stringcomp > | integercomp > | unaryop word > | word binaryop word > | word "**in**" "**{**" wordlist "**}**" > | word "**in**" listfunction > | word "**=~**" regex > | word "**!~**" regex > > > stringcomp ::= word "**==**" word > | word "**!=**" word > | word "**<**" word > | word "**<=**" word > | word "**>**" word > | word "**>=**" word > > integercomp ::= word "**-eq**" word | word "**eq**" word > | word "**-ne**" word | word "**ne**" word > | word "**-lt**" word | word "**lt**" word > | word "**-le**" word | word "**le**" word > | word "**-gt**" word | word "**gt**" word > | word "**-ge**" word | word "**ge**" word > > wordlist ::= word > | wordlist "**,**" word > > word ::= word "**.**" word > | digit > | "**'**" string "**'**" > | "**"**" string "**"**" > | variable > | rebackref > | function > > string ::= stringpart > | string stringpart > > stringpart ::= cstring > | variable > | rebackref > > cstring ::= ... > digit ::= [0-9]+ > > variable ::= "**%{**" varname "**}**" > | "**%{**" funcname "**:**" funcargs "**}**" > > rebackref ::= "**$**" [0-9] > > function ::= funcname "**(**" word "**)**" > > listfunction ::= listfuncname "**(**" word "**)**" > ``` > Variables --------- The expression parser provides a number of variables of the form `%{HTTP_HOST}`. Note that the value of a variable may depend on the phase of the request processing in which it is evaluated. For example, an expression used in an `<If >` directive is evaluated before authentication is done. Therefore, `%{REMOTE_USER}` will not be set in this case. The following variables provide the values of the named HTTP request headers. The values of other headers can be obtained with the `req` [function](#functions). Using these variables may cause the header name to be added to the Vary header of the HTTP response, except where otherwise noted for the directive accepting the expression. The `req_novary` [function](#functions) may be used to circumvent this behavior. | Name | | --- | | `HTTP_ACCEPT` | | `HTTP_COOKIE` | | `HTTP_FORWARDED` | | `HTTP_HOST` | | `HTTP_PROXY_CONNECTION` | | `HTTP_REFERER` | | `HTTP_USER_AGENT` | Other request related variables | Name | Description | | --- | --- | | `REQUEST_METHOD` | The HTTP method of the incoming request (e.g. `GET`) | | `REQUEST_SCHEME` | The scheme part of the request's URI | | `REQUEST_URI` | The path part of the request's URI | | `DOCUMENT_URI` | Same as `REQUEST_URI` | | `REQUEST_FILENAME` | The full local filesystem path to the file or script matching the request, if this has already been determined by the server at the time `REQUEST_FILENAME` is referenced. Otherwise, such as when used in virtual host context, the same value as `REQUEST_URI` | | `SCRIPT_FILENAME` | Same as `REQUEST_FILENAME` | | `LAST_MODIFIED` | The date and time of last modification of the file in the format `20101231235959`, if this has already been determined by the server at the time `LAST_MODIFIED` is referenced. | | `SCRIPT_USER` | The user name of the owner of the script. | | `SCRIPT_GROUP` | The group name of the group of the script. | | `PATH_INFO` | The trailing path name information, see `[AcceptPathInfo](mod/core#acceptpathinfo)` | | `QUERY_STRING` | The query string of the current request | | `IS_SUBREQ` | "`true`" if the current request is a subrequest, "`false`" otherwise | | `THE_REQUEST` | The complete request line (e.g., "`GET /index.html HTTP/1.1`") | | `REMOTE_ADDR` | The IP address of the remote host | | `REMOTE_PORT` | The port of the remote host (2.4.26 and later) | | `REMOTE_HOST` | The host name of the remote host | | `REMOTE_USER` | The name of the authenticated user, if any (not available during `<If>`) | | `REMOTE_IDENT` | The user name set by `[mod\_ident](mod/mod_ident)` | | `SERVER_NAME` | The `[ServerName](mod/core#servername)` of the current vhost | | `SERVER_PORT` | The server port of the current vhost, see `[ServerName](mod/core#servername)` | | `SERVER_ADMIN` | The `[ServerAdmin](mod/core#serveradmin)` of the current vhost | | `SERVER_PROTOCOL` | The protocol used by the request | | `DOCUMENT_ROOT` | The `[DocumentRoot](mod/core#documentroot)` of the current vhost | | `AUTH_TYPE` | The configured `[AuthType](mod/mod_authn_core#authtype)` (e.g. "`basic`") | | `CONTENT_TYPE` | The content type of the response (not available during `<If>`) | | `HANDLER` | The name of the <handler> creating the response | | `HTTP2` | "`on`" if the request uses http/2, "`off`" otherwise | | `HTTPS` | "`on`" if the request uses https, "`off`" otherwise | | `IPV6` | "`on`" if the connection uses IPv6, "`off`" otherwise | | `REQUEST_STATUS` | The HTTP error status of the request (not available during `<If>`) | | `REQUEST_LOG_ID` | The error log id of the request (see `[ErrorLogFormat](mod/core#errorlogformat)`) | | `CONN_LOG_ID` | The error log id of the connection (see `[ErrorLogFormat](mod/core#errorlogformat)`) | | `CONN_REMOTE_ADDR` | The peer IP address of the connection (see the `[mod\_remoteip](mod/mod_remoteip)` module) | | `CONTEXT_PREFIX` | | | `CONTEXT_DOCUMENT_ROOT` | | Misc variables | Name | Description | | --- | --- | | `TIME_YEAR` | The current year (e.g. `2010`) | | `TIME_MON` | The current month (`01`, ..., `12`) | | `TIME_DAY` | The current day of the month (`01`, ...) | | `TIME_HOUR` | The hour part of the current time (`00`, ..., `23`) | | `TIME_MIN` | The minute part of the current time | | `TIME_SEC` | The second part of the current time | | `TIME_WDAY` | The day of the week (starting with `0` for Sunday) | | `TIME` | The date and time in the format `20101231235959` | | `SERVER_SOFTWARE` | The server version string | | `API_VERSION` | The date of the API version (module magic number) | Some modules register additional variables, see e.g. `[mod\_ssl](mod/mod_ssl)`. Binary operators ---------------- With the exception of some built-in comparison operators, binary operators have the form "`-[a-zA-Z][a-zA-Z0-9_]+`", i.e. a minus and at least two characters. The name is not case sensitive. Modules may register additional binary operators. ### Comparison operators | Name | Alternative | Description | | --- | --- | --- | | `==` | `=` | String equality | | `!=` | | String inequality | | `<` | | String less than | | `<=` | | String less than or equal | | `>` | | String greater than | | `>=` | | String greater than or equal | | `=~` | | String matches the regular expression | | `!~` | | String does not match the regular expression | | `-eq` | `eq` | Integer equality | | `-ne` | `ne` | Integer inequality | | `-lt` | `lt` | Integer less than | | `-le` | `le` | Integer less than or equal | | `-gt` | `gt` | Integer greater than | | `-ge` | `ge` | Integer greater than or equal | ### Other binary operators | Name | Description | | --- | --- | | `-ipmatch` | IP address matches address/netmask | | `-strmatch` | left string matches pattern given by right string (containing wildcards \*, ?, []) | | `-strcmatch` | same as `-strmatch`, but case insensitive | | `-fnmatch` | same as `-strmatch`, but slashes are not matched by wildcards | Unary operators --------------- Unary operators take one argument and have the form "`-[a-zA-Z]`", i.e. a minus and one character. The name *is* case sensitive. Modules may register additional unary operators. | Name | Description | Restricted | | --- | --- | --- | | `-d` | The argument is treated as a filename. True if the file exists and is a directory | yes | | `-e` | The argument is treated as a filename. True if the file (or dir or special) exists | yes | | `-f` | The argument is treated as a filename. True if the file exists and is regular file | yes | | `-s` | The argument is treated as a filename. True if the file exists and is not empty | yes | | `-L` | The argument is treated as a filename. True if the file exists and is symlink | yes | | `-h` | The argument is treated as a filename. True if the file exists and is symlink (same as `-L`) | yes | | `-F` | True if string is a valid file, accessible via all the server's currently-configured access controls for that path. This uses an internal subrequest to do the check, so use it with care - it can impact your server's performance! | | | `-U` | True if string is a valid URL, accessible via all the server's currently-configured access controls for that path. This uses an internal subrequest to do the check, so use it with care - it can impact your server's performance! | | | `-A` | Alias for `-U` | | | `-n` | True if string is not empty | | | `-z` | True if string is empty | | | `-T` | False if string is empty, "`0`", "`off`", "`false`", or "`no`" (case insensitive). True otherwise. | | | `-R` | Same as "`%{REMOTE_ADDR} -ipmatch ...`", but more efficient | | The operators marked as "restricted" are not available in some modules like `[mod\_include](mod/mod_include)`. Functions --------- Normal string-valued functions take one string as argument and return a string. Functions names are not case sensitive. Modules may register additional functions. | Name | Description | Special notes | | --- | --- | --- | | `req`, `http` | Get HTTP request header; header names may be added to the Vary header, see below | | | `req_novary` | Same as `req`, but header names will not be added to the Vary header | | | `resp` | Get HTTP response header (most response headers will not yet be set during `<If>`) | | | `reqenv` | Lookup request environment variable (as a shortcut, `v` can also be used to access variables). | ordering | | `osenv` | Lookup operating system environment variable | | | `note` | Lookup request note | ordering | | `env` | Return first match of `note`, `reqenv`, `osenv` | ordering | | `tolower` | Convert string to lower case | | | `toupper` | Convert string to upper case | | | `escape` | Escape special characters in %hex encoding | | | `unescape` | Unescape %hex encoded string, leaving encoded slashes alone; return empty string if %00 is found | | | `base64` | Encode the string using base64 encoding | | | `unbase64` | Decode base64 encoded string, return truncated string if 0x00 is found | | | `md5` | Hash the string using MD5, then encode the hash with hexadecimal encoding | | | `sha1` | Hash the string using SHA1, then encode the hash with hexadecimal encoding | | | `file` | Read contents from a file (including line endings, when present) | restricted | | `filemod` | Return last modification time of a file (or 0 if file does not exist or is not regular file) | restricted | | `filesize` | Return size of a file (or 0 if file does not exist or is not regular file) | restricted | The functions marked as "restricted" in the final column are not available in some modules like `[mod\_include](mod/mod_include)`. The functions marked as "ordering" in the final column require some consideration for the ordering of different components of the server, especially when the function is used within the <`[If](mod/core#if)`> directive which is evaluated relatively early. **Environment variable ordering** When environment variables are looked up within an <`[If](mod/core#if)`> condition, it's important to consider how extremely early in request processing that this resolution occurs. As a guideline, any directive defined outside of virtual host context (directory, location, htaccess) is not likely to have yet had a chance to execute. `[SetEnvIf](mod/mod_setenvif#setenvif)` in virtual host scope is one directive that runs prior to this resolution When `reqenv` is used outside of <`[If](mod/core#if)`>, the resolution will generally occur later, but the exact timing depends on the directive the expression has been used within. When the functions `req` or `http` are used, the header name will automatically be added to the Vary header of the HTTP response, except where otherwise noted for the directive accepting the expression. The `req_novary` function can be used to prevent names from being added to the Vary header. In addition to string-valued functions, there are also list-valued functions which take one string as argument and return a wordlist, i.e. a list of strings. The wordlist can be used with the special `-in` operator. Functions names are not case sensitive. Modules may register additional functions. There are no built-in list-valued functions. `[mod\_ssl](mod/mod_ssl)` provides `PeerExtList`. See the description of `[SSLRequire](mod/mod_ssl#sslrequire)` for details (but `PeerExtList` is also usable outside of `[SSLRequire](mod/mod_ssl#sslrequire)`). Example expressions ------------------- The following examples show how expressions might be used to evaluate requests: ``` # Compare the host name to example.com and redirect to www.example.com if it matches <If "%{HTTP_HOST} == 'example.com'"> Redirect permanent "/" "http://www.example.com/" </If> # Force text/plain if requesting a file with the query string contains 'forcetext' <If "%{QUERY_STRING} =~ /forcetext/"> ForceType text/plain </If> # Only allow access to this content during business hours <Directory "/foo/bar/business"> Require expr %{TIME_HOUR} -gt 9 && %{TIME_HOUR} -lt 17 </Directory> # Check a HTTP header for a list of values <If "%{HTTP:X-example-header} in { 'foo', 'bar', 'baz' }"> Header set matched true </If> # Check an environment variable for a regular expression, negated. <If "! reqenv('REDIRECT_FOO') =~ /bar/"> Header set matched true </If> # Check result of URI mapping by running in Directory context with -f <Directory "/var/www"> AddEncoding x-gzip gz <If "-f '%{REQUEST_FILENAME}.unzipme' && ! %{HTTP:Accept-Encoding} =~ /gzip/"> SetOutputFilter INFLATE </If> </Directory> # Check against the client IP <If "-R '192.168.1.0/24'"> Header set matched true </If> # Function example in boolean context <If "md5('foo') == 'acbd18db4cc2f85cedef654fccc4a4d8'"> Header set checksum-matched true </If> # Function example in string context Header set foo-checksum "expr=%{md5:foo}" # This delays the evaluation of the condition clause compared to <If> Header always set CustomHeader my-value "expr=%{REQUEST_URI} =~ m#^/special_path\.php$#" # Conditional logging CustomLog logs/access-errors.log common "expr=%{REQUEST_STATUS} >= 400" CustomLog logs/access-errors-specific.log common "expr=%{REQUEST_STATUS} -in {'405','410'}" ``` Other ----- | Name | Alternative | Description | | --- | --- | --- | | `-in` | `in` | string contained in wordlist | | `/regexp/` | `m#regexp#` | Regular expression (the second form allows different delimiters than /) | | `/regexp/i` | `m#regexp#i` | Case insensitive regular expression | | ``` $0 ... $9 ``` | | Regular expression backreferences | ### Regular expression backreferences The strings `$0` ... `$9` allow to reference the capture groups from a previously executed, successfully matching regular expressions. They can normally only be used in the same expression as the matching regex, but some modules allow special uses. Comparison with SSLRequire -------------------------- The *ap\_expr* syntax is mostly a superset of the syntax of the deprecated `[SSLRequire](mod/mod_ssl#sslrequire)` directive. The differences are described in `[SSLRequire](mod/mod_ssl#sslrequire)`'s documentation. Version History --------------- The `req_novary` [function](#functions) is available for versions 2.4.4 and later.
programming_docs
apache_http_server Log Files Log Files ========= In order to effectively manage a web server, it is necessary to get feedback about the activity and performance of the server as well as any problems that may be occurring. The Apache HTTP Server provides very comprehensive and flexible logging capabilities. This document describes how to configure its logging capabilities, and how to understand what the logs contain. Overview -------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_log\_config](mod/mod_log_config)` * `[mod\_log\_forensic](mod/mod_log_forensic)` * `[mod\_logio](mod/mod_logio)` * `[mod\_cgi](mod/mod_cgi)` | | The Apache HTTP Server provides a variety of different mechanisms for logging everything that happens on your server, from the initial request, through the URL mapping process, to the final resolution of the connection, including any errors that may have occurred in the process. In addition to this, third-party modules may provide logging capabilities, or inject entries into the existing log files, and applications such as CGI programs, or PHP scripts, or other handlers, may send messages to the server error log. In this document we discuss the logging modules that are a standard part of the http server. Security Warning ---------------- Anyone who can write to the directory where Apache httpd is writing a log file can almost certainly gain access to the uid that the server is started as, which is normally root. Do *NOT* give people write access to the directory the logs are stored in without being aware of the consequences; see the [security tips](misc/security_tips) document for details. In addition, log files may contain information supplied directly by the client, without escaping. Therefore, it is possible for malicious clients to insert control-characters in the log files, so care must be taken in dealing with raw logs. Error Log --------- | Related Modules | Related Directives | | --- | --- | | * `[core](mod/core)` | * `[ErrorLog](mod/core#errorlog)` * `[ErrorLogFormat](mod/core#errorlogformat)` * `[LogLevel](mod/core#loglevel)` | The server error log, whose name and location is set by the `[ErrorLog](mod/core#errorlog)` directive, is the most important log file. This is the place where Apache httpd will send diagnostic information and record any errors that it encounters in processing requests. It is the first place to look when a problem occurs with starting the server or with the operation of the server, since it will often contain details of what went wrong and how to fix it. The error log is usually written to a file (typically `error_log` on Unix systems and `error.log` on Windows and OS/2). On Unix systems it is also possible to have the server send errors to `syslog` or [pipe them to a program](#piped). The format of the error log is defined by the `[ErrorLogFormat](mod/core#errorlogformat)` directive, with which you can customize what values are logged. A default is format defined if you don't specify one. A typical log message follows: ``` [Fri Sep 09 10:42:29.902022 2011] [core:error] [pid 35708:tid 4328636416] [client 72.15.99.187] File does not exist: /usr/local/apache2/htdocs/favicon.ico ``` The first item in the log entry is the date and time of the message. The next is the module producing the message (core, in this case) and the severity level of that message. This is followed by the process ID and, if appropriate, the thread ID, of the process that experienced the condition. Next, we have the client address that made the request. And finally is the detailed error message, which in this case indicates a request for a file that did not exist. A very wide variety of different messages can appear in the error log. Most look similar to the example above. The error log will also contain debugging output from CGI scripts. Any information written to `stderr` by a CGI script will be copied directly to the error log. Putting a `%L` token in both the error log and the access log will produce a log entry ID with which you can correlate the entry in the error log with the entry in the access log. If `[mod\_unique\_id](mod/mod_unique_id)` is loaded, its unique request ID will be used as the log entry ID, too. During testing, it is often useful to continuously monitor the error log for any problems. On Unix systems, you can accomplish this using: ``` tail -f error_log ``` Per-module logging ------------------ The `[LogLevel](mod/core#loglevel)` directive allows you to specify a log severity level on a per-module basis. In this way, if you are troubleshooting a problem with just one particular module, you can turn up its logging volume without also getting the details of other modules that you're not interested in. This is particularly useful for modules such as `[mod\_proxy](mod/mod_proxy)` or `[mod\_rewrite](mod/mod_rewrite)` where you want to know details about what it's trying to do. Do this by specifying the name of the module in your `LogLevel` directive: ``` LogLevel info rewrite:trace5 ``` This sets the main `LogLevel` to info, but turns it up to `trace5` for `[mod\_rewrite](mod/mod_rewrite)`. This replaces the per-module logging directives, such as `RewriteLog`, that were present in earlier versions of the server. Access Log ---------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_log\_config](mod/mod_log_config)` * `[mod\_setenvif](mod/mod_setenvif)` | * `[CustomLog](mod/mod_log_config#customlog)` * `[LogFormat](mod/mod_log_config#logformat)` * `[SetEnvIf](mod/mod_setenvif#setenvif)` | The server access log records all requests processed by the server. The location and content of the access log are controlled by the `[CustomLog](mod/mod_log_config#customlog)` directive. The `[LogFormat](mod/mod_log_config#logformat)` directive can be used to simplify the selection of the contents of the logs. This section describes how to configure the server to record information in the access log. Of course, storing the information in the access log is only the start of log management. The next step is to analyze this information to produce useful statistics. Log analysis in general is beyond the scope of this document, and not really part of the job of the web server itself. For more information about this topic, and for applications which perform log analysis, check the [Open Directory](http://dmoz.org/Computers/Software/Internet/Site_Management/Log_Analysis/). Various versions of Apache httpd have used other modules and directives to control access logging, including mod\_log\_referer, mod\_log\_agent, and the `TransferLog` directive. The `[CustomLog](mod/mod_log_config#customlog)` directive now subsumes the functionality of all the older directives. The format of the access log is highly configurable. The format is specified using a format string that looks much like a C-style printf(1) format string. Some examples are presented in the next sections. For a complete list of the possible contents of the format string, see the `[mod\_log\_config](mod/mod_log_config)` [format strings](mod/mod_log_config#formats). ### Common Log Format A typical configuration for the access log might look as follows. ``` LogFormat "%h %l %u %t \"%r\" %>s %b" common CustomLog logs/access_log common ``` This defines the *nickname* `common` and associates it with a particular log format string. The format string consists of percent directives, each of which tell the server to log a particular piece of information. Literal characters may also be placed in the format string and will be copied directly into the log output. The quote character (`"`) must be escaped by placing a backslash before it to prevent it from being interpreted as the end of the format string. The format string may also contain the special control characters "`\n`" for new-line and "`\t`" for tab. The `[CustomLog](mod/mod_log_config#customlog)` directive sets up a new log file using the defined *nickname*. The filename for the access log is relative to the `[ServerRoot](mod/core#serverroot)` unless it begins with a slash. The above configuration will write log entries in a format known as the Common Log Format (CLF). This standard format can be produced by many different web servers and read by many log analysis programs. The log file entries produced in CLF will look something like this: ``` 127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326 ``` Each part of this log entry is described below. `127.0.0.1` (`%h`) This is the IP address of the client (remote host) which made the request to the server. If `[HostnameLookups](mod/core#hostnamelookups)` is set to `On`, then the server will try to determine the hostname and log it in place of the IP address. However, this configuration is not recommended since it can significantly slow the server. Instead, it is best to use a log post-processor such as `[logresolve](programs/logresolve)` to determine the hostnames. The IP address reported here is not necessarily the address of the machine at which the user is sitting. If a proxy server exists between the user and the server, this address will be the address of the proxy, rather than the originating machine. `-` (`%l`) The "hyphen" in the output indicates that the requested piece of information is not available. In this case, the information that is not available is the RFC 1413 identity of the client determined by `identd` on the clients machine. This information is highly unreliable and should almost never be used except on tightly controlled internal networks. Apache httpd will not even attempt to determine this information unless `[IdentityCheck](mod/mod_ident#identitycheck)` is set to `On`. `frank` (`%u`) This is the userid of the person requesting the document as determined by HTTP authentication. The same value is typically provided to CGI scripts in the `REMOTE_USER` environment variable. If the status code for the request (see below) is 401, then this value should not be trusted because the user is not yet authenticated. If the document is not password protected, this part will be "`-`" just like the previous one. `[10/Oct/2000:13:55:36 -0700]` (`%t`) The time that the request was received. The format is: ``` [day/month/year:hour:minute:second zone] day = 2*digit month = 3*letter year = 4*digit hour = 2*digit minute = 2*digit second = 2*digit zone = (`+' | `-') 4*digit ``` It is possible to have the time displayed in another format by specifying `%{format}t` in the log format string, where `format` is either as in `strftime(3)` from the C standard library, or one of the supported special tokens. For details see the `[mod\_log\_config](mod/mod_log_config)` [format strings](mod/mod_log_config#formats). `"GET /apache_pb.gif HTTP/1.0"` (`\"%r\"`) The request line from the client is given in double quotes. The request line contains a great deal of useful information. First, the method used by the client is `GET`. Second, the client requested the resource `/apache_pb.gif`, and third, the client used the protocol `HTTP/1.0`. It is also possible to log one or more parts of the request line independently. For example, the format string "`%m %U%q %H`" will log the method, path, query-string, and protocol, resulting in exactly the same output as "`%r`". `200` (`%>s`) This is the status code that the server sends back to the client. This information is very valuable, because it reveals whether the request resulted in a successful response (codes beginning in 2), a redirection (codes beginning in 3), an error caused by the client (codes beginning in 4), or an error in the server (codes beginning in 5). The full list of possible status codes can be found in the [HTTP specification](http://www.w3.org/Protocols/rfc2616/rfc2616.txt) (RFC2616 section 10). `2326` (`%b`) The last part indicates the size of the object returned to the client, not including the response headers. If no content was returned to the client, this value will be "`-`". To log "`0`" for no content, use `%B` instead. ### Combined Log Format Another commonly used format string is called the Combined Log Format. It can be used as follows. ``` LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined CustomLog log/access_log combined ``` This format is exactly the same as the Common Log Format, with the addition of two more fields. Each of the additional fields uses the percent-directive `%{*header*}i`, where *header* can be any HTTP request header. The access log under this format will look like: ``` 127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326 "http://www.example.com/start.html" "Mozilla/4.08 [en] (Win98; I ;Nav)" ``` The additional fields are: `"http://www.example.com/start.html"` (`\"%{Referer}i\"`) The "Referer" (sic) HTTP request header. This gives the site that the client reports having been referred from. (This should be the page that links to or includes `/apache_pb.gif`). `"Mozilla/4.08 [en] (Win98; I ;Nav)"` (`\"%{User-agent}i\"`) The User-Agent HTTP request header. This is the identifying information that the client browser reports about itself. ### Multiple Access Logs Multiple access logs can be created simply by specifying multiple `[CustomLog](mod/mod_log_config#customlog)` directives in the configuration file. For example, the following directives will create three access logs. The first contains the basic CLF information, while the second and third contain referer and browser information. The last two `[CustomLog](mod/mod_log_config#customlog)` lines show how to mimic the effects of the `ReferLog` and `AgentLog` directives. ``` LogFormat "%h %l %u %t \"%r\" %>s %b" common CustomLog logs/access_log common CustomLog logs/referer_log "%{Referer}i -> %U" CustomLog logs/agent_log "%{User-agent}i" ``` This example also shows that it is not necessary to define a nickname with the `[LogFormat](mod/mod_log_config#logformat)` directive. Instead, the log format can be specified directly in the `[CustomLog](mod/mod_log_config#customlog)` directive. ### Conditional Logs There are times when it is convenient to exclude certain entries from the access logs based on characteristics of the client request. This is easily accomplished with the help of [environment variables](env). First, an environment variable must be set to indicate that the request meets certain conditions. This is usually accomplished with `[SetEnvIf](mod/mod_setenvif#setenvif)`. Then the `env=` clause of the `[CustomLog](mod/mod_log_config#customlog)` directive is used to include or exclude requests where the environment variable is set. Some examples: ``` # Mark requests from the loop-back interface SetEnvIf Remote_Addr "127\.0\.0\.1" dontlog # Mark requests for the robots.txt file SetEnvIf Request_URI "^/robots\.txt$" dontlog # Log what remains CustomLog logs/access_log common env=!dontlog ``` As another example, consider logging requests from english-speakers to one log file, and non-english speakers to a different log file. ``` SetEnvIf Accept-Language "en" english CustomLog logs/english_log common env=english CustomLog logs/non_english_log common env=!english ``` In a caching scenario one would want to know about the efficiency of the cache. A very simple method to find this out would be: ``` SetEnv CACHE_MISS 1 LogFormat "%h %l %u %t "%r " %>s %b %{CACHE_MISS}e" common-cache CustomLog logs/access_log common-cache ``` `[mod\_cache](mod/mod_cache)` will run before `[mod\_env](mod/mod_env)` and, when successful, will deliver the content without it. In that case a cache hit will log `-`, while a cache miss will log `1`. In addition to the `env=` syntax, `[LogFormat](mod/mod_log_config#logformat)` supports logging values conditional upon the HTTP response code: ``` LogFormat "%400,501{User-agent}i" browserlog LogFormat "%!200,304,302{Referer}i" refererlog ``` In the first example, the `User-agent` will be logged if the HTTP status code is 400 or 501. In other cases, a literal "-" will be logged instead. Likewise, in the second example, the `Referer` will be logged if the HTTP status code is **not** 200, 204, or 302. (Note the "!" before the status codes. Although we have just shown that conditional logging is very powerful and flexible, it is not the only way to control the contents of the logs. Log files are more useful when they contain a complete record of server activity. It is often easier to simply post-process the log files to remove requests that you do not want to consider. Log Rotation ------------ On even a moderately busy server, the quantity of information stored in the log files is very large. The access log file typically grows 1 MB or more per 10,000 requests. It will consequently be necessary to periodically rotate the log files by moving or deleting the existing logs. This cannot be done while the server is running, because Apache httpd will continue writing to the old log file as long as it holds the file open. Instead, the server must be [restarted](stopping) after the log files are moved or deleted so that it will open new log files. By using a *graceful* restart, the server can be instructed to open new log files without losing any existing or pending connections from clients. However, in order to accomplish this, the server must continue to write to the old log files while it finishes serving old requests. It is therefore necessary to wait for some time after the restart before doing any processing on the log files. A typical scenario that simply rotates the logs and compresses the old logs to save space is: ``` mv access_log access_log.old mv error_log error_log.old apachectl graceful sleep 600 gzip access_log.old error_log.old ``` Another way to perform log rotation is using [piped logs](#piped) as discussed in the next section. Piped Logs ---------- Apache httpd is capable of writing error and access log files through a pipe to another process, rather than directly to a file. This capability dramatically increases the flexibility of logging, without adding code to the main server. In order to write logs to a pipe, simply replace the filename with the pipe character "`|`", followed by the name of the executable which should accept log entries on its standard input. The server will start the piped-log process when the server starts, and will restart it if it crashes while the server is running. (This last feature is why we can refer to this technique as "reliable piped logging".) Piped log processes are spawned by the parent Apache httpd process, and inherit the userid of that process. This means that piped log programs usually run as root. It is therefore very important to keep the programs simple and secure. One important use of piped logs is to allow log rotation without having to restart the server. The Apache HTTP Server includes a simple program called `[rotatelogs](programs/rotatelogs)` for this purpose. For example, to rotate the logs every 24 hours, you can use: ``` CustomLog "|/usr/local/apache/bin/rotatelogs /var/log/access_log 86400" common ``` Notice that quotes are used to enclose the entire command that will be called for the pipe. Although these examples are for the access log, the same technique can be used for the error log. As with conditional logging, piped logs are a very powerful tool, but they should not be used where a simpler solution like off-line post-processing is available. By default the piped log process is spawned without invoking a shell. Use "`|$`" instead of "`|`" to spawn using a shell (usually with `/bin/sh -c`): ``` # Invoke "rotatelogs" using a shell CustomLog "|$/usr/local/apache/bin/rotatelogs /var/log/access_log 86400" common ``` This was the default behaviour for Apache 2.2. Depending on the shell specifics this might lead to an additional shell process for the lifetime of the logging pipe program and signal handling problems during restart. For compatibility reasons with Apache 2.2 the notation "`||`" is also supported and equivalent to using "`|`". **Windows note** Note that on Windows, you may run into problems when running many piped logger processes, especially when HTTPD is running as a service. This is caused by running out of desktop heap space. The desktop heap space given to each service is specified by the third argument to the `SharedSection` parameter in the HKEY\_LOCAL\_MACHINE\System\CurrentControlSet\Control\SessionManager\SubSystems\Windows registry value. **Change this value with care**; the normal caveats for changing the Windows registry apply, but you might also exhaust the desktop heap pool if the number is adjusted too high. Virtual Hosts ------------- When running a server with many [virtual hosts](vhosts/index), there are several options for dealing with log files. First, it is possible to use logs exactly as in a single-host server. Simply by placing the logging directives outside the `[<VirtualHost>](mod/core#virtualhost)` sections in the main server context, it is possible to log all requests in the same access log and error log. This technique does not allow for easy collection of statistics on individual virtual hosts. If `[CustomLog](mod/mod_log_config#customlog)` or `[ErrorLog](mod/core#errorlog)` directives are placed inside a `[<VirtualHost>](mod/core#virtualhost)` section, all requests or errors for that virtual host will be logged only to the specified file. Any virtual host which does not have logging directives will still have its requests sent to the main server logs. This technique is very useful for a small number of virtual hosts, but if the number of hosts is very large, it can be complicated to manage. In addition, it can often create problems with [insufficient file descriptors](vhosts/fd-limits). For the access log, there is a very good compromise. By adding information on the virtual host to the log format string, it is possible to log all hosts to the same log, and later split the log into individual files. For example, consider the following directives. ``` LogFormat "%v %l %u %t \"%r\" %>s %b" comonvhost CustomLog logs/access_log comonvhost ``` The `%v` is used to log the name of the virtual host that is serving the request. Then a program like [split-logfile](programs/split-logfile) can be used to post-process the access log in order to split it into one file per virtual host. Other Log Files --------------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_logio](mod/mod_logio)` * `[mod\_log\_config](mod/mod_log_config)` * `[mod\_log\_forensic](mod/mod_log_forensic)` * `[mod\_cgi](mod/mod_cgi)` | * `[LogFormat](mod/mod_log_config#logformat)` * `[BufferedLogs](mod/mod_log_config#bufferedlogs)` * `[ForensicLog](mod/mod_log_forensic#forensiclog)` * `[PidFile](mod/mpm_common#pidfile)` * `[ScriptLog](mod/mod_cgi#scriptlog)` * `[ScriptLogBuffer](mod/mod_cgi#scriptlogbuffer)` * `[ScriptLogLength](mod/mod_cgi#scriptloglength)` | ### Logging actual bytes sent and received `[mod\_logio](mod/mod_logio)` adds in two additional `[LogFormat](mod/mod_log_config#logformat)` fields (%I and %O) that log the actual number of bytes received and sent on the network. ### Forensic Logging `[mod\_log\_forensic](mod/mod_log_forensic)` provides for forensic logging of client requests. Logging is done before and after processing a request, so the forensic log contains two log lines for each request. The forensic logger is very strict with no customizations. It can be an invaluable debugging and security tool. ### PID File On startup, Apache httpd saves the process id of the parent httpd process to the file `logs/httpd.pid`. This filename can be changed with the `[PidFile](mod/mpm_common#pidfile)` directive. The process-id is for use by the administrator in restarting and terminating the daemon by sending signals to the parent process; on Windows, use the -k command line option instead. For more information see the [Stopping and Restarting](stopping) page. ### Script Log In order to aid in debugging, the `[ScriptLog](mod/mod_cgi#scriptlog)` directive allows you to record the input to and output from CGI scripts. This should only be used in testing - not for live servers. More information is available in the [mod\_cgi](mod/mod_cgi) documentation.
programming_docs
apache_http_server Server-Wide Configuration Server-Wide Configuration ========================= This document explains some of the directives provided by the `[core](mod/core)` server which are used to configure the basic operations of the server. Server Identification --------------------- | Related Modules | Related Directives | | --- | --- | | | * `[ServerName](mod/core#servername)` * `[ServerAdmin](mod/core#serveradmin)` * `[ServerSignature](mod/core#serversignature)` * `[ServerTokens](mod/core#servertokens)` * `[UseCanonicalName](mod/core#usecanonicalname)` * `[UseCanonicalPhysicalPort](mod/core#usecanonicalphysicalport)` | The `[ServerAdmin](mod/core#serveradmin)` and `[ServerTokens](mod/core#servertokens)` directives control what information about the server will be presented in server-generated documents such as error messages. The `[ServerTokens](mod/core#servertokens)` directive sets the value of the Server HTTP response header field. The `[ServerName](mod/core#servername)`, `[UseCanonicalName](mod/core#usecanonicalname)` and `[UseCanonicalPhysicalPort](mod/core#usecanonicalphysicalport)` directives are used by the server to determine how to construct self-referential URLs. For example, when a client requests a directory, but does not include the trailing slash in the directory name, httpd must redirect the client to the full name including the trailing slash so that the client will correctly resolve relative references in the document. File Locations -------------- | Related Modules | Related Directives | | --- | --- | | | * `[CoreDumpDirectory](mod/mpm_common#coredumpdirectory)` * `[DocumentRoot](mod/core#documentroot)` * `[ErrorLog](mod/core#errorlog)` * `[Mutex](mod/core#mutex)` * `[PidFile](mod/mpm_common#pidfile)` * `[ScoreBoardFile](mod/mpm_common#scoreboardfile)` * `[ServerRoot](mod/core#serverroot)` | These directives control the locations of the various files that httpd needs for proper operation. When the pathname used does not begin with a slash (/), the files are located relative to the `[ServerRoot](mod/core#serverroot)`. Be careful about locating files in paths which are writable by non-root users. See the [security tips](misc/security_tips#serverroot) documentation for more details. Limiting Resource Usage ----------------------- | Related Modules | Related Directives | | --- | --- | | | * `[LimitRequestBody](mod/core#limitrequestbody)` * `[LimitRequestFields](mod/core#limitrequestfields)` * `[LimitRequestFieldsize](mod/core#limitrequestfieldsize)` * `[LimitRequestLine](mod/core#limitrequestline)` * `[RLimitCPU](mod/core#rlimitcpu)` * `[RLimitMEM](mod/core#rlimitmem)` * `[RLimitNPROC](mod/core#rlimitnproc)` * `[ThreadStackSize](mod/mpm_common#threadstacksize)` | The `LimitRequest`\* directives are used to place limits on the amount of resources httpd will use in reading requests from clients. By limiting these values, some kinds of denial of service attacks can be mitigated. The `RLimit`\* directives are used to limit the amount of resources which can be used by processes forked off from the httpd children. In particular, this will control resources used by CGI scripts and SSI exec commands. The `[ThreadStackSize](mod/mpm_common#threadstacksize)` directive is used with some platforms to control the stack size. Implementation Choices ---------------------- | Related Modules | Related Directives | | --- | --- | | | * `[Mutex](mod/core#mutex)` | The `Mutex` directive can be used to change the underlying implementation used for mutexes, in order to relieve functional or performance problems with [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary")'s default choice. apache_http_server suEXEC Support suEXEC Support ============== The **suEXEC** feature provides users of the Apache HTTP Server the ability to run **CGI** and **SSI** programs under user IDs different from the user ID of the calling web server. Normally, when a CGI or SSI program executes, it runs as the same user who is running the web server. Used properly, this feature can reduce considerably the security risks involved with allowing users to develop and run private CGI or SSI programs. However, if suEXEC is improperly configured, it can cause any number of problems and possibly create new holes in your computer's security. If you aren't familiar with managing *setuid root* programs and the security issues they present, we highly recommend that you not consider using suEXEC. Before we begin --------------- Before jumping head-first into this document, you should be aware that certain assumptions are made about you and the environment in which you will be using suexec. First, it is assumed that you are using a UNIX derivative operating system that is capable of **setuid** and **setgid** operations. All command examples are given in this regard. Other platforms, if they are capable of supporting suEXEC, may differ in their configuration. Second, it is assumed you are familiar with some basic concepts of your computer's security and its administration. This involves an understanding of **setuid/setgid** operations and the various effects they may have on your system and its level of security. Third, it is assumed that you are using an **unmodified** version of suEXEC code. All code for suEXEC has been carefully scrutinized and tested by the developers as well as numerous beta testers. Every precaution has been taken to ensure a simple yet solidly safe base of code. Altering this code can cause unexpected problems and new security risks. It is **highly** recommended you not alter the suEXEC code unless you are well versed in the particulars of security programming and are willing to share your work with the Apache HTTP Server development team for consideration. Fourth, and last, it has been the decision of the Apache HTTP Server development team to **NOT** make suEXEC part of the default installation of Apache httpd. To this end, suEXEC configuration requires of the administrator careful attention to details. After due consideration has been given to the various settings for suEXEC, the administrator may install suEXEC through normal installation methods. The values for these settings need to be carefully determined and specified by the administrator to properly maintain system security during the use of suEXEC functionality. It is through this detailed process that we hope to limit suEXEC installation only to those who are careful and determined enough to use it. Still with us? Yes? Good. Let's move on! suEXEC Security Model --------------------- Before we begin configuring and installing suEXEC, we will first discuss the security model you are about to implement. By doing so, you may better understand what exactly is going on inside suEXEC and what precautions are taken to ensure your system's security. **suEXEC** is based on a setuid "wrapper" program that is called by the main Apache HTTP Server. This wrapper is called when an HTTP request is made for a CGI or SSI program that the administrator has designated to run as a userid other than that of the main server. When such a request is made, Apache httpd provides the suEXEC wrapper with the program's name and the user and group IDs under which the program is to execute. The wrapper then employs the following process to determine success or failure -- if any one of these conditions fail, the program logs the failure and exits with an error, otherwise it will continue: 1. **Is the user executing this wrapper a valid user of this system?** This is to ensure that the user executing the wrapper is truly a user of the system. 2. **Was the wrapper called with the proper number of arguments?** The wrapper will only execute if it is given the proper number of arguments. The proper argument format is known to the Apache HTTP Server. If the wrapper is not receiving the proper number of arguments, it is either being hacked, or there is something wrong with the suEXEC portion of your Apache httpd binary. 3. **Is this valid user allowed to run the wrapper?** Is this user the user allowed to run this wrapper? Only one user (the Apache user) is allowed to execute this program. 4. **Does the target CGI or SSI program have an unsafe hierarchical reference?** Does the target CGI or SSI program's path contain a leading '/' or have a '..' backreference? These are not allowed; the target CGI/SSI program must reside within suEXEC's document root (see `--with-suexec-docroot=*DIR*` below). 5. **Is the target user name valid?** Does the target user exist? 6. **Is the target group name valid?** Does the target group exist? 7. **Is the target user *NOT* superuser?** suEXEC does not allow `*root*` to execute CGI/SSI programs. 8. **Is the target userid *ABOVE* the minimum ID number?** The minimum user ID number is specified during configuration. This allows you to set the lowest possible userid that will be allowed to execute CGI/SSI programs. This is useful to block out "system" accounts. 9. **Is the target group *NOT* the superuser group?** Presently, suEXEC does not allow the `*root*` group to execute CGI/SSI programs. 10. **Is the target groupid *ABOVE* the minimum ID number?** The minimum group ID number is specified during configuration. This allows you to set the lowest possible groupid that will be allowed to execute CGI/SSI programs. This is useful to block out "system" groups. 11. **Can the wrapper successfully become the target user and group?** Here is where the program becomes the target user and group via setuid and setgid calls. The group access list is also initialized with all of the groups of which the user is a member. 12. **Can we change directory to the one in which the target CGI/SSI program resides?** If it doesn't exist, it can't very well contain files. If we can't change directory to it, it might as well not exist. 13. **Is the directory within the httpd webspace?** If the request is for a regular portion of the server, is the requested directory within suEXEC's document root? If the request is for a `[UserDir](mod/mod_userdir#userdir)`, is the requested directory within the directory configured as suEXEC's userdir (see [suEXEC's configuration options](#install))? 14. **Is the directory *NOT* writable by anyone else?** We don't want to open up the directory to others; only the owner user may be able to alter this directories contents. 15. **Does the target CGI/SSI program exist?** If it doesn't exists, it can't very well be executed. 16. **Is the target CGI/SSI program *NOT* writable by anyone else?** We don't want to give anyone other than the owner the ability to change the CGI/SSI program. 17. **Is the target CGI/SSI program *NOT* setuid or setgid?** We do not want to execute programs that will then change our UID/GID again. 18. **Is the target user/group the same as the program's user/group?** Is the user the owner of the file? 19. **Can we successfully clean the process environment to ensure safe operations?** suEXEC cleans the process's environment by establishing a safe execution PATH (defined during configuration), as well as only passing through those variables whose names are listed in the safe environment list (also created during configuration). 20. **Can we successfully become the target CGI/SSI program and execute?** Here is where suEXEC ends and the target CGI/SSI program begins. This is the standard operation of the suEXEC wrapper's security model. It is somewhat stringent and can impose new limitations and guidelines for CGI/SSI design, but it was developed carefully step-by-step with security in mind. For more information as to how this security model can limit your possibilities in regards to server configuration, as well as what security risks can be avoided with a proper suEXEC setup, see the ["Beware the Jabberwock"](#jabberwock) section of this document. Configuring & Installing suEXEC ------------------------------- Here's where we begin the fun. **suEXEC configuration options** `--enable-suexec` This option enables the suEXEC feature which is never installed or activated by default. At least one `--with-suexec-xxxxx` option has to be provided together with the `--enable-suexec` option to let APACI accept your request for using the suEXEC feature. `--with-suexec-bin=*PATH*` The path to the `suexec` binary must be hard-coded in the server for security reasons. Use this option to override the default path. *e.g.* `--with-suexec-bin=/usr/sbin/suexec` `--with-suexec-caller=*UID*` The [username](mod/mpm_common#user) under which httpd normally runs. This is the only user allowed to execute the suEXEC wrapper. `--with-suexec-userdir=*DIR*` Define to be the subdirectory under users' home directories where suEXEC access should be allowed. All executables under this directory will be executable by suEXEC as the user so they should be "safe" programs. If you are using a "simple" `[UserDir](mod/mod_userdir#userdir)` directive (ie. one without a "\*" in it) this should be set to the same value. suEXEC will not work properly in cases where the `[UserDir](mod/mod_userdir#userdir)` directive points to a location that is not the same as the user's home directory as referenced in the `passwd` file. Default value is "`public_html`". If you have virtual hosts with a different `[UserDir](mod/mod_userdir#userdir)` for each, you will need to define them to all reside in one parent directory; then name that parent directory here. **If this is not defined properly, "~userdir" cgi requests will not work!** `--with-suexec-docroot=*DIR*` Define as the DocumentRoot set for httpd. This will be the only hierarchy (aside from `[UserDir](mod/mod_userdir#userdir)`s) that can be used for suEXEC behavior. The default directory is the `--datadir` value with the suffix "`/htdocs`", *e.g.* if you configure with "`--datadir=/home/apache`" the directory "`/home/apache/htdocs`" is used as document root for the suEXEC wrapper. `--with-suexec-uidmin=*UID*` Define this as the lowest UID allowed to be a target user for suEXEC. For most systems, 500 or 100 is common. Default value is 100. `--with-suexec-gidmin=*GID*` Define this as the lowest GID allowed to be a target group for suEXEC. For most systems, 100 is common and therefore used as default value. `--with-suexec-logfile=*FILE*` This defines the filename to which all suEXEC transactions and errors are logged (useful for auditing and debugging purposes). By default the logfile is named "`suexec_log`" and located in your standard logfile directory (`--logfiledir`). `--with-suexec-safepath=*PATH*` Define a safe PATH environment to pass to CGI executables. Default value is "`/usr/local/bin:/usr/bin:/bin`". ### Compiling and installing the suEXEC wrapper If you have enabled the suEXEC feature with the `--enable-suexec` option the `suexec` binary (together with httpd itself) is automatically built if you execute the `make` command. After all components have been built you can execute the command `make install` to install them. The binary image `suexec` is installed in the directory defined by the `--sbindir` option. The default location is "/usr/local/apache2/bin/suexec". Please note that you need ***root privileges*** for the installation step. In order for the wrapper to set the user ID, it must be installed as owner `*root*` and must have the setuserid execution bit set for file modes. ### Setting paranoid permissions Although the suEXEC wrapper will check to ensure that its caller is the correct user as specified with the `--with-suexec-caller` `[configure](programs/configure)` option, there is always the possibility that a system or library call suEXEC uses before this check may be exploitable on your system. To counter this, and because it is best-practise in general, you should use filesystem permissions to ensure that only the group httpd runs as may execute suEXEC. If for example, your web server is configured to run as: ``` User www Group webgroup ``` and `[suexec](programs/suexec)` is installed at "/usr/local/apache2/bin/suexec", you should run: ``` chgrp webgroup /usr/local/apache2/bin/suexec chmod 4750 /usr/local/apache2/bin/suexec ``` This will ensure that only the group httpd runs as can even execute the suEXEC wrapper. Enabling & Disabling suEXEC --------------------------- Upon startup of httpd, it looks for the file `[suexec](programs/suexec)` in the directory defined by the `--sbindir` option (default is "/usr/local/apache/sbin/suexec"). If httpd finds a properly configured suEXEC wrapper, it will print the following message to the error log: ``` [notice] suEXEC mechanism enabled (wrapper: /path/to/suexec) ``` If you don't see this message at server startup, the server is most likely not finding the wrapper program where it expects it, or the executable is not installed *setuid root*. If you want to enable the suEXEC mechanism for the first time and an Apache HTTP Server is already running you must kill and restart httpd. Restarting it with a simple HUP or USR1 signal will not be enough. If you want to disable suEXEC you should kill and restart httpd after you have removed the `[suexec](programs/suexec)` file. Using suEXEC ------------ Requests for CGI programs will call the suEXEC wrapper only if they are for a virtual host containing a `[SuexecUserGroup](mod/mod_suexec#suexecusergroup)` directive or if they are processed by `[mod\_userdir](mod/mod_userdir)`. **Virtual Hosts:** One way to use the suEXEC wrapper is through the `[SuexecUserGroup](mod/mod_suexec#suexecusergroup)` directive in `[VirtualHost](mod/core#virtualhost)` definitions. By setting this directive to values different from the main server user ID, all requests for CGI resources will be executed as the *User* and *Group* defined for that `[<VirtualHost>](mod/core#virtualhost)`. If this directive is not specified for a `[<VirtualHost>](mod/core#virtualhost)` then the main server userid is assumed. **User directories:** Requests that are processed by `[mod\_userdir](mod/mod_userdir)` will call the suEXEC wrapper to execute CGI programs under the userid of the requested user directory. The only requirement needed for this feature to work is for CGI execution to be enabled for the user and that the script must meet the scrutiny of the [security checks](#model) above. See also the `--with-suexec-userdir` [compile time option](#install). Debugging suEXEC ---------------- The suEXEC wrapper will write log information to the file defined with the `--with-suexec-logfile` option as indicated above. If you feel you have configured and installed the wrapper properly, have a look at this log and the error\_log for the server to see where you may have gone astray. Beware the Jabberwock: Warnings & Examples ------------------------------------------ **NOTE!** This section may not be complete. There are a few points of interest regarding the wrapper that can cause limitations on server setup. Please review these before submitting any "bugs" regarding suEXEC. **suEXEC Points Of Interest** * Hierarchy limitations For security and efficiency reasons, all suEXEC requests must remain within either a top-level document root for virtual host requests, or one top-level personal document root for userdir requests. For example, if you have four VirtualHosts configured, you would need to structure all of your VHosts' document roots off of one main httpd document hierarchy to take advantage of suEXEC for VirtualHosts. (Example forthcoming.) * suEXEC's PATH environment variable This can be a dangerous thing to change. Make certain every path you include in this define is a **trusted** directory. You don't want to open people up to having someone from across the world running a trojan horse on them. * Altering the suEXEC code Again, this can cause **Big Trouble** if you try this without knowing what you are doing. Stay away from it if at all possible.
programming_docs
apache_http_server Filters Filters ======= This document describes the use of filters in Apache. Filtering in Apache 2 --------------------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_filter](mod/mod_filter)` * `[mod\_deflate](mod/mod_deflate)` * `[mod\_ext\_filter](mod/mod_ext_filter)` * `[mod\_include](mod/mod_include)` * `[mod\_charset\_lite](mod/mod_charset_lite)` * `[mod\_reflector](mod/mod_reflector)` * `[mod\_buffer](mod/mod_buffer)` * `[mod\_data](mod/mod_data)` * `[mod\_ratelimit](mod/mod_ratelimit)` * `[mod\_reqtimeout](mod/mod_reqtimeout)` * `[mod\_request](mod/mod_request)` * `[mod\_sed](mod/mod_sed)` * `[mod\_substitute](mod/mod_substitute)` * `[mod\_xml2enc](mod/mod_xml2enc)` * `[mod\_proxy\_html](mod/mod_proxy_html)` | * `[FilterChain](mod/mod_filter#filterchain)` * `[FilterDeclare](mod/mod_filter#filterdeclare)` * `[FilterProtocol](mod/mod_filter#filterprotocol)` * `[FilterProvider](mod/mod_filter#filterprovider)` * `[AddInputFilter](mod/mod_mime#addinputfilter)` * `[AddOutputFilter](mod/mod_mime#addoutputfilter)` * `[RemoveInputFilter](mod/mod_mime#removeinputfilter)` * `[RemoveOutputFilter](mod/mod_mime#removeoutputfilter)` * `[ReflectorHeader](mod/mod_reflector#reflectorheader)` * `[ExtFilterDefine](mod/mod_ext_filter#extfilterdefine)` * `[ExtFilterOptions](mod/mod_ext_filter#extfilteroptions)` * `[SetInputFilter](mod/core#setinputfilter)` * `[SetOutputFilter](mod/core#setoutputfilter)` | The Filter Chain is available in Apache 2.0 and higher, and enables applications to process incoming and outgoing data in a highly flexible and configurable manner, regardless of where the data comes from. We can pre-process incoming data, and post-process outgoing data, at will. This is basically independent of the traditional request processing phases. Some examples of filtering in the standard Apache distribution are: * `[mod\_include](mod/mod_include)`, implements server-side includes. * `[mod\_ssl](mod/mod_ssl)`, implements SSL encryption (https). * `[mod\_deflate](mod/mod_deflate)`, implements compression/decompression on the fly. * `[mod\_charset\_lite](mod/mod_charset_lite)`, transcodes between different character sets. * `[mod\_ext\_filter](mod/mod_ext_filter)`, runs an external program as a filter. Apache also uses a number of filters internally to perform functions like chunking and byte-range handling. A wider range of applications are implemented by third-party filter modules. A few of these are: * HTML and XML processing and rewriting * XSLT transforms and XIncludes * XML Namespace support * File Upload handling and decoding of HTML Forms * Image processing * Protection of vulnerable applications such as PHP scripts * Text search-and-replace editing Smart Filtering --------------- `[mod\_filter](mod/mod_filter)`, included in Apache 2.1 and later, enables the filter chain to be configured dynamically at run time. So for example you can set up a proxy to rewrite HTML with an HTML filter and JPEG images with a completely separate filter, despite the proxy having no prior information about what the origin server will send. This works by using a filter harness, that dispatches to different providers according to the actual contents at runtime. Any filter may be either inserted directly in the chain and run unconditionally, or used as a provider and inserted dynamically. For example, * an HTML processing filter will only run if the content is text/html or application/xhtml+xml * A compression filter will only run if the input is a compressible type and not already compressed * A charset conversion filter will be inserted if a text document is not already in the desired charset Exposing Filters as an HTTP Service ----------------------------------- Filters can be used to process content originating from the client in addition to processing content originating on the server using the `[mod\_reflector](mod/mod_reflector)` module. `[mod\_reflector](mod/mod_reflector)` accepts POST requests from clients, and reflects the content request body received within the POST request back in the response, passing through the output filter stack on the way back to the client. This technique can be used as an alternative to a web service running within an application server stack, where an output filter provides the transformation required on the request body. For example, the `[mod\_deflate](mod/mod_deflate)` module might be used to provide a general compression service, or an image transformation filter might be turned into an image transformation service. Using Filters ------------- There are two ways to use filtering: Simple and Dynamic. In general, you should use one or the other; mixing them can have unexpected consequences (although simple Input filtering can be mixed freely with either simple or dynamic Output filtering). The Simple Way is the only way to configure input filters, and is sufficient for output filters where you need a static filter chain. Relevant directives are `[SetInputFilter](mod/core#setinputfilter)`, `[SetOutputFilter](mod/core#setoutputfilter)`, `[AddInputFilter](mod/mod_mime#addinputfilter)`, `[AddOutputFilter](mod/mod_mime#addoutputfilter)`, `[RemoveInputFilter](mod/mod_mime#removeinputfilter)`, and `[RemoveOutputFilter](mod/mod_mime#removeoutputfilter)`. The Dynamic Way enables both static and flexible, dynamic configuration of output filters, as discussed in the `[mod\_filter](mod/mod_filter)` page. Relevant directives are `[FilterChain](mod/mod_filter#filterchain)`, `[FilterDeclare](mod/mod_filter#filterdeclare)`, and `[FilterProvider](mod/mod_filter#filterprovider)`. One further directive `[AddOutputFilterByType](mod/mod_filter#addoutputfilterbytype)` is still supported, but deprecated. Use dynamic configuration instead. apache_http_server Apache Miscellaneous Documentation Apache Miscellaneous Documentation ================================== Below is a list of additional documentation pages that apply to the Apache web server development project. **Warning** The documents below have not been fully updated to take into account changes made in the 2.1 version of the Apache HTTP Server. Some of the information may still be relevant, but please use it with care. [Performance Notes - Apache Tuning](perf-tuning) Notes about how to (run-time and compile-time) configure Apache for highest performance. Notes explaining why Apache does some things, and why it doesn't do other things (which make it slower/faster). [Security Tips](security_tips) Some "do"s - and "don't"s - for keeping your Apache web site secure. [Relevant Standards](relevant_standards) This document acts as a reference page for most of the relevant standards that Apache follows. [Password Encryption Formats](password_encryptions) Discussion of the various ciphers supported by Apache for authentication purposes. apache_http_server Security Tips Security Tips ============= Some hints and tips on security issues in setting up a web server. Some of the suggestions will be general, others specific to Apache. Keep up to Date --------------- The Apache HTTP Server has a good record for security and a developer community highly concerned about security issues. But it is inevitable that some problems -- small or large -- will be discovered in software after it is released. For this reason, it is crucial to keep aware of updates to the software. If you have obtained your version of the HTTP Server directly from Apache, we highly recommend you subscribe to the [Apache HTTP Server Announcements List](http://httpd.apache.org/lists.html#http-announce) where you can keep informed of new releases and security updates. Similar services are available from most third-party distributors of Apache software. Of course, most times that a web server is compromised, it is not because of problems in the HTTP Server code. Rather, it comes from problems in add-on code, CGI scripts, or the underlying Operating System. You must therefore stay aware of problems and updates with all the software on your system. Denial of Service (DoS) attacks ------------------------------- All network servers can be subject to denial of service attacks that attempt to prevent responses to clients by tying up the resources of the server. It is not possible to prevent such attacks entirely, but you can do certain things to mitigate the problems that they create. Often the most effective anti-DoS tool will be a firewall or other operating-system configurations. For example, most firewalls can be configured to restrict the number of simultaneous connections from any individual IP address or network, thus preventing a range of simple attacks. Of course this is no help against Distributed Denial of Service attacks (DDoS). There are also certain Apache HTTP Server configuration settings that can help mitigate problems: * The `[RequestReadTimeout](../mod/mod_reqtimeout#requestreadtimeout)` directive allows to limit the time a client may take to send the request. * The `[TimeOut](../mod/core#timeout)` directive should be lowered on sites that are subject to DoS attacks. Setting this to as low as a few seconds may be appropriate. As `[TimeOut](../mod/core#timeout)` is currently used for several different operations, setting it to a low value introduces problems with long running CGI scripts. * The `[KeepAliveTimeout](../mod/core#keepalivetimeout)` directive may be also lowered on sites that are subject to DoS attacks. Some sites even turn off the keepalives completely via `[KeepAlive](../mod/core#keepalive)`, which has of course other drawbacks on performance. * The values of various timeout-related directives provided by other modules should be checked. * The directives `[LimitRequestBody](../mod/core#limitrequestbody)`, `[LimitRequestFields](../mod/core#limitrequestfields)`, `[LimitRequestFieldSize](../mod/core#limitrequestfieldsize)`, `[LimitRequestLine](../mod/core#limitrequestline)`, and `[LimitXMLRequestBody](../mod/core#limitxmlrequestbody)` should be carefully configured to limit resource consumption triggered by client input. * On operating systems that support it, make sure that you use the `[AcceptFilter](../mod/core#acceptfilter)` directive to offload part of the request processing to the operating system. This is active by default in Apache httpd, but may require reconfiguration of your kernel. * Tune the `[MaxRequestWorkers](../mod/mpm_common#maxrequestworkers)` directive to allow the server to handle the maximum number of simultaneous connections without running out of resources. See also the [performance tuning documentation](perf-tuning). * The use of a threaded [mpm](../mpm) may allow you to handle more simultaneous connections, thereby mitigating DoS attacks. Further, the `[event](../mod/event)` mpm uses asynchronous processing to avoid devoting a thread to each connection. Due to the nature of the OpenSSL library the `[event](../mod/event)` mpm is currently incompatible with `[mod\_ssl](../mod/mod_ssl)` and other input filters. In these cases it falls back to the behaviour of the `[worker](../mod/worker)` mpm. * There are a number of third-party modules available that can restrict certain client behaviors and thereby mitigate DoS problems. Permissions on ServerRoot Directories ------------------------------------- In typical operation, Apache is started by the root user, and it switches to the user defined by the `[User](../mod/mod_unixd#user)` directive to serve hits. As is the case with any command that root executes, you must take care that it is protected from modification by non-root users. Not only must the files themselves be writeable only by root, but so must the directories, and parents of all directories. For example, if you choose to place ServerRoot in `/usr/local/apache` then it is suggested that you create that directory as root, with commands like these: ``` mkdir /usr/local/apache cd /usr/local/apache mkdir bin conf logs chown 0 . bin conf logs chgrp 0 . bin conf logs chmod 755 . bin conf logs ``` It is assumed that `/`, `/usr`, and `/usr/local` are only modifiable by root. When you install the `[httpd](../programs/httpd)` executable, you should ensure that it is similarly protected: ``` cp httpd /usr/local/apache/bin chown 0 /usr/local/apache/bin/httpd chgrp 0 /usr/local/apache/bin/httpd chmod 511 /usr/local/apache/bin/httpd ``` You can create an htdocs subdirectory which is modifiable by other users -- since root never executes any files out of there, and shouldn't be creating files in there. If you allow non-root users to modify any files that root either executes or writes on then you open your system to root compromises. For example, someone could replace the `[httpd](../programs/httpd)` binary so that the next time you start it, it will execute some arbitrary code. If the logs directory is writeable (by a non-root user), someone could replace a log file with a symlink to some other system file, and then root might overwrite that file with arbitrary data. If the log files themselves are writeable (by a non-root user), then someone may be able to overwrite the log itself with bogus data. Server Side Includes -------------------- Server Side Includes (SSI) present a server administrator with several potential security risks. The first risk is the increased load on the server. All SSI-enabled files have to be parsed by Apache, whether or not there are any SSI directives included within the files. While this load increase is minor, in a shared server environment it can become significant. SSI files also pose the same risks that are associated with CGI scripts in general. Using the `exec cmd` element, SSI-enabled files can execute any CGI script or program under the permissions of the user and group Apache runs as, as configured in `httpd.conf`. There are ways to enhance the security of SSI files while still taking advantage of the benefits they provide. To isolate the damage a wayward SSI file can cause, a server administrator can enable [suexec](../suexec) as described in the [CGI in General](#cgi) section. Enabling SSI for files with `.html` or `.htm` extensions can be dangerous. This is especially true in a shared, or high traffic, server environment. SSI-enabled files should have a separate extension, such as the conventional `.shtml`. This helps keep server load at a minimum and allows for easier management of risk. Another solution is to disable the ability to run scripts and programs from SSI pages. To do this replace `Includes` with `IncludesNOEXEC` in the `[Options](../mod/core#options)` directive. Note that users may still use `<--#include virtual="..." -->` to execute CGI scripts if these scripts are in directories designated by a `[ScriptAlias](../mod/mod_alias#scriptalias)` directive. CGI in General -------------- First of all, you always have to remember that you must trust the writers of the CGI scripts/programs or your ability to spot potential security holes in CGI, whether they were deliberate or accidental. CGI scripts can run essentially arbitrary commands on your system with the permissions of the web server user and can therefore be extremely dangerous if they are not carefully checked. All the CGI scripts will run as the same user, so they have potential to conflict (accidentally or deliberately) with other scripts e.g. User A hates User B, so he writes a script to trash User B's CGI database. One program which can be used to allow scripts to run as different users is [suEXEC](../suexec) which is included with Apache as of 1.2 and is called from special hooks in the Apache server code. Another popular way of doing this is with [CGIWrap](http://cgiwrap.sourceforge.net/). Non Script Aliased CGI ---------------------- Allowing users to execute CGI scripts in any directory should only be considered if: * You trust your users not to write scripts which will deliberately or accidentally expose your system to an attack. * You consider security at your site to be so feeble in other areas, as to make one more potential hole irrelevant. * You have no users, and nobody ever visits your server. Script Aliased CGI ------------------ Limiting CGI to special directories gives the admin control over what goes into those directories. This is inevitably more secure than non script aliased CGI, but only if users with write access to the directories are trusted or the admin is willing to test each new CGI script/program for potential security holes. Most sites choose this option over the non script aliased CGI approach. Other sources of dynamic content -------------------------------- Embedded scripting options which run as part of the server itself, such as `mod_php`, `mod_perl`, `mod_tcl`, and `mod_python`, run under the identity of the server itself (see the `[User](../mod/mod_unixd#user)` directive), and therefore scripts executed by these engines potentially can access anything the server user can. Some scripting engines may provide restrictions, but it is better to be safe and assume not. Dynamic content security ------------------------ When setting up dynamic content, such as `mod_php`, `mod_perl` or `mod_python`, many security considerations get out of the scope of `httpd` itself, and you need to consult documentation from those modules. For example, PHP lets you setup [Safe Mode](http://www.php.net/manual/en/ini.sect.safe-mode.php), which is most usually disabled by default. Another example is [Suhosin](http://www.hardened-php.net/suhosin/), a PHP addon for more security. For more information about those, consult each project documentation. At the Apache level, a module named [mod\_security](http://modsecurity.org/) can be seen as a HTTP firewall and, provided you configure it finely enough, can help you enhance your dynamic content security. Protecting System Settings -------------------------- To run a really tight ship, you'll want to stop users from setting up `.htaccess` files which can override security features you've configured. Here's one way to do it. In the server configuration file, put ``` <Directory "/"> AllowOverride None </Directory> ``` This prevents the use of `.htaccess` files in all directories apart from those specifically enabled. Note that this setting is the default since Apache 2.3.9. Protect Server Files by Default ------------------------------- One aspect of Apache which is occasionally misunderstood is the feature of default access. That is, unless you take steps to change it, if the server can find its way to a file through normal URL mapping rules, it can serve it to clients. For instance, consider the following example: ``` # cd /; ln -s / public_html Accessing http://localhost/~root/ ``` This would allow clients to walk through the entire filesystem. To work around this, add the following block to your server's configuration: ``` <Directory "/"> Require all denied </Directory> ``` This will forbid default access to filesystem locations. Add appropriate `[Directory](../mod/core#directory)` blocks to allow access only in those areas you wish. For example, ``` <Directory "/usr/users/*/public_html"> Require all granted </Directory> <Directory "/usr/local/httpd"> Require all granted </Directory> ``` Pay particular attention to the interactions of `[Location](../mod/core#location)` and `[Directory](../mod/core#directory)` directives; for instance, even if `<Directory "/">` denies access, a `<Location "/">` directive might overturn it. Also be wary of playing games with the `[UserDir](../mod/mod_userdir#userdir)` directive; setting it to something like `./` would have the same effect, for root, as the first example above. We strongly recommend that you include the following line in your server configuration files: ``` UserDir disabled root ``` Watching Your Logs ------------------ To keep up-to-date with what is actually going on against your server you have to check the [Log Files](../logs). Even though the log files only reports what has already happened, they will give you some understanding of what attacks is thrown against the server and allow you to check if the necessary level of security is present. A couple of examples: ``` grep -c "/jsp/source.jsp?/jsp/ /jsp/source.jsp??" access_log grep "client denied" error_log | tail -n 10 ``` The first example will list the number of attacks trying to exploit the [Apache Tomcat Source.JSP Malformed Request Information Disclosure Vulnerability](http://online.securityfocus.com/bid/4876/info/), the second example will list the ten last denied clients, for example: ``` [Thu Jul 11 17:18:39 2002] [error] [client foo.example.com] client denied by server configuration: /usr/local/apache/htdocs/.htpasswd ``` As you can see, the log files only report what already has happened, so if the client had been able to access the `.htpasswd` file you would have seen something similar to: ``` foo.example.com - - [12/Jul/2002:01:59:13 +0200] "GET /.htpasswd HTTP/1.1" ``` in your [Access Log](../logs#accesslog). This means you probably commented out the following in your server configuration file: ``` <Files ".ht*"> Require all denied </Files> ``` Merging of configuration sections --------------------------------- The merging of configuration sections is complicated and sometimes directive specific. Always test your changes when creating dependencies on how directives are merged. For modules that don't implement any merging logic, such as `[mod\_access\_compat](../mod/mod_access_compat)`, the behavior in later sections depends on whether the later section has any directives from the module. The configuration is inherited until a change is made, at which point the configuration is *replaced* and not merged.
programming_docs
apache_http_server Apache Performance Tuning Apache Performance Tuning ========================= Apache 2.x is a general-purpose webserver, designed to provide a balance of flexibility, portability, and performance. Although it has not been designed specifically to set benchmark records, Apache 2.x is capable of high performance in many real-world situations. Compared to Apache 1.3, release 2.x contains many additional optimizations to increase throughput and scalability. Most of these improvements are enabled by default. However, there are compile-time and run-time configuration choices that can significantly affect performance. This document describes the options that a server administrator can configure to tune the performance of an Apache 2.x installation. Some of these configuration options enable the httpd to better take advantage of the capabilities of the hardware and OS, while others allow the administrator to trade functionality for speed. Hardware and Operating System Issues ------------------------------------ The single biggest hardware issue affecting webserver performance is RAM. A webserver should never ever have to swap, as swapping increases the latency of each request beyond a point that users consider "fast enough". This causes users to hit stop and reload, further increasing the load. You can, and should, control the `[MaxRequestWorkers](../mod/mpm_common#maxrequestworkers)` setting so that your server does not spawn so many children that it starts swapping. The procedure for doing this is simple: determine the size of your average Apache process, by looking at your process list via a tool such as `top`, and divide this into your total available memory, leaving some room for other processes. Beyond that the rest is mundane: get a fast enough CPU, a fast enough network card, and fast enough disks, where "fast enough" is something that needs to be determined by experimentation. Operating system choice is largely a matter of local concerns. But some guidelines that have proven generally useful are: * Run the latest stable release and patch level of the operating system that you choose. Many OS suppliers have introduced significant performance improvements to their TCP stacks and thread libraries in recent years. * If your OS supports a `sendfile(2)` system call, make sure you install the release and/or patches needed to enable it. (With Linux, for example, this means using Linux 2.4 or later. For early releases of Solaris 8, you may need to apply a patch.) On systems where it is available, `sendfile` enables Apache 2 to deliver static content faster and with lower CPU utilization. Run-Time Configuration Issues ----------------------------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_dir](../mod/mod_dir)` * `[mpm\_common](../mod/mpm_common)` * `[mod\_status](../mod/mod_status)` | * `[AllowOverride](../mod/core#allowoverride)` * `[DirectoryIndex](../mod/mod_dir#directoryindex)` * `[HostnameLookups](../mod/core#hostnamelookups)` * `[EnableMMAP](../mod/core#enablemmap)` * `[EnableSendfile](../mod/core#enablesendfile)` * `[KeepAliveTimeout](../mod/core#keepalivetimeout)` * `[MaxSpareServers](../mod/prefork#maxspareservers)` * `[MinSpareServers](../mod/prefork#minspareservers)` * `[Options](../mod/core#options)` * `[StartServers](../mod/mpm_common#startservers)` | ### HostnameLookups and other DNS considerations Prior to Apache 1.3, `[HostnameLookups](../mod/core#hostnamelookups)` defaulted to `On`. This adds latency to every request because it requires a DNS lookup to complete before the request is finished. In Apache 1.3 this setting defaults to `Off`. If you need to have addresses in your log files resolved to hostnames, use the `[logresolve](../programs/logresolve)` program that comes with Apache, or one of the numerous log reporting packages which are available. It is recommended that you do this sort of postprocessing of your log files on some machine other than the production web server machine, in order that this activity not adversely affect server performance. If you use any ``[Allow](../mod/mod_access_compat#allow)` from domain` or ``[Deny](../mod/mod_access_compat#deny)` from domain` directives (i.e., using a hostname, or a domain name, rather than an IP address) then you will pay for two DNS lookups (a reverse, followed by a forward lookup to make sure that the reverse is not being spoofed). For best performance, therefore, use IP addresses, rather than names, when using these directives, if possible. Note that it's possible to scope the directives, such as within a `<Location "/server-status">` section. In this case the DNS lookups are only performed on requests matching the criteria. Here's an example which disables lookups except for `.html` and `.cgi` files: ``` HostnameLookups off <Files ~ "\.(html|cgi)$"> HostnameLookups on </Files> ``` But even still, if you just need DNS names in some CGIs you could consider doing the `gethostbyname` call in the specific CGIs that need it. ### FollowSymLinks and SymLinksIfOwnerMatch Wherever in your URL-space you do not have an `Options FollowSymLinks`, or you do have an `Options SymLinksIfOwnerMatch`, Apache will need to issue extra system calls to check up on symlinks. (One extra call per filename component.) For example, if you had: ``` DocumentRoot "/www/htdocs" <Directory "/"> Options SymLinksIfOwnerMatch </Directory> ``` and a request is made for the URI `/index.html`, then Apache will perform `lstat(2)` on `/www`, `/www/htdocs`, and `/www/htdocs/index.html`. The results of these `lstats` are never cached, so they will occur on every single request. If you really desire the symlinks security checking, you can do something like this: ``` DocumentRoot "/www/htdocs" <Directory "/"> Options FollowSymLinks </Directory> <Directory "/www/htdocs"> Options -FollowSymLinks +SymLinksIfOwnerMatch </Directory> ``` This at least avoids the extra checks for the `[DocumentRoot](../mod/core#documentroot)` path. Note that you'll need to add similar sections if you have any `[Alias](../mod/mod_alias#alias)` or `[RewriteRule](../mod/mod_rewrite#rewriterule)` paths outside of your document root. For highest performance, and no symlink protection, set `FollowSymLinks` everywhere, and never set `SymLinksIfOwnerMatch`. ### AllowOverride Wherever in your URL-space you allow overrides (typically `.htaccess` files), Apache will attempt to open `.htaccess` for each filename component. For example, ``` DocumentRoot "/www/htdocs" <Directory "/"> AllowOverride all </Directory> ``` and a request is made for the URI `/index.html`. Then Apache will attempt to open `/.htaccess`, `/www/.htaccess`, and `/www/htdocs/.htaccess`. The solutions are similar to the previous case of `Options FollowSymLinks`. For highest performance use `AllowOverride None` everywhere in your filesystem. ### Negotiation If at all possible, avoid content negotiation if you're really interested in every last ounce of performance. In practice the benefits of negotiation outweigh the performance penalties. There's one case where you can speed up the server. Instead of using a wildcard such as: ``` DirectoryIndex index ``` Use a complete list of options: ``` DirectoryIndex index.cgi index.pl index.shtml index.html ``` where you list the most common choice first. Also note that explicitly creating a `type-map` file provides better performance than using `MultiViews`, as the necessary information can be determined by reading this single file, rather than having to scan the directory for files. If your site needs content negotiation, consider using `type-map` files, rather than the `Options MultiViews` directive to accomplish the negotiation. See the [Content Negotiation](../content-negotiation) documentation for a full discussion of the methods of negotiation, and instructions for creating `type-map` files. ### Memory-mapping In situations where Apache 2.x needs to look at the contents of a file being delivered--for example, when doing server-side-include processing--it normally memory-maps the file if the OS supports some form of `mmap(2)`. On some platforms, this memory-mapping improves performance. However, there are cases where memory-mapping can hurt the performance or even the stability of the httpd: * On some operating systems, `mmap` does not scale as well as `read(2)` when the number of CPUs increases. On multiprocessor Solaris servers, for example, Apache 2.x sometimes delivers server-parsed files faster when `mmap` is disabled. * If you memory-map a file located on an NFS-mounted filesystem and a process on another NFS client machine deletes or truncates the file, your process may get a bus error the next time it tries to access the mapped file content. For installations where either of these factors applies, you should use `EnableMMAP off` to disable the memory-mapping of delivered files. (Note: This directive can be overridden on a per-directory basis.) ### Sendfile In situations where Apache 2.x can ignore the contents of the file to be delivered -- for example, when serving static file content -- it normally uses the kernel sendfile support for the file if the OS supports the `sendfile(2)` operation. On most platforms, using sendfile improves performance by eliminating separate read and send mechanics. However, there are cases where using sendfile can harm the stability of the httpd: * Some platforms may have broken sendfile support that the build system did not detect, especially if the binaries were built on another box and moved to such a machine with broken sendfile support. * With an NFS-mounted filesystem, the kernel may be unable to reliably serve the network file through its own cache. For installations where either of these factors applies, you should use `EnableSendfile off` to disable sendfile delivery of file contents. (Note: This directive can be overridden on a per-directory basis.) ### Process Creation Prior to Apache 1.3 the `[MinSpareServers](../mod/prefork#minspareservers)`, `[MaxSpareServers](../mod/prefork#maxspareservers)`, and `[StartServers](../mod/mpm_common#startservers)` settings all had drastic effects on benchmark results. In particular, Apache required a "ramp-up" period in order to reach a number of children sufficient to serve the load being applied. After the initial spawning of `[StartServers](../mod/mpm_common#startservers)` children, only one child per second would be created to satisfy the `[MinSpareServers](../mod/prefork#minspareservers)` setting. So a server being accessed by 100 simultaneous clients, using the default `[StartServers](../mod/mpm_common#startservers)` of `5` would take on the order of 95 seconds to spawn enough children to handle the load. This works fine in practice on real-life servers because they aren't restarted frequently. But it does really poorly on benchmarks which might only run for ten minutes. The one-per-second rule was implemented in an effort to avoid swamping the machine with the startup of new children. If the machine is busy spawning children, it can't service requests. But it has such a drastic effect on the perceived performance of Apache that it had to be replaced. As of Apache 1.3, the code will relax the one-per-second rule. It will spawn one, wait a second, then spawn two, wait a second, then spawn four, and it will continue exponentially until it is spawning 32 children per second. It will stop whenever it satisfies the `[MinSpareServers](../mod/prefork#minspareservers)` setting. This appears to be responsive enough that it's almost unnecessary to twiddle the `[MinSpareServers](../mod/prefork#minspareservers)`, `[MaxSpareServers](../mod/prefork#maxspareservers)` and `[StartServers](../mod/mpm_common#startservers)` knobs. When more than 4 children are spawned per second, a message will be emitted to the `[ErrorLog](../mod/core#errorlog)`. If you see a lot of these errors, then consider tuning these settings. Use the `[mod\_status](../mod/mod_status)` output as a guide. Related to process creation is process death induced by the `[MaxConnectionsPerChild](../mod/mpm_common#maxconnectionsperchild)` setting. By default this is `0`, which means that there is no limit to the number of connections handled per child. If your configuration currently has this set to some very low number, such as `30`, you may want to bump this up significantly. If you are running SunOS or an old version of Solaris, limit this to `10000` or so because of memory leaks. When keep-alives are in use, children will be kept busy doing nothing waiting for more requests on the already open connection. The default `[KeepAliveTimeout](../mod/core#keepalivetimeout)` of `5` seconds attempts to minimize this effect. The tradeoff here is between network bandwidth and server resources. In no event should you raise this above about `60` seconds, as [most of the benefits are lost](http://www.hpl.hp.com/techreports/Compaq-DEC/WRL-95-4.html). Compile-Time Configuration Issues --------------------------------- ### Choosing an MPM Apache 2.x supports pluggable concurrency models, called [Multi-Processing Modules](../mpm) (MPMs). When building Apache, you must choose an MPM to use. There are platform-specific MPMs for some platforms: `[mpm\_netware](../mod/mpm_netware)`, `[mpmt\_os2](../mod/mpmt_os2)`, and `[mpm\_winnt](../mod/mpm_winnt)`. For general Unix-type systems, there are several MPMs from which to choose. The choice of MPM can affect the speed and scalability of the httpd: * The `[worker](../mod/worker)` MPM uses multiple child processes with many threads each. Each thread handles one connection at a time. Worker generally is a good choice for high-traffic servers because it has a smaller memory footprint than the prefork MPM. * The `[event](../mod/event)` MPM is threaded like the Worker MPM, but is designed to allow more requests to be served simultaneously by passing off some processing work to supporting threads, freeing up the main threads to work on new requests. * The `[prefork](../mod/prefork)` MPM uses multiple child processes with one thread each. Each process handles one connection at a time. On many systems, prefork is comparable in speed to worker, but it uses more memory. Prefork's threadless design has advantages over worker in some situations: it can be used with non-thread-safe third-party modules, and it is easier to debug on platforms with poor thread debugging support. For more information on these and other MPMs, please see the MPM [documentation](../mpm). ### Modules Since memory usage is such an important consideration in performance, you should attempt to eliminate modules that you are not actually using. If you have built the modules as [DSOs](../dso), eliminating modules is a simple matter of commenting out the associated `[LoadModule](../mod/mod_so#loadmodule)` directive for that module. This allows you to experiment with removing modules and seeing if your site still functions in their absence. If, on the other hand, you have modules statically linked into your Apache binary, you will need to recompile Apache in order to remove unwanted modules. An associated question that arises here is, of course, what modules you need, and which ones you don't. The answer here will, of course, vary from one web site to another. However, the *minimal* list of modules which you can get by with tends to include `[mod\_mime](../mod/mod_mime)`, `[mod\_dir](../mod/mod_dir)`, and `[mod\_log\_config](../mod/mod_log_config)`. `mod_log_config` is, of course, optional, as you can run a web site without log files. This is, however, not recommended. ### Atomic Operations Some modules, such as `[mod\_cache](../mod/mod_cache)` and recent development builds of the worker MPM, use APR's atomic API. This API provides atomic operations that can be used for lightweight thread synchronization. By default, APR implements these operations using the most efficient mechanism available on each target OS/CPU platform. Many modern CPUs, for example, have an instruction that does an atomic compare-and-swap (CAS) operation in hardware. On some platforms, however, APR defaults to a slower, mutex-based implementation of the atomic API in order to ensure compatibility with older CPU models that lack such instructions. If you are building Apache for one of these platforms, and you plan to run only on newer CPUs, you can select a faster atomic implementation at build time by configuring Apache with the `--enable-nonportable-atomics` option: ``` ./buildconf ./configure --with-mpm=worker --enable-nonportable-atomics=yes ``` The `--enable-nonportable-atomics` option is relevant for the following platforms: * Solaris on SPARC By default, APR uses mutex-based atomics on Solaris/SPARC. If you configure with `--enable-nonportable-atomics`, however, APR generates code that uses a SPARC v8plus opcode for fast hardware compare-and-swap. If you configure Apache with this option, the atomic operations will be more efficient (allowing for lower CPU utilization and higher concurrency), but the resulting executable will run only on UltraSPARC chips. * Linux on x86 By default, APR uses mutex-based atomics on Linux. If you configure with `--enable-nonportable-atomics`, however, APR generates code that uses a 486 opcode for fast hardware compare-and-swap. This will result in more efficient atomic operations, but the resulting executable will run only on 486 and later chips (and not on 386). ### mod\_status and ExtendedStatus On If you include `[mod\_status](../mod/mod_status)` and you also set `ExtendedStatus On` when building and running Apache, then on every request Apache will perform two calls to `gettimeofday(2)` (or `times(2)` depending on your operating system), and (pre-1.3) several extra calls to `time(2)`. This is all done so that the status report contains timing indications. For highest performance, set `ExtendedStatus off` (which is the default). ### accept Serialization - Multiple Sockets **Warning:** This section has not been fully updated to take into account changes made in the 2.x version of the Apache HTTP Server. Some of the information may still be relevant, but please use it with care. This discusses a shortcoming in the Unix socket API. Suppose your web server uses multiple `[Listen](../mod/mpm_common#listen)` statements to listen on either multiple ports or multiple addresses. In order to test each socket to see if a connection is ready, Apache uses `select(2)`. `select(2)` indicates that a socket has *zero* or *at least one* connection waiting on it. Apache's model includes multiple children, and all the idle ones test for new connections at the same time. A naive implementation looks something like this (these examples do not match the code, they're contrived for pedagogical purposes): ``` for (;;) { for (;;) { fd_set accept_fds; FD_ZERO (&accept_fds); for (i = first_socket; i <= last_socket; ++i) { FD_SET (i, &accept_fds); } rc = select (last_socket+1, &accept_fds, NULL, NULL, NULL); if (rc < 1) continue; new_connection = -1; for (i = first_socket; i <= last_socket; ++i) { if (FD_ISSET (i, &accept_fds)) { new_connection = accept (i, NULL, NULL); if (new_connection != -1) break; } } if (new_connection != -1) break; } process_the(new_connection); } ``` But this naive implementation has a serious starvation problem. Recall that multiple children execute this loop at the same time, and so multiple children will block at `select` when they are in between requests. All those blocked children will awaken and return from `select` when a single request appears on any socket. (The number of children which awaken varies depending on the operating system and timing issues.) They will all then fall down into the loop and try to `accept` the connection. But only one will succeed (assuming there's still only one connection ready). The rest will be *blocked* in `accept`. This effectively locks those children into serving requests from that one socket and no other sockets, and they'll be stuck there until enough new requests appear on that socket to wake them all up. This starvation problem was first documented in [PR#467](http://bugs.apache.org/index/full/467). There are at least two solutions. One solution is to make the sockets non-blocking. In this case the `accept` won't block the children, and they will be allowed to continue immediately. But this wastes CPU time. Suppose you have ten idle children in `select`, and one connection arrives. Then nine of those children will wake up, try to `accept` the connection, fail, and loop back into `select`, accomplishing nothing. Meanwhile none of those children are servicing requests that occurred on other sockets until they get back up to the `select` again. Overall this solution does not seem very fruitful unless you have as many idle CPUs (in a multiprocessor box) as you have idle children (not a very likely situation). Another solution, the one used by Apache, is to serialize entry into the inner loop. The loop looks like this (differences highlighted): ``` for (;;) { **accept\_mutex\_on ();** for (;;) { fd_set accept_fds; FD_ZERO (&accept_fds); for (i = first_socket; i <= last_socket; ++i) { FD_SET (i, &accept_fds); } rc = select (last_socket+1, &accept_fds, NULL, NULL, NULL); if (rc < 1) continue; new_connection = -1; for (i = first_socket; i <= last_socket; ++i) { if (FD_ISSET (i, &accept_fds)) { new_connection = accept (i, NULL, NULL); if (new_connection != -1) break; } } if (new_connection != -1) break; } **accept\_mutex\_off ();** process the new_connection; } ``` The functions `accept_mutex_on` and `accept_mutex_off` implement a mutual exclusion semaphore. Only one child can have the mutex at any time. There are several choices for implementing these mutexes. The choice is defined in `src/conf.h` (pre-1.3) or `src/include/ap_config.h` (1.3 or later). Some architectures do not have any locking choice made, on these architectures it is unsafe to use multiple `[Listen](../mod/mpm_common#listen)` directives. The `[Mutex](../mod/core#mutex)` directive can be used to change the mutex implementation of the `mpm-accept` mutex at run-time. Special considerations for different mutex implementations are documented with that directive. Another solution that has been considered but never implemented is to partially serialize the loop -- that is, let in a certain number of processes. This would only be of interest on multiprocessor boxes where it's possible that multiple children could run simultaneously, and the serialization actually doesn't take advantage of the full bandwidth. This is a possible area of future investigation, but priority remains low because highly parallel web servers are not the norm. Ideally you should run servers without multiple `[Listen](../mod/mpm_common#listen)` statements if you want the highest performance. But read on. ### accept Serialization - Single Socket The above is fine and dandy for multiple socket servers, but what about single socket servers? In theory they shouldn't experience any of these same problems because all the children can just block in `accept(2)` until a connection arrives, and no starvation results. In practice this hides almost the same "spinning" behavior discussed above in the non-blocking solution. The way that most TCP stacks are implemented, the kernel actually wakes up all processes blocked in `accept` when a single connection arrives. One of those processes gets the connection and returns to user-space. The rest spin in the kernel and go back to sleep when they discover there's no connection for them. This spinning is hidden from the user-land code, but it's there nonetheless. This can result in the same load-spiking wasteful behavior that a non-blocking solution to the multiple sockets case can. For this reason we have found that many architectures behave more "nicely" if we serialize even the single socket case. So this is actually the default in almost all cases. Crude experiments under Linux (2.0.30 on a dual Pentium pro 166 w/128Mb RAM) have shown that the serialization of the single socket case causes less than a 3% decrease in requests per second over unserialized single-socket. But unserialized single-socket showed an extra 100ms latency on each request. This latency is probably a wash on long haul lines, and only an issue on LANs. If you want to override the single socket serialization, you can define `SINGLE_LISTEN_UNSERIALIZED_ACCEPT`, and then single-socket servers will not serialize at all. ### Lingering Close As discussed in [draft-ietf-http-connection-00.txt](http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-connection-00.txt) section 8, in order for an HTTP server to **reliably** implement the protocol, it needs to shut down each direction of the communication independently. (Recall that a TCP connection is bi-directional. Each half is independent of the other.) When this feature was added to Apache, it caused a flurry of problems on various versions of Unix because of shortsightedness. The TCP specification does not state that the `FIN_WAIT_2` state has a timeout, but it doesn't prohibit it. On systems without the timeout, Apache 1.2 induces many sockets stuck forever in the `FIN_WAIT_2` state. In many cases this can be avoided by simply upgrading to the latest TCP/IP patches supplied by the vendor. In cases where the vendor has never released patches (*i.e.*, SunOS4 -- although folks with a source license can patch it themselves), we have decided to disable this feature. There are two ways to accomplish this. One is the socket option `SO_LINGER`. But as fate would have it, this has never been implemented properly in most TCP/IP stacks. Even on those stacks with a proper implementation (*i.e.*, Linux 2.0.31), this method proves to be more expensive (cputime) than the next solution. For the most part, Apache implements this in a function called `lingering_close` (in `http_main.c`). The function looks roughly like this: ``` void lingering_close (int s) { char junk_buffer[2048]; /* shutdown the sending side */ shutdown (s, 1); signal (SIGALRM, lingering_death); alarm (30); for (;;) { select (s for reading, 2 second timeout); if (error) break; if (s is ready for reading) { if (read (s, junk_buffer, sizeof (junk_buffer)) <= 0) { break; } /* just toss away whatever is here */ } } close (s); } ``` This naturally adds some expense at the end of a connection, but it is required for a reliable implementation. As HTTP/1.1 becomes more prevalent, and all connections are persistent, this expense will be amortized over more requests. If you want to play with fire and disable this feature, you can define `NO_LINGCLOSE`, but this is not recommended at all. In particular, as HTTP/1.1 pipelined persistent connections come into use, `lingering_close` is an absolute necessity (and [pipelined connections are faster](http://www.w3.org/Protocols/HTTP/Performance/Pipeline.html), so you want to support them). ### Scoreboard File Apache's parent and children communicate with each other through something called the scoreboard. Ideally this should be implemented in shared memory. For those operating systems that we either have access to, or have been given detailed ports for, it typically is implemented using shared memory. The rest default to using an on-disk file. The on-disk file is not only slow, but it is unreliable (and less featured). Peruse the `src/main/conf.h` file for your architecture, and look for either `USE_MMAP_SCOREBOARD` or `USE_SHMGET_SCOREBOARD`. Defining one of those two (as well as their companions `HAVE_MMAP` and `HAVE_SHMGET` respectively) enables the supplied shared memory code. If your system has another type of shared memory, edit the file `src/main/http_main.c` and add the hooks necessary to use it in Apache. (Send us back a patch too, please.) Historical note: The Linux port of Apache didn't start to use shared memory until version 1.2 of Apache. This oversight resulted in really poor and unreliable behavior of earlier versions of Apache on Linux. ### DYNAMIC\_MODULE\_LIMIT If you have no intention of using dynamically loaded modules (you probably don't if you're reading this and tuning your server for every last ounce of performance), then you should add `-DDYNAMIC_MODULE_LIMIT=0` when building your server. This will save RAM that's allocated only for supporting dynamically loaded modules. Appendix: Detailed Analysis of a Trace -------------------------------------- Here is a system call trace of Apache 2.0.38 with the worker MPM on Solaris 8. This trace was collected using: ``` truss -l -p httpd_child_pid. ``` The `-l` option tells truss to log the ID of the LWP (lightweight process--Solaris' form of kernel-level thread) that invokes each system call. Other systems may have different system call tracing utilities such as `strace`, `ktrace`, or `par`. They all produce similar output. In this trace, a client has requested a 10KB static file from the httpd. Traces of non-static requests or requests with content negotiation look wildly different (and quite ugly in some cases). ``` /67: accept(3, 0x00200BEC, 0x00200C0C, 1) (sleeping...) /67: accept(3, 0x00200BEC, 0x00200C0C, 1) = 9 ``` In this trace, the listener thread is running within LWP #67. Note the lack of `accept(2)` serialization. On this particular platform, the worker MPM uses an unserialized accept by default unless it is listening on multiple ports. ``` /65: lwp_park(0x00000000, 0) = 0 /67: lwp_unpark(65, 1) = 0 ``` Upon accepting the connection, the listener thread wakes up a worker thread to do the request processing. In this trace, the worker thread that handles the request is mapped to LWP #65. ``` /65: getsockname(9, 0x00200BA4, 0x00200BC4, 1) = 0 ``` In order to implement virtual hosts, Apache needs to know the local socket address used to accept the connection. It is possible to eliminate this call in many situations (such as when there are no virtual hosts, or when `[Listen](../mod/mpm_common#listen)` directives are used which do not have wildcard addresses). But no effort has yet been made to do these optimizations. ``` /65: brk(0x002170E8) = 0 /65: brk(0x002190E8) = 0 ``` The `brk(2)` calls allocate memory from the heap. It is rare to see these in a system call trace, because the httpd uses custom memory allocators (`apr_pool` and `apr_bucket_alloc`) for most request processing. In this trace, the httpd has just been started, so it must call `malloc(3)` to get the blocks of raw memory with which to create the custom memory allocators. ``` /65: fcntl(9, F_GETFL, 0x00000000) = 2 /65: fstat64(9, 0xFAF7B818) = 0 /65: getsockopt(9, 65535, 8192, 0xFAF7B918, 0xFAF7B910, 2190656) = 0 /65: fstat64(9, 0xFAF7B818) = 0 /65: getsockopt(9, 65535, 8192, 0xFAF7B918, 0xFAF7B914, 2190656) = 0 /65: setsockopt(9, 65535, 8192, 0xFAF7B918, 4, 2190656) = 0 /65: fcntl(9, F_SETFL, 0x00000082) = 0 ``` Next, the worker thread puts the connection to the client (file descriptor 9) in non-blocking mode. The `setsockopt(2)` and `getsockopt(2)` calls are a side-effect of how Solaris' libc handles `fcntl(2)` on sockets. ``` /65: read(9, " G E T / 1 0 k . h t m".., 8000) = 97 ``` The worker thread reads the request from the client. ``` /65: stat("/var/httpd/apache/httpd-8999/htdocs/10k.html", 0xFAF7B978) = 0 /65: open("/var/httpd/apache/httpd-8999/htdocs/10k.html", O_RDONLY) = 10 ``` This httpd has been configured with `Options FollowSymLinks` and `AllowOverride None`. Thus it doesn't need to `lstat(2)` each directory in the path leading up to the requested file, nor check for `.htaccess` files. It simply calls `stat(2)` to verify that the file: 1) exists, and 2) is a regular file, not a directory. ``` /65: sendfilev(0, 9, 0x00200F90, 2, 0xFAF7B53C) = 10269 ``` In this example, the httpd is able to send the HTTP response header and the requested file with a single `sendfilev(2)` system call. Sendfile semantics vary among operating systems. On some other systems, it is necessary to do a `write(2)` or `writev(2)` call to send the headers before calling `sendfile(2)`. ``` /65: write(4, " 1 2 7 . 0 . 0 . 1 - ".., 78) = 78 ``` This `write(2)` call records the request in the access log. Note that one thing missing from this trace is a `time(2)` call. Unlike Apache 1.3, Apache 2.x uses `gettimeofday(3)` to look up the time. On some operating systems, like Linux or Solaris, `gettimeofday` has an optimized implementation that doesn't require as much overhead as a typical system call. ``` /65: shutdown(9, 1, 1) = 0 /65: poll(0xFAF7B980, 1, 2000) = 1 /65: read(9, 0xFAF7BC20, 512) = 0 /65: close(9) = 0 ``` The worker thread does a lingering close of the connection. ``` /65: close(10) = 0 /65: lwp_park(0x00000000, 0) (sleeping...) ``` Finally the worker thread closes the file that it has just delivered and blocks until the listener assigns it another connection. ``` /67: accept(3, 0x001FEB74, 0x001FEB94, 1) (sleeping...) ``` Meanwhile, the listener thread is able to accept another connection as soon as it has dispatched this connection to a worker thread (subject to some flow-control logic in the worker MPM that throttles the listener if all the available workers are busy). Though it isn't apparent from this trace, the next `accept(2)` can (and usually does, under high load conditions) occur in parallel with the worker thread's handling of the just-accepted connection.
programming_docs
apache_http_server Relevant Standards Relevant Standards ================== This page documents all the relevant standards that the Apache HTTP Server follows, along with brief descriptions. In addition to the information listed below, the following resources should be consulted: * <http://purl.org/NET/http-errata> - HTTP/1.1 Specification Errata * <http://www.rfc-editor.org/errata.php> - RFC Errata * <http://ftp.ics.uci.edu/pub/ietf/http/#RFC> - A pre-compiled list of HTTP related RFCs **Notice** This document is not yet complete. HTTP Recommendations -------------------- Regardless of what modules are compiled and used, Apache as a basic web server complies with the following IETF recommendations: [RFC 1945](http://www.rfc-editor.org/rfc/rfc1945.txt) (Informational) The Hypertext Transfer Protocol (HTTP) is an application-level protocol with the lightness and speed necessary for distributed, collaborative, hypermedia information systems. This documents HTTP/1.0. [RFC 2616](http://www.rfc-editor.org/rfc/rfc2616.txt) (Standards Track) The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. This documents HTTP/1.1. [RFC 2396](http://www.rfc-editor.org/rfc/rfc2396.txt) (Standards Track) A Uniform Resource Identifier (URI) is a compact string of characters for identifying an abstract or physical resource. [RFC 4346](http://www.rfc-editor.org/rfc/rfc4346.txt) (Standards Track) The TLS protocol provides communications security over the Internet. It provides encryption, and is designed to prevent eavesdropping, tampering, and message forgery. HTML Recommendations -------------------- Regarding the Hypertext Markup Language, Apache complies with the following IETF and W3C recommendations: [RFC 2854](http://www.rfc-editor.org/rfc/rfc2854.txt) (Informational) This document summarizes the history of HTML development, and defines the "text/html" MIME type by pointing to the relevant W3C recommendations. [HTML 4.01 Specification](http://www.w3.org/TR/html401) ([Errata](http://www.w3.org/MarkUp/html4-updates/errata)) This specification defines the HyperText Markup Language (HTML), the publishing language of the World Wide Web. This specification defines HTML 4.01, which is a subversion of HTML 4. [HTML 3.2 Reference Specification](http://www.w3.org/TR/REC-html32) The HyperText Markup Language (HTML) is a simple markup language used to create hypertext documents that are portable from one platform to another. HTML documents are SGML documents. [XHTML 1.1 - Module-based XHTML](http://www.w3.org/TR/xhtml11/) ([Errata](http://www.w3.org/MarkUp/2009/xhtml11-2nd-edition-errata.html)) This Recommendation defines a new XHTML document type that is based upon the module framework and modules defined in Modularization of XHTML. [XHTML 1.0 The Extensible HyperText Markup Language (Second Edition)](http://www.w3.org/TR/xhtml1) ([Errata](http://www.w3.org/2002/08/REC-xhtml1-20020801-errata/)) This specification defines the Second Edition of XHTML 1.0, a reformulation of HTML 4 as an XML 1.0 application, and three DTDs corresponding to the ones defined by HTML 4. Authentication -------------- Concerning the different methods of authentication, Apache follows the following IETF recommendations: [RFC 2617](http://www.rfc-editor.org/rfc/rfc2617.txt) (Standards Track) "HTTP/1.0", includes the specification for a Basic Access Authentication scheme. Language/Country Codes ---------------------- The following links document ISO and other language and country code information: [ISO 639-2](http://www.loc.gov/standards/iso639-2/) ISO 639 provides two sets of language codes, one as a two-letter code set (639-1) and another as a three-letter code set (this part of ISO 639) for the representation of names of languages. [ISO 3166-1](http://www.iso.org/iso/country_codes) These pages document the country names (official short names in English) in alphabetical order as given in ISO 3166-1 and the corresponding ISO 3166-1-alpha-2 code elements. [BCP 47](http://www.rfc-editor.org/rfc/bcp/bcp47.txt) (Best Current Practice), [RFC 3066](http://www.rfc-editor.org/rfc/rfc3066.txt) This document describes a language tag for use in cases where it is desired to indicate the language used in an information object, how to register values for use in this language tag, and a construct for matching such language tags. [RFC 3282](http://www.rfc-editor.org/rfc/rfc3282.txt) (Standards Track) This document defines a "Content-language:" header, for use in cases where one desires to indicate the language of something that has RFC 822-like headers, like MIME body parts or Web documents, and an "Accept-Language:" header for use in cases where one wishes to indicate one's preferences with regard to language. apache_http_server Password Formats Password Formats ================ Notes about the password encryption formats generated and understood by Apache. Basic Authentication -------------------- There are five formats that Apache recognizes for basic-authentication passwords. Note that not all formats work on every platform: bcrypt "$2y$" + the result of the crypt\_blowfish algorithm. See the APR source file [crypt\_blowfish.c](http://svn.apache.org/viewvc/apr/apr/trunk/crypto/crypt_blowfish.c?view=markup) for the details of the algorithm. MD5 "$apr1$" + the result of an Apache-specific algorithm using an iterated (1,000 times) MD5 digest of various combinations of a random 32-bit salt and the password. See the APR source file [apr\_md5.c](http://svn.apache.org/viewvc/apr/apr/trunk/crypto/apr_md5.c?view=markup) for the details of the algorithm. SHA1 "{SHA}" + Base64-encoded SHA-1 digest of the password. Insecure. CRYPT Unix only. Uses the traditional Unix `crypt(3)` function with a randomly-generated 32-bit salt (only 12 bits used) and the first 8 characters of the password. Insecure. PLAIN TEXT (i.e. *unencrypted*) Windows & Netware only. Insecure. ### Generating values with htpasswd ### bcrypt ``` $ htpasswd -nbB myName myPassword myName:$2y$05$c4WoMPo3SXsafkva.HHa6uXQZWr7oboPiC2bT/r7q1BB8I2s0BRqC ``` ### MD5 ``` $ htpasswd -nbm myName myPassword myName:$apr1$r31.....$HqJZimcKQFAMYayBlzkrA/ ``` ### SHA1 ``` $ htpasswd -nbs myName myPassword myName:{SHA}VBPuJHI7uixaa6LQGWx4s+5GKNE= ``` ### CRYPT ``` $ htpasswd -nbd myName myPassword myName:rqXexS6ZhobKA ``` ### Generating CRYPT and MD5 values with the OpenSSL command-line program OpenSSL knows the Apache-specific MD5 algorithm. ### MD5 ``` $ openssl passwd -apr1 myPassword $apr1$qHDFfhPC$nITSVHgYbDAK1Y0acGRnY0 ``` ### CRYPT ``` openssl passwd -crypt myPassword qQ5vTYO3c8dsU ``` ### Validating CRYPT or MD5 passwords with the OpenSSL command line program The salt for a CRYPT password is the first two characters (converted to a binary value). To validate `myPassword` against `rqXexS6ZhobKA` ### CRYPT ``` $ openssl passwd -crypt -salt rq myPassword Warning: truncating password to 8 characters rqXexS6ZhobKA ``` Note that using `myPasswo` instead of `myPassword` will produce the same result because only the first 8 characters of CRYPT passwords are considered. The salt for an MD5 password is between `$apr1$` and the following `$` (as a Base64-encoded binary value - max 8 chars). To validate `myPassword` against `$apr1$r31.....$HqJZimcKQFAMYayBlzkrA/` ### MD5 ``` $ openssl passwd -apr1 -salt r31..... myPassword $apr1$r31.....$HqJZimcKQFAMYayBlzkrA/ ``` ### Database password fields for mod\_dbd The SHA1 variant is probably the most useful format for DBD authentication. Since the SHA1 and Base64 functions are commonly available, other software can populate a database with encrypted passwords that are usable by Apache basic authentication. To create Apache SHA1-variant basic-authentication passwords in various languages: ### PHP ``` '{SHA}' . base64_encode(sha1($password, TRUE)) ``` ### Java ``` "{SHA}" + new sun.misc.BASE64Encoder().encode(java.security.MessageDigest.getInstance("SHA1").digest(password.getBytes())) ``` ### ColdFusion ``` "{SHA}" & ToBase64(BinaryDecode(Hash(password, "SHA1"), "Hex")) ``` ### Ruby ``` require 'digest/sha1' require 'base64' '{SHA}' + Base64.encode64(Digest::SHA1.digest(password)) ``` ### C or C++ ``` Use the APR function: apr_sha1_base64 ``` ### Python ``` import base64 import hashlib "{SHA}" + format(base64.b64encode(hashlib.sha1(password).digest())) ``` ### PostgreSQL (with the contrib/pgcrypto functions installed) `'{SHA}'||encode(digest(password,'sha1'),'base64')` Digest Authentication --------------------- Apache recognizes one format for digest-authentication passwords - the MD5 hash of the string `user:realm:password` as a 32-character string of hexadecimal digits. `realm` is the Authorization Realm argument to the `[AuthName](../mod/mod_authn_core#authname)` directive in httpd.conf. ### Database password fields for mod\_dbd Since the MD5 function is commonly available, other software can populate a database with encrypted passwords that are usable by Apache digest authentication. To create Apache digest-authentication passwords in various languages: ### PHP ``` md5($user . ':' . $realm . ':' .$password) ``` ### Java ``` byte b[] = java.security.MessageDigest.getInstance("MD5").digest( (user + ":" + realm + ":" + password ).getBytes()); java.math.BigInteger bi = new java.math.BigInteger(1, b); String s = bi.toString(16); while (s.length() < 32) s = "0" + s; // String s is the encrypted password ``` ### ColdFusion ``` LCase(Hash( (user & ":" & realm & ":" & password) , "MD5")) ``` ### Ruby ``` require 'digest/md5' Digest::MD5.hexdigest(user + ':' + realm + ':' + password) ``` ### PostgreSQL (with the contrib/pgcrypto functions installed) ``` encode(digest( user || ':' || realm || ':' || password , 'md5'), 'hex') ``` apache_http_server Redirecting and Remapping with mod_rewrite Redirecting and Remapping with mod\_rewrite =========================================== This document supplements the `[mod\_rewrite](../mod/mod_rewrite)` [reference documentation](../mod/mod_rewrite). It describes how you can use `[mod\_rewrite](../mod/mod_rewrite)` to redirect and remap request. This includes many examples of common uses of mod\_rewrite, including detailed descriptions of how each works. Note that many of these examples won't work unchanged in your particular server configuration, so it's important that you understand them, rather than merely cutting and pasting the examples into your configuration. From Old to New (internal) -------------------------- Description: Assume we have recently renamed the page `foo.html` to `bar.html` and now want to provide the old URL for backward compatibility. However, we want that users of the old URL even not recognize that the pages was renamed - that is, we don't want the address to change in their browser. Solution: We rewrite the old URL to the new one internally via the following rule: ``` RewriteEngine on RewriteRule "^**/foo**\.html$" "**/bar**.html" [PT] ``` Rewriting From Old to New (external) ------------------------------------ Description: Assume again that we have recently renamed the page `foo.html` to `bar.html` and now want to provide the old URL for backward compatibility. But this time we want that the users of the old URL get hinted to the new one, i.e. their browsers Location field should change, too. Solution: We force a HTTP redirect to the new URL which leads to a change of the browsers and thus the users view: ``` RewriteEngine on RewriteRule "^**/foo**\.html$" "**bar**.html" [**R**] ``` Discussion In this example, as contrasted to the [internal](#old-to-new-intern) example above, we can simply use the Redirect directive. mod\_rewrite was used in that earlier example in order to hide the redirect from the client: ``` Redirect "/foo.html" "/bar.html" ``` Resource Moved to Another Server -------------------------------- Description: If a resource has moved to another server, you may wish to have URLs continue to work for a time on the old server while people update their bookmarks. Solution: You can use `[mod\_rewrite](../mod/mod_rewrite)` to redirect these URLs to the new server, but you might also consider using the Redirect or RedirectMatch directive. ``` #With mod_rewrite RewriteEngine on RewriteRule "^/docs/(.+)" "http://new.example.com/docs/$1" [R,L] ``` ``` #With RedirectMatch RedirectMatch "^/docs/(.*)" "http://new.example.com/docs/$1" ``` ``` #With Redirect Redirect "/docs/" "http://new.example.com/docs/" ``` From Static to Dynamic ---------------------- Description: How can we transform a static page `foo.html` into a dynamic variant `foo.cgi` in a seamless way, i.e. without notice by the browser/user. Solution: We just rewrite the URL to the CGI-script and force the handler to be **cgi-script** so that it is executed as a CGI program. This way a request to `/~quux/foo.html` internally leads to the invocation of `/~quux/foo.cgi`. ``` RewriteEngine on RewriteBase "/~quux/" RewriteRule "^foo\.html$" "foo.cgi" [H=**cgi-script**] ``` Backward Compatibility for file extension change ------------------------------------------------ Description: How can we make URLs backward compatible (still existing virtually) after migrating `document.YYYY` to `document.XXXX`, e.g. after translating a bunch of `.html` files to `.php`? Solution: We rewrite the name to its basename and test for existence of the new extension. If it exists, we take that name, else we rewrite the URL to its original state. ``` # backward compatibility ruleset for # rewriting document.html to document.php # when and only when document.php exists <Directory "/var/www/htdocs"> RewriteEngine on RewriteBase "/var/www/htdocs" RewriteCond "$1.php" -f RewriteCond "$1.html" !-f RewriteRule "^(.*).html$" "$1.php" </Directory> ``` Discussion This example uses an often-overlooked feature of mod\_rewrite, by taking advantage of the order of execution of the ruleset. In particular, mod\_rewrite evaluates the left-hand-side of the RewriteRule before it evaluates the RewriteCond directives. Consequently, $1 is already defined by the time the RewriteCond directives are evaluated. This allows us to test for the existence of the original (`document.html`) and target (`document.php`) files using the same base filename. This ruleset is designed to use in a per-directory context (In a <Directory> block or in a .htaccess file), so that the `-f` checks are looking at the correct directory path. You may need to set a `[RewriteBase](../mod/mod_rewrite#rewritebase)` directive to specify the directory base that you're working in. Canonical Hostnames ------------------- Description: The goal of this rule is to force the use of a particular hostname, in preference to other hostnames which may be used to reach the same site. For example, if you wish to force the use of **www.example.com** instead of **example.com**, you might use a variant of the following recipe. Solution: The very best way to solve this doesn't involve mod\_rewrite at all, but rather uses the `[Redirect](../mod/mod_alias#redirect)` directive placed in a virtual host for the non-canonical hostname(s). ``` <VirtualHost *:80> ServerName undesired.example.com ServerAlias example.com notthis.example.com Redirect "/" "http://www.example.com/" </VirtualHost> <VirtualHost *:80> ServerName www.example.com </VirtualHost> ``` You can alternatively accomplish this using the `[<If>](../mod/core#if)` directive: ``` <If "%{HTTP_HOST} != 'www.example.com'"> Redirect "/" "http://www.example.com/" </If> ``` Or, for example, to redirect a portion of your site to HTTPS, you might do the following: ``` <If "%{SERVER_PROTOCOL} != 'HTTPS'"> Redirect "/admin/" "https://www.example.com/admin/" </If> ``` If, for whatever reason, you still want to use `mod_rewrite` - if, for example, you need this to work with a larger set of RewriteRules - you might use one of the recipes below. For sites running on a port other than 80: ``` RewriteCond "%{HTTP_HOST}" "!^www\.example\.com" [NC] RewriteCond "%{HTTP_HOST}" "!^$" RewriteCond "%{SERVER_PORT}" "!^80$" RewriteRule "^/?(.*)" "http://www.example.com:%{SERVER_PORT}/$1" [L,R,NE] ``` And for a site running on port 80 ``` RewriteCond "%{HTTP_HOST}" "!^www\.example\.com" [NC] RewriteCond "%{HTTP_HOST}" "!^$" RewriteRule "^/?(.*)" "http://www.example.com/$1" [L,R,NE] ``` If you wanted to do this generically for all domain names - that is, if you want to redirect **example.com** to **www.example.com** for all possible values of **example.com**, you could use the following recipe: ``` RewriteCond "%{HTTP_HOST}" "!^www\." [NC] RewriteCond "%{HTTP_HOST}" "!^$" RewriteRule "^/?(.*)" "http://www.%{HTTP_HOST}/$1" [L,R,NE] ``` These rulesets will work either in your main server configuration file, or in a `.htaccess` file placed in the `[DocumentRoot](../mod/core#documentroot)` of the server. Search for pages in more than one directory ------------------------------------------- Description: A particular resource might exist in one of several places, and we want to look in those places for the resource when it is requested. Perhaps we've recently rearranged our directory structure, dividing content into several locations. Solution: The following ruleset searches in two directories to find the resource, and, if not finding it in either place, will attempt to just serve it out of the location requested. ``` RewriteEngine on # first try to find it in dir1/... # ...and if found stop and be happy: RewriteCond "%{DOCUMENT_ROOT}/**dir1**/%{REQUEST_URI}" -f RewriteRule "^(.+)" "%{DOCUMENT_ROOT}/**dir1**/$1" [L] # second try to find it in dir2/... # ...and if found stop and be happy: RewriteCond "%{DOCUMENT_ROOT}/**dir2**/%{REQUEST_URI}" -f RewriteRule "^(.+)" "%{DOCUMENT_ROOT}/**dir2**/$1" [L] # else go on for other Alias or ScriptAlias directives, # etc. RewriteRule "^" "-" [PT] ``` Redirecting to Geographically Distributed Servers ------------------------------------------------- Description: We have numerous mirrors of our website, and want to redirect people to the one that is located in the country where they are located. Solution: Looking at the hostname of the requesting client, we determine which country they are coming from. If we can't do a lookup on their IP address, we fall back to a default server. We'll use a `[RewriteMap](../mod/mod_rewrite#rewritemap)` directive to build a list of servers that we wish to use. ``` HostnameLookups on RewriteEngine on RewriteMap multiplex "txt:/path/to/map.mirrors" RewriteCond "%{REMOTE_HOST}" "([a-z]+)$" [NC] RewriteRule "^/(.*)$" "${multiplex:**%1**|http://www.example.com/}$1" [R,L] ``` ``` ## map.mirrors -- Multiplexing Map de http://www.example.de/ uk http://www.example.uk/ com http://www.example.com/ ##EOF## ``` Discussion This ruleset relies on `[HostNameLookups](../mod/core#hostnamelookups)` being set `on`, which can be a significant performance hit. The `[RewriteCond](../mod/mod_rewrite#rewritecond)` directive captures the last portion of the hostname of the requesting client - the country code - and the following RewriteRule uses that value to look up the appropriate mirror host in the map file. Browser Dependent Content ------------------------- Description: We wish to provide different content based on the browser, or user-agent, which is requesting the content. Solution: We have to decide, based on the HTTP header "User-Agent", which content to serve. The following config does the following: If the HTTP header "User-Agent" contains "Mozilla/3", the page `foo.html` is rewritten to `foo.NS.html` and the rewriting stops. If the browser is "Lynx" or "Mozilla" of version 1 or 2, the URL becomes `foo.20.html`. All other browsers receive page `foo.32.html`. This is done with the following ruleset: ``` RewriteCond "%{HTTP_USER_AGENT}" "^**Mozilla/3**.*" RewriteRule "^foo\.html$" "foo.**NS**.html" [**L**] RewriteCond "%{HTTP_USER_AGENT}" "^Lynx/" [OR] RewriteCond "%{HTTP_USER_AGENT}" "^Mozilla/[12]" RewriteRule "^foo\.html$" "foo.**20**.html" [**L**] RewriteRule "^foo\.html$" "foo.**32**.html" [**L**] ``` Canonical URLs -------------- Description: On some webservers there is more than one URL for a resource. Usually there are canonical URLs (which are be actually used and distributed) and those which are just shortcuts, internal ones, and so on. Independent of which URL the user supplied with the request, they should finally see the canonical one in their browser address bar. Solution: We do an external HTTP redirect for all non-canonical URLs to fix them in the location view of the Browser and for all subsequent requests. In the example ruleset below we replace `/puppies` and `/canines` by the canonical `/dogs`. ``` RewriteRule "^/(puppies|canines)/(.*)" "/dogs/$2" [R] ``` Discussion: This should really be accomplished with Redirect or RedirectMatch directives: ``` RedirectMatch "^/(puppies|canines)/(.*)" "/dogs/$2" ``` Moved `DocumentRoot` -------------------- Description: Usually the `[DocumentRoot](../mod/core#documentroot)` of the webserver directly relates to the URL "`/`". But often this data is not really of top-level priority. For example, you may wish for visitors, on first entering a site, to go to a particular subdirectory `/about/`. This may be accomplished using the following ruleset: Solution: We redirect the URL `/` to `/about/`: ``` RewriteEngine on RewriteRule "^/$" "/about/" [**R**] ``` Note that this can also be handled using the `[RedirectMatch](../mod/mod_alias#redirectmatch)` directive: ``` RedirectMatch "^/$" "http://example.com/about/" ``` Note also that the example rewrites only the root URL. That is, it rewrites a request for `http://example.com/`, but not a request for `http://example.com/page.html`. If you have in fact changed your document root - that is, if **all** of your content is in fact in that subdirectory, it is greatly preferable to simply change your `[DocumentRoot](../mod/core#documentroot)` directive, or move all of the content up one directory, rather than rewriting URLs. Fallback Resource ----------------- Description: You want a single resource (say, a certain file, like index.php) to handle all requests that come to a particular directory, except those that should go to an existing resource such as an image, or a css file. Solution: As of version 2.2.16, you should use the `[FallbackResource](../mod/mod_dir#fallbackresource)` directive for this: ``` <Directory "/var/www/my_blog"> FallbackResource "index.php" </Directory> ``` However, in earlier versions of Apache, or if your needs are more complicated than this, you can use a variation of the following rewrite set to accomplish the same thing: ``` <Directory "/var/www/my_blog"> RewriteBase "/my_blog" RewriteCond "/var/www/my_blog/%{REQUEST_FILENAME}" !-f RewriteCond "/var/www/my_blog/%{REQUEST_FILENAME}" !-d RewriteRule "^" "index.php" [PT] </Directory> ``` If, on the other hand, you wish to pass the requested URI as a query string argument to index.php, you can replace that RewriteRule with: ``` RewriteRule "(.*)" "index.php?$1" [PT,QSA] ``` Note that these rulesets can be used in a `.htaccess` file, as well as in a <Directory> block. Rewrite query string -------------------- Description: You want to capture a particular value from a query string and either replace it or incorporate it into another component of the URL. Solutions: Many of the solutions in this section will all use the same condition, which leaves the matched value in the %2 backreference. %1 is the beginining of the query string (up to the key of intererest), and %3 is the remainder. This condition is a bit complex for flexibility and to avoid double '&&' in the substitutions. * This solution removes the matching key and value: ``` # Remove mykey=??? RewriteCond "%{QUERY_STRING}" "(.*(?:^|&))mykey=([^&]*)&?(.*)&?$" RewriteRule "(.*)" "$1?%1%3" ``` * This solution uses the captured value in the URL substitution, discarding the rest of the original query by appending a '?': ``` # Copy from query string to PATH_INFO RewriteCond "%{QUERY_STRING}" "(.*(?:^|&))mykey=([^&]*)&?(.*)&?$" RewriteRule "(.*)" "$1/products/%2/?" [PT] ``` * This solution checks the captured value in a subsequent condition: ``` # Capture the value of mykey in the query string RewriteCond "%{QUERY_STRING}" "(.*(?:^|&))mykey=([^&]*)&?(.*)&?$" RewriteCond "%2" !=not-so-secret-value RewriteRule "(.*)" - [F] ``` * This solution shows the reverse of the previous ones, copying path components (perhaps PATH\_INFO) from the URL into the query string. ``` # The desired URL might be /products/kitchen-sink, and the script expects # /path?products=kitchen-sink. RewriteRule "^/?path/([^/]+)/([^/]+)" "/path?$1=$2" [PT] ```
programming_docs
apache_http_server RewriteRule Flags RewriteRule Flags ================= This document discusses the flags which are available to the `[RewriteRule](../mod/mod_rewrite#rewriterule)` directive, providing detailed explanations and examples. Introduction ------------ A `[RewriteRule](../mod/mod_rewrite#rewriterule)` can have its behavior modified by one or more flags. Flags are included in square brackets at the end of the rule, and multiple flags are separated by commas. ``` RewriteRule pattern target [Flag1,Flag2,Flag3] ``` Each flag (with a few exceptions) has a short form, such as `CO`, as well as a longer form, such as `cookie`. While it is most common to use the short form, it is recommended that you familiarize yourself with the long form, so that you remember what each flag is supposed to do. Some flags take one or more arguments. Flags are not case sensitive. Flags that alter metadata associated with the request (T=, H=, E=) have no affect in per-directory and htaccess context, when a substitution (other than '-') is performed during the same round of rewrite processing. Presented here are each of the available flags, along with an example of how you might use them. B (escape backreferences) ------------------------- The [B] flag instructs `[RewriteRule](../mod/mod_rewrite#rewriterule)` to escape non-alphanumeric characters before applying the transformation. In 2.4.26 and later, you can limit the escaping to specific characters in backreferences by listing them: `[B=#?;]`. Note: The space character can be used in the list of characters to escape, but it cannot be the last character in the list. `mod_rewrite` has to unescape URLs before mapping them, so backreferences are unescaped at the time they are applied. Using the B flag, non-alphanumeric characters in backreferences will be escaped. For example, consider the rule: ``` RewriteRule "^search/(.*)$" "/search.php?term=$1" ``` Given a search term of 'x & y/z', a browser will encode it as 'x%20%26%20y%2Fz', making the request 'search/x%20%26%20y%2Fz'. Without the B flag, this rewrite rule will map to 'search.php?term=x & y/z', which isn't a valid URL, and so would be encoded as `search.php?term=x%20&y%2Fz=`, which is not what was intended. With the B flag set on this same rule, the parameters are re-encoded before being passed on to the output URL, resulting in a correct mapping to `/search.php?term=x%20%26%20y%2Fz`. ``` RewriteRule "^search/(.*)$" "/search.php?term=$1" [B,PT] ``` Note that you may also need to set `[AllowEncodedSlashes](../mod/core#allowencodedslashes)` to `On` to get this particular example to work, as httpd does not allow encoded slashes in URLs, and returns a 404 if it sees one. This escaping is particularly necessary in a proxy situation, when the backend may break if presented with an unescaped URL. An alternative to this flag is using a `[RewriteCond](../mod/mod_rewrite#rewritecond)` to capture against %{THE\_REQUEST} which will capture strings in the encoded form. BNP|backrefnoplus (don't escape space to +) ------------------------------------------- The [BNP] flag instructs `[RewriteRule](../mod/mod_rewrite#rewriterule)` to escape the space character in a backreference to %20 rather than '+'. Useful when the backreference will be used in the path component rather than the query string. This flag is available in version 2.4.26 and later. C|chain ------- The [C] or [chain] flag indicates that the `[RewriteRule](../mod/mod_rewrite#rewriterule)` is chained to the next rule. That is, if the rule matches, then it is processed as usual and control moves on to the next rule. However, if it does not match, then the next rule, and any other rules that are chained together, are skipped. CO|cookie --------- The [CO], or [cookie] flag, allows you to set a cookie when a particular `[RewriteRule](../mod/mod_rewrite#rewriterule)` matches. The argument consists of three required fields and five optional fields. The full syntax for the flag, including all attributes, is as follows: `[CO=NAME:VALUE:DOMAIN:lifetime:path:secure:httponly:samesite]` If a literal ':' character is needed in any of the cookie fields, an alternate syntax is available. To opt-in to the alternate syntax, the cookie "Name" should be preceded with a ';' character, and field separators should be specified as ';'. `[CO=;NAME;VALUE:MOREVALUE;DOMAIN;lifetime;path;secure;httponly;samesite]` You must declare a name, a value, and a domain for the cookie to be set. Domain The domain for which you want the cookie to be valid. This may be a hostname, such as `www.example.com`, or it may be a domain, such as `.example.com`. It must be at least two parts separated by a dot. That is, it may not be merely `.com` or `.net`. Cookies of that kind are forbidden by the cookie security model. You may optionally also set the following values: Lifetime The time for which the cookie will persist, in minutes. A value of 0 indicates that the cookie will persist only for the current browser session. This is the default value if none is specified. Path The path, on the current website, for which the cookie is valid, such as `/customers/` or `/files/download/`. By default, this is set to `/` - that is, the entire website. Secure If set to `secure`, `true`, or `1`, the cookie will only be permitted to be translated via secure (https) connections. httponly If set to `HttpOnly`, `true`, or `1`, the cookie will have the `HttpOnly` flag set, which means that the cookie is inaccessible to JavaScript code on browsers that support this feature. samesite If set to anything other than `false` or `0`, the `SameSite` attribute is set to the specified value. Typical values are `None`, `Lax`, and `Strict`.Available in 2.5.1 and later. Consider this example: ``` RewriteEngine On RewriteRule "^/index\.html" "-" [CO=frontdoor:yes:.example.com:1440:/] ``` In the example give, the rule doesn't rewrite the request. The "-" rewrite target tells mod\_rewrite to pass the request through unchanged. Instead, it sets a cookie called 'frontdoor' to a value of 'yes'. The cookie is valid for any host in the `.example.com` domain. It is set to expire in 1440 minutes (24 hours) and is returned for all URIs. DPI|discardpath --------------- The DPI flag causes the PATH\_INFO portion of the rewritten URI to be discarded. This flag is available in version 2.2.12 and later. In per-directory context, the URI each `RewriteRule` compares against is the concatenation of the current values of the URI and PATH\_INFO. The current URI can be the initial URI as requested by the client, the result of a previous round of mod\_rewrite processing, or the result of a prior rule in the current round of mod\_rewrite processing. In contrast, the PATH\_INFO that is appended to the URI before each rule reflects only the value of PATH\_INFO before this round of mod\_rewrite processing. As a consequence, if large portions of the URI are matched and copied into a substitution in multiple `RewriteRule` directives, without regard for which parts of the URI came from the current PATH\_INFO, the final URI may have multiple copies of PATH\_INFO appended to it. Use this flag on any substitution where the PATH\_INFO that resulted from the previous mapping of this request to the filesystem is not of interest. This flag permanently forgets the PATH\_INFO established before this round of mod\_rewrite processing began. PATH\_INFO will not be recalculated until the current round of mod\_rewrite processing completes. Subsequent rules during this round of processing will see only the direct result of substitutions, without any PATH\_INFO appended. E|env ----- With the [E], or [env] flag, you can set the value of an environment variable. Note that some environment variables may be set after the rule is run, thus unsetting what you have set. See [the Environment Variables document](../env) for more details on how Environment variables work. The full syntax for this flag is: ``` [E=VAR:VAL] [E=!VAR] ``` `VAL` may contain backreferences (`$N` or `%N`) which are expanded. Using the short form `[E=VAR]` you can set the environment variable named `VAR` to an empty value. The form `[E=!VAR]` allows to unset a previously set environment variable named `VAR`. Environment variables can then be used in a variety of contexts, including CGI programs, other RewriteRule directives, or CustomLog directives. The following example sets an environment variable called 'image' to a value of '1' if the requested URI is an image file. Then, that environment variable is used to exclude those requests from the access log. ``` RewriteRule "\.(png|gif|jpg)$" "-" [E=image:1] CustomLog "logs/access_log" combined env=!image ``` Note that this same effect can be obtained using `[SetEnvIf](../mod/mod_setenvif#setenvif)`. This technique is offered as an example, not as a recommendation. END --- Using the [END] flag terminates not only the current round of rewrite processing (like [L]) but also prevents any subsequent rewrite processing from occurring in per-directory (htaccess) context. This does not apply to new requests resulting from external redirects. F|forbidden ----------- Using the [F] flag causes the server to return a 403 Forbidden status code to the client. While the same behavior can be accomplished using the `[Deny](../mod/mod_access_compat#deny)` directive, this allows more flexibility in assigning a Forbidden status. The following rule will forbid `.exe` files from being downloaded from your server. ``` RewriteRule "\.exe" "-" [F] ``` This example uses the "-" syntax for the rewrite target, which means that the requested URI is not modified. There's no reason to rewrite to another URI, if you're going to forbid the request. When using [F], an [L] is implied - that is, the response is returned immediately, and no further rules are evaluated. G|gone ------ The [G] flag forces the server to return a 410 Gone status with the response. This indicates that a resource used to be available, but is no longer available. As with the [F] flag, you will typically use the "-" syntax for the rewrite target when using the [G] flag: ``` RewriteRule "oldproduct" "-" [G,NC] ``` When using [G], an [L] is implied - that is, the response is returned immediately, and no further rules are evaluated. H|handler --------- Forces the resulting request to be handled with the specified handler. For example, one might use this to force all files without a file extension to be parsed by the php handler: ``` RewriteRule "!\." "-" [H=application/x-httpd-php] ``` The regular expression above - `!\.` - will match any request that does not contain the literal `.` character. This can be also used to force the handler based on some conditions. For example, the following snippet used in per-server context allows `.php` files to be *displayed* by `mod_php` if they are requested with the `.phps` extension: ``` RewriteRule "^(/source/.+\.php)s$" "$1" [H=application/x-httpd-php-source] ``` The regular expression above - `^(/source/.+\.php)s$` - will match any request that starts with `/source/` followed by 1 or n characters followed by `.phps` literally. The backreference $1 referrers to the captured match within parenthesis of the regular expression. L|last ------ The [L] flag causes `[mod\_rewrite](../mod/mod_rewrite)` to stop processing the rule set. In most contexts, this means that if the rule matches, no further rules will be processed. This corresponds to the `last` command in Perl, or the `break` command in C. Use this flag to indicate that the current rule should be applied immediately without considering further rules. If you are using `[RewriteRule](../mod/mod_rewrite#rewriterule)` in either `.htaccess` files or in `[<Directory>](../mod/core#directory)` sections, it is important to have some understanding of how the rules are processed. The simplified form of this is that once the rules have been processed, the rewritten request is handed back to the URL parsing engine to do what it may with it. It is possible that as the rewritten request is handled, the `.htaccess` file or `[<Directory>](../mod/core#directory)` section may be encountered again, and thus the ruleset may be run again from the start. Most commonly this will happen if one of the rules causes a redirect - either internal or external - causing the request process to start over. It is therefore important, if you are using `[RewriteRule](../mod/mod_rewrite#rewriterule)` directives in one of these contexts, that you take explicit steps to avoid rules looping, and not count solely on the [L] flag to terminate execution of a series of rules, as shown below. An alternative flag, [END], can be used to terminate not only the current round of rewrite processing but prevent any subsequent rewrite processing from occurring in per-directory (htaccess) context. This does not apply to new requests resulting from external redirects. The example given here will rewrite any request to `index.php`, giving the original request as a query string argument to `index.php`, however, the `[RewriteCond](../mod/mod_rewrite#rewritecond)` ensures that if the request is already for `index.php`, the `[RewriteRule](../mod/mod_rewrite#rewriterule)` will be skipped. ``` RewriteBase "/" RewriteCond "%{REQUEST_URI}" "!=/index.php" RewriteRule "^(.*)" "/index.php?req=$1" [L,PT] ``` N|next ------ The [N] flag causes the ruleset to start over again from the top, using the result of the ruleset so far as a starting point. Use with extreme caution, as it may result in loop. The [Next] flag could be used, for example, if you wished to replace a certain string or letter repeatedly in a request. The example shown here will replace A with B everywhere in a request, and will continue doing so until there are no more As to be replaced. ``` RewriteRule "(.*)A(.*)" "$1B$2" [N] ``` You can think of this as a `while` loop: While this pattern still matches (i.e., while the URI still contains an `A`), perform this substitution (i.e., replace the `A` with a `B`). In 2.4.8 and later, this module returns an error after 32,000 iterations to protect against unintended looping. An alternative maximum number of iterations can be specified by adding to the N flag. ``` # Be willing to replace 1 character in each pass of the loop RewriteRule "(.+)[><;]$" "$1" [N=64000] # ... or, give up if after 10 loops RewriteRule "(.+)[><;]$" "$1" [N=10] ``` NC|nocase --------- Use of the [NC] flag causes the `[RewriteRule](../mod/mod_rewrite#rewriterule)` to be matched in a case-insensitive manner. That is, it doesn't care whether letters appear as upper-case or lower-case in the matched URI. In the example below, any request for an image file will be proxied to your dedicated image server. The match is case-insensitive, so that `.jpg` and `.JPG` files are both acceptable, for example. ``` RewriteRule "(.*\.(jpg|gif|png))$" "http://images.example.com$1" [P,NC] ``` NE|noescape ----------- By default, special characters, such as `&` and `?`, for example, will be converted to their hexcode equivalent. Using the [NE] flag prevents that from happening. ``` RewriteRule "^/anchor/(.+)" "/bigpage.html#$1" [NE,R] ``` The above example will redirect `/anchor/xyz` to `/bigpage.html#xyz`. Omitting the [NE] will result in the # being converted to its hexcode equivalent, `%23`, which will then result in a 404 Not Found error condition. NS|nosubreq ----------- Use of the [NS] flag prevents the rule from being used on subrequests. For example, a page which is included using an SSI (Server Side Include) is a subrequest, and you may want to avoid rewrites happening on those subrequests. Also, when `[mod\_dir](../mod/mod_dir)` tries to find out information about possible directory default files (such as `index.html` files), this is an internal subrequest, and you often want to avoid rewrites on such subrequests. On subrequests, it is not always useful, and can even cause errors, if the complete set of rules are applied. Use this flag to exclude problematic rules. To decide whether or not to use this rule: if you prefix URLs with CGI-scripts, to force them to be processed by the CGI-script, it's likely that you will run into problems (or significant overhead) on sub-requests. In these cases, use this flag. Images, javascript files, or css files, loaded as part of an HTML page, are not subrequests - the browser requests them as separate HTTP requests. P|proxy ------- Use of the [P] flag causes the request to be handled by `[mod\_proxy](../mod/mod_proxy)`, and handled via a proxy request. For example, if you wanted all image requests to be handled by a back-end image server, you might do something like the following: ``` RewriteRule "/(.*)\.(jpg|gif|png)$" "http://images.example.com/$1.$2" [P] ``` Use of the [P] flag implies [L] - that is, the request is immediately pushed through the proxy, and any following rules will not be considered. You must make sure that the substitution string is a valid URI (typically starting with `http://`*hostname*) which can be handled by the `[mod\_proxy](../mod/mod_proxy)`. If not, you will get an error from the proxy module. Use this flag to achieve a more powerful implementation of the `[ProxyPass](../mod/mod_proxy#proxypass)` directive, to map remote content into the namespace of the local server. **Security Warning** Take care when constructing the target URL of the rule, considering the security impact from allowing the client influence over the set of URLs to which your server will act as a proxy. Ensure that the scheme and hostname part of the URL is either fixed, or does not allow the client undue influence. **Performance warning** Using this flag triggers the use of `[mod\_proxy](../mod/mod_proxy)`, without handling of persistent connections. This means the performance of your proxy will be better if you set it up with `[ProxyPass](../mod/mod_proxy#proxypass)` or `[ProxyPassMatch](../mod/mod_proxy#proxypassmatch)` This is because this flag triggers the use of the default worker, which does not handle connection pooling/reuse. Avoid using this flag and prefer those directives, whenever you can. Note: `[mod\_proxy](../mod/mod_proxy)` must be enabled in order to use this flag. PT|passthrough -------------- The target (or substitution string) in a RewriteRule is assumed to be a file path, by default. The use of the [PT] flag causes it to be treated as a URI instead. That is to say, the use of the [PT] flag causes the result of the `[RewriteRule](../mod/mod_rewrite#rewriterule)` to be passed back through URL mapping, so that location-based mappings, such as `[Alias](../mod/mod_alias#alias)`, `[Redirect](../mod/mod_alias#redirect)`, or `[ScriptAlias](../mod/mod_alias#scriptalias)`, for example, might have a chance to take effect. If, for example, you have an `[Alias](../mod/mod_alias#alias)` for /icons, and have a `[RewriteRule](../mod/mod_rewrite#rewriterule)` pointing there, you should use the [PT] flag to ensure that the `[Alias](../mod/mod_alias#alias)` is evaluated. ``` Alias "/icons" "/usr/local/apache/icons" RewriteRule "/pics/(.+)\.jpg$" "/icons/$1.gif" [PT] ``` Omission of the [PT] flag in this case will cause the Alias to be ignored, resulting in a 'File not found' error being returned. The `PT` flag implies the `L` flag: rewriting will be stopped in order to pass the request to the next phase of processing. Note that the `PT` flag is implied in per-directory contexts such as `[<Directory>](../mod/core#directory)` sections or in `.htaccess` files. The only way to circumvent that is to rewrite to `-`. QSA|qsappend ------------ When the replacement URI contains a query string, the default behavior of `[RewriteRule](../mod/mod_rewrite#rewriterule)` is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined. Consider the following rule: ``` RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA] ``` With the [QSA] flag, a request for `/pages/123?one=two` will be mapped to `/page.php?page=123&one=two`. Without the [QSA] flag, that same request will be mapped to `/page.php?page=123` - that is, the existing query string will be discarded. QSD|qsdiscard ------------- When the requested URI contains a query string, and the target URI does not, the default behavior of `[RewriteRule](../mod/mod_rewrite#rewriterule)` is to copy that query string to the target URI. Using the [QSD] flag causes the query string to be discarded. This flag is available in version 2.4.0 and later. Using [QSD] and [QSA] together will result in [QSD] taking precedence. If the target URI has a query string, the default behavior will be observed - that is, the original query string will be discarded and replaced with the query string in the `RewriteRule` target URI. QSL|qslast ---------- By default, the first (left-most) question mark in the substitution delimits the path from the query string. Using the [QSL] flag instructs `[RewriteRule](../mod/mod_rewrite#rewriterule)` to instead split the two components using the last (right-most) question mark. This is useful when mapping to files that have literal question marks in their filename. If no query string is used in the substitution, a question mark can be appended to it in combination with this flag. This flag is available in version 2.4.19 and later. R|redirect ---------- Use of the [R] flag causes a HTTP redirect to be issued to the browser. If a fully-qualified URL is specified (that is, including `http://servername/`) then a redirect will be issued to that location. Otherwise, the current protocol, servername, and port number will be used to generate the URL sent with the redirect. *Any* valid HTTP response status code may be specified, using the syntax [R=305], with a 302 status code being used by default if none is specified. The status code specified need not necessarily be a redirect (3xx) status code. However, if a status code is outside the redirect range (300-399) then the substitution string is dropped entirely, and rewriting is stopped as if the `L` were used. In addition to response status codes, you may also specify redirect status using their symbolic names: `temp` (default), `permanent`, or `seeother`. You will almost always want to use [R] in conjunction with [L] (that is, use [R,L]) because on its own, the [R] flag prepends `http://thishost[:thisport]` to the URI, but then passes this on to the next rule in the ruleset, which can often result in 'Invalid URI in request' warnings. S|skip ------ The [S] flag is used to skip rules that you don't want to run. The syntax of the skip flag is [S=*N*], where *N* signifies the number of rules to skip (provided the `[RewriteRule](../mod/mod_rewrite#rewriterule)` matches). This can be thought of as a `goto` statement in your rewrite ruleset. In the following example, we only want to run the `[RewriteRule](../mod/mod_rewrite#rewriterule)` if the requested URI doesn't correspond with an actual file. ``` # Is the request for a non-existent file? RewriteCond "%{REQUEST_FILENAME}" "!-f" RewriteCond "%{REQUEST_FILENAME}" "!-d" # If so, skip these two RewriteRules RewriteRule ".?" "-" [S=2] RewriteRule "(.*\.gif)" "images.php?$1" RewriteRule "(.*\.html)" "docs.php?$1" ``` This technique is useful because a `[RewriteCond](../mod/mod_rewrite#rewritecond)` only applies to the `[RewriteRule](../mod/mod_rewrite#rewriterule)` immediately following it. Thus, if you want to make a `RewriteCond` apply to several `RewriteRule`s, one possible technique is to negate those conditions and add a `RewriteRule` with a [Skip] flag. You can use this to make pseudo if-then-else constructs: The last rule of the then-clause becomes `skip=N`, where N is the number of rules in the else-clause: ``` # Does the file exist? RewriteCond "%{REQUEST_FILENAME}" "!-f" RewriteCond "%{REQUEST_FILENAME}" "!-d" # Create an if-then-else construct by skipping 3 lines if we meant to go to the "else" stanza. RewriteRule ".?" "-" [S=3] # IF the file exists, then: RewriteRule "(.*\.gif)" "images.php?$1" RewriteRule "(.*\.html)" "docs.php?$1" # Skip past the "else" stanza. RewriteRule ".?" "-" [S=1] # ELSE... RewriteRule "(.*)" "404.php?file=$1" # END ``` It is probably easier to accomplish this kind of configuration using the `<If>`, `<ElseIf>`, and `<Else>` directives instead. T|type ------ Sets the MIME type with which the resulting response will be sent. This has the same effect as the `[AddType](../mod/mod_mime#addtype)` directive. For example, you might use the following technique to serve Perl source code as plain text, if requested in a particular way: ``` # Serve .pl files as plain text RewriteRule "\.pl$" "-" [T=text/plain] ``` Or, perhaps, if you have a camera that produces jpeg images without file extensions, you could force those images to be served with the correct MIME type by virtue of their file names: ``` # Files with 'IMG' in the name are jpg images. RewriteRule "IMG" "-" [T=image/jpg] ``` Please note that this is a trivial example, and could be better done using `[<FilesMatch>](../mod/core#filesmatch)` instead. Always consider the alternate solutions to a problem before resorting to rewrite, which will invariably be a less efficient solution than the alternatives. If used in per-directory context, use only `-` (dash) as the substitution *for the entire round of mod\_rewrite processing*, otherwise the MIME-type set with this flag is lost due to an internal re-processing (including subsequent rounds of mod\_rewrite processing). The `L` flag can be useful in this context to end the *current* round of mod\_rewrite processing.
programming_docs
apache_http_server Using RewriteMap Using RewriteMap ================ This document supplements the `[mod\_rewrite](../mod/mod_rewrite)` [reference documentation](../mod/mod_rewrite). It describes the use of the `[RewriteMap](../mod/mod_rewrite#rewritemap)` directive, and provides examples of each of the various `[RewriteMap](../mod/mod_rewrite#rewritemap)` types. Note that many of these examples won't work unchanged in your particular server configuration, so it's important that you understand them, rather than merely cutting and pasting the examples into your configuration. Introduction ------------ The `[RewriteMap](../mod/mod_rewrite#rewritemap)` directive defines an external function which can be called in the context of `[RewriteRule](../mod/mod_rewrite#rewriterule)` or `[RewriteCond](../mod/mod_rewrite#rewritecond)` directives to perform rewriting that is too complicated, or too specialized to be performed just by regular expressions. The source of this lookup can be any of the types listed in the sections below, and enumerated in the `[RewriteMap](../mod/mod_rewrite#rewritemap)` reference documentation. The syntax of the `[RewriteMap](../mod/mod_rewrite#rewritemap)` directive is as follows: ``` RewriteMap *MapName* *MapType*:*MapSource* ``` The *MapName* is an arbitrary name that you assign to the map, and which you will use in directives later on. Arguments are passed to the map via the following syntax: **`${` *MapName* `:` *LookupKey* `}` `${` *MapName* `:` *LookupKey* `|` *DefaultValue* `}`** When such a construct occurs, the map *MapName* is consulted and the key *LookupKey* is looked-up. If the key is found, the map-function construct is substituted by *SubstValue*. If the key is not found then it is substituted by *DefaultValue* or by the empty string if no *DefaultValue* was specified. For example, you can define a `[RewriteMap](../mod/mod_rewrite#rewritemap)` as: ``` RewriteMap examplemap "txt:/path/to/file/map.txt" ``` You would then be able to use this map in a `[RewriteRule](../mod/mod_rewrite#rewriterule)` as follows: ``` RewriteRule "^/ex/(.*)" "${examplemap:$1}" ``` A default value can be specified in the event that nothing is found in the map: ``` RewriteRule "^/ex/(.*)" "${examplemap:$1|/not_found.html}" ``` **Per-directory and .htaccess context** The `[RewriteMap](../mod/mod_rewrite#rewritemap)` directive may not be used in `[<Directory>](../mod/core#directory)` sections or `.htaccess` files. You must declare the map in server or virtualhost context. You may use the map, once created, in your `[RewriteRule](../mod/mod_rewrite#rewriterule)` and `[RewriteCond](../mod/mod_rewrite#rewritecond)` directives in those scopes. You just can't **declare** it in those scopes. The sections that follow describe the various *MapType*s that may be used, and give examples of each. int: Internal Function ---------------------- When a MapType of `int` is used, the MapSource is one of the available internal `[RewriteMap](../mod/mod_rewrite#rewritemap)` functions. Module authors can provide additional internal functions by registering them with the `ap_register_rewrite_mapfunc` API. The functions that are provided by default are: * **toupper**: Converts the key to all upper case. * **tolower**: Converts the key to all lower case. * **escape**: Translates special characters in the key to hex-encodings. * **unescape**: Translates hex-encodings in the key back to special characters. To use one of these functions, create a `[RewriteMap](../mod/mod_rewrite#rewritemap)` referencing the int function, and then use that in your `[RewriteRule](../mod/mod_rewrite#rewriterule)`: **Redirect a URI to an all-lowercase version of itself** ``` RewriteMap lc int:tolower RewriteRule "(.*)" "${lc:$1}" [R] ``` Please note that the example offered here is for illustration purposes only, and is not a recommendation. If you want to make URLs case-insensitive, consider using `[mod\_speling](../mod/mod_speling)` instead. txt: Plain text maps -------------------- When a MapType of `txt` is used, the MapSource is a filesystem path to a plain-text mapping file, containing one space-separated key/value pair per line. Optionally, a line may contain a comment, starting with a '#' character. A valid text rewrite map file will have the following syntax: ``` # Comment line MatchingKey SubstValue MatchingKey SubstValue # comment ``` When the `[RewriteMap](../mod/mod_rewrite#rewritemap)` is invoked the argument is looked for in the first argument of a line, and, if found, the substitution value is returned. For example, we can use a mapfile to translate product names to product IDs for easier-to-remember URLs, using the following recipe: **Product to ID configuration** ``` RewriteMap product2id "txt:/etc/apache2/productmap.txt" RewriteRule "^/product/(.*)" "/prods.php?id=${product2id:$1|NOTFOUND}" [PT] ``` We assume here that the `prods.php` script knows what to do when it received an argument of `id=NOTFOUND` when a product is not found in the lookup map. The file `/etc/apache2/productmap.txt` then contains the following: ### Product to ID map ``` ## ## productmap.txt - Product to ID map file ## television 993 stereo 198 fishingrod 043 basketball 418 telephone 328 ``` Thus, when `http://example.com/product/television` is requested, the `[RewriteRule](../mod/mod_rewrite#rewriterule)` is applied, and the request is internally mapped to `/prods.php?id=993`. **Note: .htaccess files** The example given is crafted to be used in server or virtualhost scope. If you're planning to use this in a `.htaccess` file, you'll need to remove the leading slash from the rewrite pattern in order for it to match anything: ``` RewriteRule "^product/(.*)" "/prods.php?id=${product2id:$1|NOTFOUND}" [PT] ``` **Cached lookups** The looked-up keys are cached by httpd until the `mtime` (modified time) of the mapfile changes, or the httpd server is restarted. This ensures better performance on maps that are called by many requests. rnd: Randomized Plain Text -------------------------- When a MapType of `rnd` is used, the MapSource is a filesystem path to a plain-text mapping file, each line of which contains a key, and one or more values separated by `|`. One of these values will be chosen at random if the key is matched. For example, you can use the following map file and directives to provide a random load balancing between several back-end servers, via a reverse-proxy. Images are sent to one of the servers in the 'static' pool, while everything else is sent to one of the 'dynamic' pool. ### Rewrite map file ``` ## ## map.txt -- rewriting map ## static www1|www2|www3|www4 dynamic www5|www6 ``` **Configuration directives** ``` RewriteMap servers "rnd:/path/to/file/map.txt" RewriteRule "^/(.*\.(png|gif|jpg))" "http://${servers:static}/$1" [NC,P,L] RewriteRule "^/(.*)" "http://${servers:dynamic}/$1" [P,L] ``` So, when an image is requested and the first of these rules is matched, `[RewriteMap](../mod/mod_rewrite#rewritemap)` looks up the string `static` in the map file, which returns one of the specified hostnames at random, which is then used in the `[RewriteRule](../mod/mod_rewrite#rewriterule)` target. If you wanted to have one of the servers more likely to be chosen (for example, if one of the server has more memory than the others, and so can handle more requests) simply list it more times in the map file. ``` static www1|www1|www2|www3|www4 ``` dbm: DBM Hash File ------------------ When a MapType of `dbm` is used, the MapSource is a filesystem path to a DBM database file containing key/value pairs to be used in the mapping. This works exactly the same way as the `txt` map, but is much faster, because a DBM is indexed, whereas a text file is not. This allows more rapid access to the desired key. You may optionally specify a particular dbm type: ``` RewriteMap examplemap "dbm=sdbm:/etc/apache/mapfile.dbm" ``` The type can be `sdbm`, `gdbm`, `ndbm` or `db`. However, it is recommended that you just use the [httxt2dbm](../programs/httxt2dbm) utility that is provided with Apache HTTP Server, as it will use the correct DBM library, matching the one that was used when httpd itself was built. To create a dbm file, first create a text map file as described in the [txt](#txt) section. Then run `httxt2dbm`: ``` $ httxt2dbm -i mapfile.txt -o mapfile.map ``` You can then reference the resulting file in your `[RewriteMap](../mod/mod_rewrite#rewritemap)` directive: ``` RewriteMap mapname "dbm:/etc/apache/mapfile.map" ``` Note that with some dbm types, more than one file is generated, with a common base name. For example, you may have two files named `mapfile.map.dir` and `mapfile.map.pag`. This is normal, and you need only use the base name `mapfile.map` in your `[RewriteMap](../mod/mod_rewrite#rewritemap)` directive. **Cached lookups** The looked-up keys are cached by httpd until the `mtime` (modified time) of the mapfile changes, or the httpd server is restarted. This ensures better performance on maps that are called by many requests. prg: External Rewriting Program ------------------------------- When a MapType of `prg` is used, the MapSource is a filesystem path to an executable program which will providing the mapping behavior. This can be a compiled binary file, or a program in an interpreted language such as Perl or Python. This program is started once, when the Apache HTTP Server is started, and then communicates with the rewriting engine via `STDIN` and `STDOUT`. That is, for each map function lookup, it expects one argument via `STDIN`, and should return one new-line terminated response string on `STDOUT`. If there is no corresponding lookup value, the map program should return the four-character string "`NULL`" to indicate this. External rewriting programs are not started if they're defined in a context that does not have `[RewriteEngine](../mod/mod_rewrite#rewriteengine)` set to `on`. By default, external rewriting programs are run as the user:group who started httpd. This can be changed on UNIX systems by passing user name and group name as third argument to `[RewriteMap](../mod/mod_rewrite#rewritemap)` in the `username:groupname` format. This feature utilizes the `rewrite-map` mutex, which is required for reliable communication with the program. The mutex mechanism and lock file can be configured with the `[Mutex](../mod/core#mutex)` directive. A simple example is shown here which will replace all dashes with underscores in a request URI. **Rewrite configuration** ``` RewriteMap d2u "prg:/www/bin/dash2under.pl" apache:apache RewriteRule "-" "${d2u:%{REQUEST_URI}}" ``` **dash2under.pl** ``` #!/usr/bin/perl $| = 1; # Turn off I/O buffering while (<STDIN>) { s/-/_/g; # Replace dashes with underscores print $_; } ``` **Caution!** * Keep your rewrite map program as simple as possible. If the program hangs, it will cause httpd to wait indefinitely for a response from the map, which will, in turn, cause httpd to stop responding to requests. * Be sure to turn off buffering in your program. In Perl this is done by the second line in the example script: `$| = 1;` This will of course vary in other languages. Buffered I/O will cause httpd to wait for the output, and so it will hang. * Remember that there is only one copy of the program, started at server startup. All requests will need to go through this one bottleneck. This can cause significant slowdowns if many requests must go through this process, or if the script itself is very slow. dbd or fastdbd: SQL Query ------------------------- When a MapType of `dbd` or `fastdbd` is used, the MapSource is a SQL SELECT statement that takes a single argument and returns a single value. `[mod\_dbd](../mod/mod_dbd)` will need to be configured to point at the right database for this statement to be executed. There are two forms of this MapType. Using a MapType of `dbd` causes the query to be executed with each map request, while using `fastdbd` caches the database lookups internally. So, while `fastdbd` is more efficient, and therefore faster, it won't pick up on changes to the database until the server is restarted. If a query returns more than one row, a random row from the result set is used. ### Example ``` RewriteMap myquery "fastdbd:SELECT destination FROM rewrite WHERE source = %s" ``` **Note** The query name is passed to the database driver as a label for an SQL prepared statement, and will therefore need to follow any rules (such as case-sensitivity) required for your database. Summary ------- The `[RewriteMap](../mod/mod_rewrite#rewritemap)` directive can occur more than once. For each mapping-function use one `[RewriteMap](../mod/mod_rewrite#rewritemap)` directive to declare its rewriting mapfile. While you cannot **declare** a map in per-directory context (`.htaccess` files or `[<Directory>](../mod/core#directory)` blocks) it is possible to **use** this map in per-directory context. apache_http_server Apache mod_rewrite Apache mod\_rewrite =================== `[mod\_rewrite](../mod/mod_rewrite)` provides a way to modify incoming URL requests, dynamically, based on [regular expression](intro#regex) rules. This allows you to map arbitrary URLs onto your internal URL structure in any way you like. It supports an unlimited number of rules and an unlimited number of attached rule conditions for each rule to provide a really flexible and powerful URL manipulation mechanism. The URL manipulations can depend on various tests: server variables, environment variables, HTTP headers, time stamps, external database lookups, and various other external programs or handlers, can be used to achieve granular URL matching. Rewrite rules can operate on the full URLs, including the path-info and query string portions, and may be used in per-server context (`httpd.conf`), per-virtualhost context (`[<VirtualHost>](../mod/core#virtualhost)` blocks), or per-directory context (`.htaccess` files and `[<Directory>](../mod/core#directory)` blocks). The rewritten result can lead to further rules, internal sub-processing, external request redirection, or proxy passthrough, depending on what <flags> you attach to the rules. Since mod\_rewrite is so powerful, it can indeed be rather complex. This document supplements the [reference documentation](../mod/mod_rewrite), and attempts to allay some of that complexity, and provide highly annotated examples of common scenarios that you may handle with mod\_rewrite. But we also attempt to show you when you should not use mod\_rewrite, and use other standard Apache features instead, thus avoiding this unnecessary complexity. * [mod\_rewrite reference documentation](../mod/mod_rewrite) * [Introduction to regular expressions and mod\_rewrite](intro) * [Using mod\_rewrite for redirection and remapping of URLs](remapping) * [Using mod\_rewrite to control access](access) * [Dynamic virtual hosts with mod\_rewrite](vhosts) * [Dynamic proxying with mod\_rewrite](proxy) * [Using RewriteMap](rewritemap) * [Advanced techniques](advanced) * [When **NOT** to use mod\_rewrite](avoid) * [RewriteRule Flags](flags) * [Technical details](tech) apache_http_server Using mod_rewrite to control access Using mod\_rewrite to control access ==================================== This document supplements the `[mod\_rewrite](../mod/mod_rewrite)` [reference documentation](../mod/mod_rewrite). It describes how you can use `[mod\_rewrite](../mod/mod_rewrite)` to control access to various resources, and other related techniques. This includes many examples of common uses of mod\_rewrite, including detailed descriptions of how each works. Note that many of these examples won't work unchanged in your particular server configuration, so it's important that you understand them, rather than merely cutting and pasting the examples into your configuration. Forbidding Image "Hotlinking" ----------------------------- Description: The following technique forbids the practice of other sites including your images inline in their pages. This practice is often referred to as "hotlinking", and results in your bandwidth being used to serve content for someone else's site. Solution: This technique relies on the value of the `HTTP_REFERER` variable, which is optional. As such, it's possible for some people to circumvent this limitation. However, most users will experience the failed request, which should, over time, result in the image being removed from that other site. There are several ways that you can handle this situation. In this first example, we simply deny the request, if it didn't initiate from a page on our site. For the purpose of this example, we assume that our site is `www.example.com`. ``` RewriteCond "%{HTTP_REFERER}" "!^$" RewriteCond "%{HTTP_REFERER}" "!www.example.com" [NC] RewriteRule "\.(gif|jpg|png)$" "-" [F,NC] ``` In this second example, instead of failing the request, we display an alternate image instead. ``` RewriteCond "%{HTTP_REFERER}" "!^$" RewriteCond "%{HTTP_REFERER}" "!www.example.com" [NC] RewriteRule "\.(gif|jpg|png)$" "/images/go-away.png" [R,NC] ``` In the third example, we redirect the request to an image on some other site. ``` RewriteCond "%{HTTP_REFERER}" "!^$" RewriteCond "%{HTTP_REFERER}" "!www.example.com" [NC] RewriteRule "\.(gif|jpg|png)$" "http://other.example.com/image.gif" [R,NC] ``` Of these techniques, the last two tend to be the most effective in getting people to stop hotlinking your images, because they will simply not see the image that they expected to see. Discussion: If all you wish to do is deny access to the resource, rather than redirecting that request elsewhere, this can be accomplished without the use of mod\_rewrite: ``` SetEnvIf Referer "example\.com" localreferer <FilesMatch "\.(jpg|png|gif)$"> Require env localreferer </FilesMatch> ``` Blocking of Robots ------------------ Description: In this recipe, we discuss how to block persistent requests from a particular robot, or user agent. The standard for robot exclusion defines a file, `/robots.txt` that specifies those portions of your website where you wish to exclude robots. However, some robots do not honor these files. Note that there are methods of accomplishing this which do not use mod\_rewrite. Note also that any technique that relies on the clients `USER_AGENT` string can be circumvented very easily, since that string can be changed. Solution: We use a ruleset that specifies the directory to be protected, and the client `USER_AGENT` that identifies the malicious or persistent robot. In this example, we are blocking a robot called `NameOfBadRobot` from a location `/secret/files`. You may also specify an IP address range, if you are trying to block that user agent only from the particular source. ``` RewriteCond "%{HTTP_USER_AGENT}" "^NameOfBadRobot" RewriteCond "%{REMOTE_ADDR}" "=123\.45\.67\.[8-9]" RewriteRule "^/secret/files/" "-" [F] ``` Discussion: Rather than using mod\_rewrite for this, you can accomplish the same end using alternate means, as illustrated here: ``` SetEnvIfNoCase User-Agent "^NameOfBadRobot" goaway <Location "/secret/files"> <RequireAll> Require all granted Require not env goaway </RequireAll> </Location> ``` As noted above, this technique is trivial to circumvent, by simply modifying the `USER_AGENT` request header. If you are experiencing a sustained attack, you should consider blocking it at a higher level, such as at your firewall. Denying Hosts in a Reject List ------------------------------ Description: We wish to maintain a list of hosts, rather like `hosts.deny`, and have those hosts blocked from accessing our server. Solution: ``` RewriteEngine on RewriteMap hosts-deny "txt:/path/to/hosts.deny" RewriteCond "${hosts-deny:%{REMOTE_ADDR}|NOT-FOUND}" "!=NOT-FOUND" [OR] RewriteCond "${hosts-deny:%{REMOTE_HOST}|NOT-FOUND}" "!=NOT-FOUND" RewriteRule "^" "-" [F] ``` ``` ## ## hosts.deny ## ## ATTENTION! This is a map, not a list, even when we treat it as such. ## mod_rewrite parses it for key/value pairs, so at least a ## dummy value "-" must be present for each entry. ## 193.102.180.41 - bsdti1.sdm.de - 192.76.162.40 - ``` Discussion: The second RewriteCond assumes that you have HostNameLookups turned on, so that client IP addresses will be resolved. If that's not the case, you should drop the second RewriteCond, and drop the `[OR]` flag from the first RewriteCond. Referer-based Deflector ----------------------- Description: Redirect requests based on the Referer from which the request came, with different targets per Referer. Solution: The following ruleset uses a map file to associate each Referer with a redirection target. ``` RewriteMap deflector "txt:/path/to/deflector.map" RewriteCond "%{HTTP_REFERER}" !="" RewriteCond "${deflector:%{HTTP_REFERER}}" "=-" RewriteRule "^" "%{HTTP_REFERER}" [R,L] RewriteCond "%{HTTP_REFERER}" !="" RewriteCond "${deflector:%{HTTP_REFERER}|NOT-FOUND}" "!=NOT-FOUND" RewriteRule "^" "${deflector:%{HTTP_REFERER}}" [R,L] ``` The map file lists redirection targets for each referer, or, if we just wish to redirect back to where they came from, a "-" is placed in the map: ``` ## ## deflector.map ## http://badguys.example.com/bad/index.html - http://badguys.example.com/bad/index2.html - http://badguys.example.com/bad/index3.html http://somewhere.example.com/ ```
programming_docs
apache_http_server Dynamic mass virtual hosts with mod_rewrite Dynamic mass virtual hosts with mod\_rewrite ============================================ This document supplements the `[mod\_rewrite](../mod/mod_rewrite)` [reference documentation](../mod/mod_rewrite). It describes how you can use `[mod\_rewrite](../mod/mod_rewrite)` to create dynamically configured virtual hosts. mod\_rewrite is not the best way to configure virtual hosts. You should first consider the [alternatives](../vhosts/mass) before resorting to mod\_rewrite. See also the "[how to avoid mod\_rewrite](avoid#vhosts) document. Virtual Hosts For Arbitrary Hostnames ------------------------------------- Description: We want to automatically create a virtual host for every hostname which resolves in our domain, without having to create new VirtualHost sections. In this recipe, we assume that we'll be using the hostname `www.SITE.example.com` for each user, and serve their content out of `/home/SITE/www`. Solution: ``` RewriteEngine on RewriteMap lowercase int:tolower RewriteCond "${lowercase:%{**HTTP\_HOST**}}" "^www\.**([^.]+)**\.example\.com$" RewriteRule "^(.*)" "/home/**%1**/www$1" ``` Discussion You will need to take care of the DNS resolution - Apache does not handle name resolution. You'll need either to create CNAME records for each hostname, or a DNS wildcard record. Creating DNS records is beyond the scope of this document. The internal `tolower` RewriteMap directive is used to ensure that the hostnames being used are all lowercase, so that there is no ambiguity in the directory structure which must be created. Parentheses used in a `[RewriteCond](../mod/mod_rewrite#rewritecond)` are captured into the backreferences `%1`, `%2`, etc, while parentheses used in `[RewriteRule](../mod/mod_rewrite#rewriterule)` are captured into the backreferences `$1`, `$2`, etc. As with many techniques discussed in this document, mod\_rewrite really isn't the best way to accomplish this task. You should, instead, consider using `[mod\_vhost\_alias](../mod/mod_vhost_alias)` instead, as it will much more gracefully handle anything beyond serving static files, such as any dynamic content, and Alias resolution. Dynamic Virtual Hosts Using `[mod\_rewrite](../mod/mod_rewrite)` ---------------------------------------------------------------- This extract from `httpd.conf` does the same thing as [the first example](#per-hostname). The first half is very similar to the corresponding part above, except for some changes, required for backward compatibility and to make the `mod_rewrite` part work properly; the second half configures `mod_rewrite` to do the actual work. Because `mod_rewrite` runs before other URI translation modules (e.g., `mod_alias`), `mod_rewrite` must be told to explicitly ignore any URLs that would have been handled by those modules. And, because these rules would otherwise bypass any `ScriptAlias` directives, we must have `mod_rewrite` explicitly enact those mappings. ``` # get the server name from the Host: header UseCanonicalName Off # splittable logs LogFormat "%{Host}i %h %l %u %t \"%r\" %s %b" vcommon CustomLog "logs/access_log" vcommon <Directory "/www/hosts"> # ExecCGI is needed here because we can't force # CGI execution in the way that ScriptAlias does Options FollowSymLinks ExecCGI </Directory> RewriteEngine On # a ServerName derived from a Host: header may be any case at all RewriteMap lowercase int:tolower ## deal with normal documents first: # allow Alias "/icons/" to work - repeat for other aliases RewriteCond "%{REQUEST_URI}" "!^/icons/" # allow CGIs to work RewriteCond "%{REQUEST_URI}" "!^/cgi-bin/" # do the magic RewriteRule "^/(.*)$" "/www/hosts/${lowercase:%{SERVER_NAME}}/docs/$1" ## and now deal with CGIs - we have to force a handler RewriteCond "%{REQUEST_URI}" "^/cgi-bin/" RewriteRule "^/(.*)$" "/www/hosts/${lowercase:%{SERVER_NAME}}/cgi-bin/$1" [H=cgi-script] ``` Using a Separate Virtual Host Configuration File ------------------------------------------------ This arrangement uses more advanced `[mod\_rewrite](../mod/mod_rewrite)` features to work out the translation from virtual host to document root, from a separate configuration file. This provides more flexibility, but requires more complicated configuration. The `vhost.map` file should look something like this: ``` customer-1.example.com /www/customers/1 customer-2.example.com /www/customers/2 # ... customer-N.example.com /www/customers/N ``` The `httpd.conf` should contain the following: ``` RewriteEngine on RewriteMap lowercase int:tolower # define the map file RewriteMap vhost "txt:/www/conf/vhost.map" # deal with aliases as above RewriteCond "%{REQUEST_URI}" "!^/icons/" RewriteCond "%{REQUEST_URI}" "!^/cgi-bin/" RewriteCond "${lowercase:%{SERVER_NAME}}" "^(.+)$" # this does the file-based remap RewriteCond "${vhost:%1}" "^(/.*)$" RewriteRule "^/(.*)$" "%1/docs/$1" RewriteCond "%{REQUEST_URI}" "^/cgi-bin/" RewriteCond "${lowercase:%{SERVER_NAME}}" "^(.+)$" RewriteCond "${vhost:%1}" "^(/.*)$" RewriteRule "^/cgi-bin/(.*)$" "%1/cgi-bin/$1" [H=cgi-script] ``` apache_http_server Apache mod_rewrite Introduction Apache mod\_rewrite Introduction ================================ This document supplements the `[mod\_rewrite](../mod/mod_rewrite)` [reference documentation](../mod/mod_rewrite). It describes the basic concepts necessary for use of `[mod\_rewrite](../mod/mod_rewrite)`. Other documents go into greater detail, but this doc should help the beginner get their feet wet. Introduction ------------ The Apache module `[mod\_rewrite](../mod/mod_rewrite)` is a very powerful and sophisticated module which provides a way to do URL manipulations. With it, you can do nearly all types of URL rewriting that you may need. It is, however, somewhat complex, and may be intimidating to the beginner. There is also a tendency to treat rewrite rules as magic incantation, using them without actually understanding what they do. This document attempts to give sufficient background so that what follows is understood, rather than just copied blindly. Remember that many common URL-manipulation tasks don't require the full power and complexity of `[mod\_rewrite](../mod/mod_rewrite)`. For simple tasks, see `[mod\_alias](../mod/mod_alias)` and the documentation on [mapping URLs to the filesystem](../urlmapping). Finally, before proceeding, be sure to configure `[mod\_rewrite](../mod/mod_rewrite)`'s log level to one of the trace levels using the `[LogLevel](../mod/core#loglevel)` directive. Although this can give an overwhelming amount of information, it is indispensable in debugging problems with `[mod\_rewrite](../mod/mod_rewrite)` configuration, since it will tell you exactly how each rule is processed. Regular Expressions ------------------- `[mod\_rewrite](../mod/mod_rewrite)` uses the [Perl Compatible Regular Expression](http://pcre.org/) vocabulary. In this document, we do not attempt to provide a detailed reference to regular expressions. For that, we recommend the [PCRE man pages](http://pcre.org/pcre.txt), the [Perl regular expression man page](http://perldoc.perl.org/perlre.html), and [Mastering Regular Expressions, by Jeffrey Friedl](http://shop.oreilly.com/product/9780596528126.do). In this document, we attempt to provide enough of a regex vocabulary to get you started, without being overwhelming, in the hope that `[RewriteRule](../mod/mod_rewrite#rewriterule)`s will be scientific formulae, rather than magical incantations. ### Regex vocabulary The following are the minimal building blocks you will need, in order to write regular expressions and `[RewriteRule](../mod/mod_rewrite#rewriterule)`s. They certainly do not represent a complete regular expression vocabulary, but they are a good place to start, and should help you read basic regular expressions, as well as write your own. | Character | Meaning | Example | | --- | --- | --- | | `.` | Matches any single character | `c.t` will match `cat`, `cot`, `cut`, etc | | `+` | Repeats the previous match one or more times | `a+` matches `a`, `aa`, `aaa`, etc | | `*` | Repeats the previous match zero or more times | `a*` matches all the same things `a+` matches, but will also match an empty string | | `?` | Makes the match optional | `colou?r` will match `color` and `colour` | | `\` | Escape the next character | `\.` will match `.` (dot) and not *any single character* as explain above | | `^` | Called an anchor, matches the beginning of the string | `^a` matches a string that begins with `a` | | `$` | The other anchor, this matches the end of the string | `a$` matches a string that ends with `a` | | ``` ( ) ``` | Groups several characters into a single unit, and captures a match for use in a backreference | `(ab)+` matches `ababab` - that is, the `+` applies to the group. For more on backreferences see [below](#InternalBackRefs) | | ``` [ ] ``` | A character class - matches one of the characters | `c[uoa]t` matches `cut`, `cot` or `cat` | | ``` [^ ] ``` | Negative character class - matches any character not specified | `c[^/]t` matches `cat` or `c=t` but not `c/t` | In `[mod\_rewrite](../mod/mod_rewrite)` the `!` character can be used before a regular expression to negate it. This is, a string will be considered to have matched only if it does not match the rest of the expression. ### Regex Back-Reference Availability One important thing here has to be remembered: Whenever you use parentheses in *Pattern* or in one of the *CondPattern*, back-references are internally created which can be used with the strings `$N` and `%N` (see below). These are available for creating the *Substitution* parameter of a `[RewriteRule](../mod/mod_rewrite#rewriterule)` or the *TestString* parameter of a `[RewriteCond](../mod/mod_rewrite#rewritecond)`. Captures in the `[RewriteRule](../mod/mod_rewrite#rewriterule)` patterns are (counterintuitively) available to all preceding `[RewriteCond](../mod/mod_rewrite#rewritecond)` directives, because the `[RewriteRule](../mod/mod_rewrite#rewriterule)` expression is evaluated before the individual conditions. Figure 1 shows to which locations the back-references are transferred for expansion as well as illustrating the flow of the RewriteRule, RewriteCond matching. In the next chapters, we will be exploring how to use these back-references, so do not fret if it seems a bit alien to you at first. Figure 1: The back-reference flow through a rule. In this example, a request for `/test/1234` would be transformed into `/admin.foo?page=test&id=1234&host=admin.example.com`. RewriteRule Basics ------------------ A `[RewriteRule](../mod/mod_rewrite#rewriterule)` consists of three arguments separated by spaces. The arguments are 1. Pattern: which incoming URLs should be affected by the rule; 2. Substitution: where should the matching requests be sent; 3. [flags]: options affecting the rewritten request. The Pattern is a [regular expression](#regex). It is initially (for the first rewrite rule or until a substitution occurs) matched against the URL-path of the incoming request (the part after the hostname but before any question mark indicating the beginning of a query string) or, in per-directory context, against the request's path relative to the directory for which the rule is defined. Once a substitution has occurred, the rules that follow are matched against the substituted value. Figure 2: Syntax of the RewriteRule directive. The Substitution can itself be one of three things: A full filesystem path to a resource ``` RewriteRule "^/games" "/usr/local/games/web" ``` This maps a request to an arbitrary location on your filesystem, much like the `[Alias](../mod/mod_alias#alias)` directive. A web-path to a resource ``` RewriteRule "^/foo$" "/bar" ``` If `[DocumentRoot](../mod/core#documentroot)` is set to `/usr/local/apache2/htdocs`, then this directive would map requests for `http://example.com/foo` to the path `/usr/local/apache2/htdocs/bar`. An absolute URL ``` RewriteRule "^/product/view$" "http://site2.example.com/seeproduct.html" [R] ``` This tells the client to make a new request for the specified URL. The Substitution can also contain *back-references* to parts of the incoming URL-path matched by the Pattern. Consider the following: ``` RewriteRule "^/product/(.*)/view$" "/var/web/productdb/$1" ``` The variable `$1` will be replaced with whatever text was matched by the expression inside the parenthesis in the Pattern. For example, a request for `http://example.com/product/r14df/view` will be mapped to the path `/var/web/productdb/r14df`. If there is more than one expression in parenthesis, they are available in order in the variables `$1`, `$2`, `$3`, and so on. Rewrite Flags ------------- The behavior of a `[RewriteRule](../mod/mod_rewrite#rewriterule)` can be modified by the application of one or more flags to the end of the rule. For example, the matching behavior of a rule can be made case-insensitive by the application of the `[NC]` flag: ``` RewriteRule "^puppy.html" "smalldog.html" [NC] ``` For more details on the available flags, their meanings, and examples, see the [Rewrite Flags](flags) document. Rewrite Conditions ------------------ One or more `[RewriteCond](../mod/mod_rewrite#rewritecond)` directives can be used to restrict the types of requests that will be subject to the following `[RewriteRule](../mod/mod_rewrite#rewriterule)`. The first argument is a variable describing a characteristic of the request, the second argument is a [regular expression](#regex) that must match the variable, and a third optional argument is a list of flags that modify how the match is evaluated. Figure 3: Syntax of the RewriteCond directive For example, to send all requests from a particular IP range to a different server, you could use: ``` RewriteCond "%{REMOTE_ADDR}" "^10\.2\." RewriteRule "(.*)" "http://intranet.example.com$1" ``` When more than one `[RewriteCond](../mod/mod_rewrite#rewritecond)` is specified, they must all match for the `[RewriteRule](../mod/mod_rewrite#rewriterule)` to be applied. For example, to deny requests that contain the word "hack" in their query string, unless they also contain a cookie containing the word "go", you could use: ``` RewriteCond "%{QUERY_STRING}" "hack" RewriteCond "%{HTTP_COOKIE}" !go RewriteRule "." "-" [F] ``` Notice that the exclamation mark specifies a negative match, so the rule is only applied if the cookie does not contain "go". Matches in the regular expressions contained in the `[RewriteCond](../mod/mod_rewrite#rewritecond)`s can be used as part of the Substitution in the `[RewriteRule](../mod/mod_rewrite#rewriterule)` using the variables `%1`, `%2`, etc. For example, this will direct the request to a different directory depending on the hostname used to access the site: ``` RewriteCond "%{HTTP_HOST}" "(.*)" RewriteRule "^/(.*)" "/sites/%1/$1" ``` If the request was for `http://example.com/foo/bar`, then `%1` would contain `example.com` and `$1` would contain `foo/bar`. Rewrite maps ------------ The `[RewriteMap](../mod/mod_rewrite#rewritemap)` directive provides a way to call an external function, so to speak, to do your rewriting for you. This is discussed in greater detail in the [RewriteMap supplementary documentation](rewritemap). .htaccess files --------------- Rewriting is typically configured in the main server configuration setting (outside any `[<Directory>](../mod/core#directory)` section) or inside `[<VirtualHost>](../mod/core#virtualhost)` containers. This is the easiest way to do rewriting and is recommended. It is possible, however, to do rewriting inside `[<Directory>](../mod/core#directory)` sections or [`.htaccess` files](../howto/htaccess) at the expense of some additional complexity. This technique is called per-directory rewrites. The main difference with per-server rewrites is that the path prefix of the directory containing the `.htaccess` file is stripped before matching in the `[RewriteRule](../mod/mod_rewrite#rewriterule)`. In addition, the `[RewriteBase](../mod/mod_rewrite#rewritebase)` should be used to assure the request is properly mapped. apache_http_server Advanced Techniques with mod_rewrite Advanced Techniques with mod\_rewrite ===================================== This document supplements the `[mod\_rewrite](../mod/mod_rewrite)` [reference documentation](../mod/mod_rewrite). It provides a few advanced techniques using mod\_rewrite. Note that many of these examples won't work unchanged in your particular server configuration, so it's important that you understand them, rather than merely cutting and pasting the examples into your configuration. URL-based sharding across multiple backends ------------------------------------------- Description: A common technique for distributing the burden of server load or storage space is called "sharding". When using this method, a front-end server will use the url to consistently "shard" users or objects to separate backend servers. Solution: A mapping is maintained, from users to target servers, in external map files. They look like: ``` user1 physical_host_of_user1 user2 physical_host_of_user2 : : ``` We put this into a `map.users-to-hosts` file. The aim is to map; `/u/user1/anypath` to `http://physical_host_of_user1/u/user/anypath` thus every URL path need not be valid on every backend physical host. The following ruleset does this for us with the help of the map files assuming that server0 is a default server which will be used if a user has no entry in the map: ``` RewriteEngine on RewriteMap users-to-hosts "txt:/path/to/map.users-to-hosts" RewriteRule "^/u/([^/]+)/?(.*)" "http://${users-to-hosts:$1|server0}/u/$1/$2" ``` See the `[RewriteMap](../mod/mod_rewrite#rewritemap)` documentation for more discussion of the syntax of this directive. On-the-fly Content-Regeneration ------------------------------- Description: We wish to dynamically generate content, but store it statically once it is generated. This rule will check for the existence of the static file, and if it's not there, generate it. The static files can be removed periodically, if desired (say, via cron) and will be regenerated on demand. Solution: This is done via the following ruleset: ``` # This example is valid in per-directory context only RewriteCond "%{REQUEST_URI}" "!-U" RewriteRule "^(.+)\.html$" "/regenerate_page.cgi" [PT,L] ``` The `-U` operator determines whether the test string (in this case, `REQUEST_URI`) is a valid URL. It does this via a subrequest. In the event that this subrequest fails - that is, the requested resource doesn't exist - this rule invokes the CGI program `/regenerate_page.cgi`, which generates the requested resource and saves it into the document directory, so that the next time it is requested, a static copy can be served. In this way, documents that are infrequently updated can be served in static form. if documents need to be refreshed, they can be deleted from the document directory, and they will then be regenerated the next time they are requested. Load Balancing -------------- Description: We wish to randomly distribute load across several servers using mod\_rewrite. Solution: We'll use `[RewriteMap](../mod/mod_rewrite#rewritemap)` and a list of servers to accomplish this. ``` RewriteEngine on RewriteMap lb "rnd:/path/to/serverlist.txt" RewriteRule "^/(.*)" "http://${lb:servers}/$1" [P,L] ``` `serverlist.txt` will contain a list of the servers: ``` ## serverlist.txt servers one.example.com|two.example.com|three.example.com ``` If you want one particular server to get more of the load than the others, add it more times to the list. Discussion Apache comes with a load-balancing module - `[mod\_proxy\_balancer](../mod/mod_proxy_balancer)` - which is far more flexible and featureful than anything you can cobble together using mod\_rewrite. Structured Userdirs ------------------- Description: Some sites with thousands of users use a structured homedir layout, *i.e.* each homedir is in a subdirectory which begins (for instance) with the first character of the username. So, `/~larry/anypath` is `/home/l/larry/public_html/anypath` while `/~waldo/anypath` is `/home/w/waldo/public_html/anypath`. Solution: We use the following ruleset to expand the tilde URLs into the above layout. ``` RewriteEngine on RewriteRule "^/~(**([a-z])**[a-z0-9]+)(.*)" "/home/**$2**/$1/public_html$3" ``` Redirecting Anchors ------------------- Description: By default, redirecting to an HTML anchor doesn't work, because mod\_rewrite escapes the `#` character, turning it into `%23`. This, in turn, breaks the redirection. Solution: Use the `[NE]` flag on the `RewriteRule`. NE stands for No Escape. Discussion: This technique will of course also work with other special characters that mod\_rewrite, by default, URL-encodes. Time-Dependent Rewriting ------------------------ Description: We wish to use mod\_rewrite to serve different content based on the time of day. Solution: There are a lot of variables named `TIME_xxx` for rewrite conditions. In conjunction with the special lexicographic comparison patterns `<STRING`, `>STRING` and `=STRING` we can do time-dependent redirects: ``` RewriteEngine on RewriteCond "%{TIME_HOUR}%{TIME_MIN}" ">0700" RewriteCond "%{TIME_HOUR}%{TIME_MIN}" "<1900" RewriteRule "^foo\.html$" "foo.day.html" [L] RewriteRule "^foo\.html$" "foo.night.html" ``` This provides the content of `foo.day.html` under the URL `foo.html` from `07:01-18:59` and at the remaining time the contents of `foo.night.html`. `[mod\_cache](../mod/mod_cache)`, intermediate proxies and browsers may each cache responses and cause the either page to be shown outside of the time-window configured. `[mod\_expires](../mod/mod_expires)` may be used to control this effect. You are, of course, much better off simply serving the content dynamically, and customizing it based on the time of day. Set Environment Variables Based On URL Parts -------------------------------------------- Description: At times, we want to maintain some kind of status when we perform a rewrite. For example, you want to make a note that you've done that rewrite, so that you can check later to see if a request came via that rewrite. One way to do this is by setting an environment variable. Solution: Use the [E] flag to set an environment variable. ``` RewriteEngine on RewriteRule "^/horse/(.*)" "/pony/$1" [E=**rewritten:1**] ``` Later in your ruleset you might check for this environment variable using a RewriteCond: ``` RewriteCond "%{ENV:rewritten}" "=1" ``` Note that environment variables do not survive an external redirect. You might consider using the [CO] flag to set a cookie. For per-directory and htaccess rewrites, where the final substitution is processed as an internal redirect, environment variables from the previous round of rewriting are prefixed with "REDIRECT\_".
programming_docs
apache_http_server Apache mod_rewrite Technical Details Apache mod\_rewrite Technical Details ===================================== This document discusses some of the technical details of mod\_rewrite and URL matching. API Phases ---------- The Apache HTTP Server handles requests in several phases. At each of these phases, one or more modules may be called upon to handle that portion of the request lifecycle. Phases include things like URL-to-filename translation, authentication, authorization, content, and logging. (This is not an exhaustive list.) mod\_rewrite acts in two of these phases (or "hooks", as they are often called) to influence how URLs may be rewritten. First, it uses the URL-to-filename translation hook, which occurs after the HTTP request has been read, but before any authorization starts. Secondly, it uses the Fixup hook, which is after the authorization phases, and after per-directory configuration files (`.htaccess` files) have been read, but before the content handler is called. So, after a request comes in and a corresponding server or virtual host has been determined, the rewriting engine starts processing any `mod_rewrite` directives appearing in the per-server configuration. (i.e., in the main server configuration file and `[<Virtualhost>](../mod/core#virtualhost)` sections.) This happens in the URL-to-filename phase. A few steps later, once the final data directories have been found, the per-directory configuration directives (`.htaccess` files and `[<Directory>](../mod/core#directory)` blocks) are applied. This happens in the Fixup phase. In each of these cases, mod\_rewrite rewrites the `REQUEST_URI` either to a new URL, or to a filename. In per-directory context (i.e., within `.htaccess` files and `Directory` blocks), these rules are being applied after a URL has already been translated to a filename. Because of this, the URL-path that mod\_rewrite initially compares `[RewriteRule](../mod/mod_rewrite#rewriterule)` directives against is the full filesystem path to the translated filename with the current directories path (including a trailing slash) removed from the front. To illustrate: If rules are in /var/www/foo/.htaccess and a request for /foo/bar/baz is being processed, an expression like ^bar/baz$ would match. If a substitution is made in per-directory context, a new internal subrequest is issued with the new URL, which restarts processing of the request phases. If the substitution is a relative path, the `[RewriteBase](../mod/mod_rewrite#rewritebase)` directive determines the URL-path prefix prepended to the substitution. In per-directory context, care must be taken to create rules which will eventually (in some future "round" of per-directory rewrite processing) not perform a substitution to avoid looping. (See [RewriteLooping](http://wiki.apache.org/httpd/RewriteLooping) for further discussion of this problem.) Because of this further manipulation of the URL in per-directory context, you'll need to take care to craft your rewrite rules differently in that context. In particular, remember that the leading directory path will be stripped off of the URL that your rewrite rules will see. Consider the examples below for further clarification. | Location of rule | Rule | | --- | --- | | VirtualHost section | RewriteRule "^/images/(.+)\.jpg" "/images/$1.gif" | | .htaccess file in document root | RewriteRule "^images/(.+)\.jpg" "images/$1.gif" | | .htaccess file in images directory | RewriteRule "^(.+)\.jpg" "$1.gif" | For even more insight into how mod\_rewrite manipulates URLs in different contexts, you should consult the [log entries](../mod/mod_rewrite#logging) made during rewriting. Ruleset Processing ------------------ Now when mod\_rewrite is triggered in these two API phases, it reads the configured rulesets from its configuration structure (which itself was either created on startup for per-server context or during the directory walk of the Apache kernel for per-directory context). Then the URL rewriting engine is started with the contained ruleset (one or more rules together with their conditions). The operation of the URL rewriting engine itself is exactly the same for both configuration contexts. Only the final result processing is different. The order of rules in the ruleset is important because the rewriting engine processes them in a special (and not very obvious) order. The rule is this: The rewriting engine loops through the ruleset rule by rule (`[RewriteRule](../mod/mod_rewrite#rewriterule)` directives) and when a particular rule matches it optionally loops through existing corresponding conditions (`RewriteCond` directives). For historical reasons the conditions are given first, and so the control flow is a little bit long-winded. See Figure 1 for more details. Figure 1:The control flow through the rewriting ruleset First the URL is matched against the *Pattern* of each rule. If it fails, mod\_rewrite immediately stops processing this rule, and continues with the next rule. If the *Pattern* matches, mod\_rewrite looks for corresponding rule conditions (RewriteCond directives, appearing immediately above the RewriteRule in the configuration). If none are present, it substitutes the URL with a new value, which is constructed from the string *Substitution*, and goes on with its rule-looping. But if conditions exist, it starts an inner loop for processing them in the order that they are listed. For conditions, the logic is different: we don't match a pattern against the current URL. Instead we first create a string *TestString* by expanding variables, back-references, map lookups, *etc.* and then we try to match *CondPattern* against it. If the pattern doesn't match, the complete set of conditions and the corresponding rule fails. If the pattern matches, then the next condition is processed until no more conditions are available. If all conditions match, processing is continued with the substitution of the URL with *Substitution*. apache_http_server Using mod_rewrite for Proxying Using mod\_rewrite for Proxying =============================== This document supplements the `[mod\_rewrite](../mod/mod_rewrite)` [reference documentation](../mod/mod_rewrite). It describes how to use the RewriteRule's [P] flag to proxy content to another server. A number of recipes are provided that describe common scenarios. Proxying Content with mod\_rewrite ---------------------------------- Description: mod\_rewrite provides the [P] flag, which allows URLs to be passed, via mod\_proxy, to another server. Two examples are given here. In one example, a URL is passed directly to another server, and served as though it were a local URL. In the other example, we proxy missing content to a back-end server. Solution: To simply map a URL to another server, we use the [P] flag, as follows: ``` RewriteEngine on RewriteBase "/products/" RewriteRule "^widget/(.*)$" "http://product.example.com/widget/$1" [P] ProxyPassReverse "/products/widget/" "http://product.example.com/widget/" ``` In the second example, we proxy the request only if we can't find the resource locally. This can be very useful when you're migrating from one server to another, and you're not sure if all the content has been migrated yet. ``` RewriteCond "%{REQUEST_FILENAME}" !-f RewriteCond "%{REQUEST_FILENAME}" !-d RewriteRule "^/(.*)" "http://old.example.com/$1" [P] ProxyPassReverse "/" "http://old.example.com/" ``` Discussion: In each case, we add a `[ProxyPassReverse](../mod/mod_proxy#proxypassreverse)` directive to ensure that any redirects issued by the backend are correctly passed on to the client. Consider using either `[ProxyPass](../mod/mod_proxy#proxypass)` or `[ProxyPassMatch](../mod/mod_proxy#proxypassmatch)` whenever possible in preference to mod\_rewrite. apache_http_server When not to use mod_rewrite When not to use mod\_rewrite ============================ This document supplements the `[mod\_rewrite](../mod/mod_rewrite)` [reference documentation](../mod/mod_rewrite). It describes perhaps one of the most important concepts about `[mod\_rewrite](../mod/mod_rewrite)` - namely, when to avoid using it. `[mod\_rewrite](../mod/mod_rewrite)` should be considered a last resort, when other alternatives are found wanting. Using it when there are simpler alternatives leads to configurations which are confusing, fragile, and hard to maintain. Understanding what other alternatives are available is a very important step towards `[mod\_rewrite](../mod/mod_rewrite)` mastery. Note that many of these examples won't work unchanged in your particular server configuration, so it's important that you understand them, rather than merely cutting and pasting the examples into your configuration. The most common situation in which `[mod\_rewrite](../mod/mod_rewrite)` is the right tool is when the very best solution requires access to the server configuration files, and you don't have that access. Some configuration directives are only available in the server configuration file. So if you are in a hosting situation where you only have .htaccess files to work with, you may need to resort to `[mod\_rewrite](../mod/mod_rewrite)`. Simple Redirection ------------------ `[mod\_alias](../mod/mod_alias)` provides the `[Redirect](../mod/mod_alias#redirect)` and `[RedirectMatch](../mod/mod_alias#redirectmatch)` directives, which provide a means to redirect one URL to another. This kind of simple redirection of one URL, or a class of URLs, to somewhere else, should be accomplished using these directives rather than `[RewriteRule](../mod/mod_rewrite#rewriterule)`. `RedirectMatch` allows you to include a regular expression in your redirection criteria, providing many of the benefits of using `RewriteRule`. A common use for `RewriteRule` is to redirect an entire class of URLs. For example, all URLs in the `/one` directory must be redirected to `http://one.example.com/`, or perhaps all `http` requests must be redirected to `https`. These situations are better handled by the `Redirect` directive. Remember that `Redirect` preserves path information. That is to say, a redirect for a URL `/one` will also redirect all URLs under that, such as `/one/two.html` and `/one/three/four.html`. To redirect URLs under `/one` to `http://one.example.com`, do the following: ``` Redirect "/one/" "http://one.example.com/" ``` To redirect one hostname to another, for example `example.com` to `www.example.com`, see the [Canonical Hostnames](remapping#canonicalhost) recipe. To redirect `http` URLs to `https`, do the following: ``` <VirtualHost *:80> ServerName www.example.com Redirect "/" "https://www.example.com/" </VirtualHost> <VirtualHost *:443> ServerName www.example.com # ... SSL configuration goes here </VirtualHost> ``` The use of `RewriteRule` to perform this task may be appropriate if there are other `RewriteRule` directives in the same scope. This is because, when there are `Redirect` and `RewriteRule` directives in the same scope, the `RewriteRule` directives will run first, regardless of the order of appearance in the configuration file. In the case of the *http-to-https* redirection, the use of `RewriteRule` would be appropriate if you don't have access to the main server configuration file, and are obliged to perform this task in a `.htaccess` file instead. URL Aliasing ------------ The `[Alias](../mod/mod_alias#alias)` directive provides mapping from a URI to a directory - usually a directory outside of your `[DocumentRoot](../mod/core#documentroot)`. Although it is possible to perform this mapping with `[mod\_rewrite](../mod/mod_rewrite)`, `[Alias](../mod/mod_alias#alias)` is the preferred method, for reasons of simplicity and performance. ### Using Alias ``` Alias "/cats" "/var/www/virtualhosts/felines/htdocs" ``` The use of `[mod\_rewrite](../mod/mod_rewrite)` to perform this mapping may be appropriate when you do not have access to the server configuration files. Alias may only be used in server or virtualhost context, and not in a `.htaccess` file. Symbolic links would be another way to accomplish the same thing, if you have `Options FollowSymLinks` enabled on your server. Virtual Hosting --------------- Although it is possible to handle [virtual hosts with mod\_rewrite](vhosts), it is seldom the right way. Creating individual `[<VirtualHost>](../mod/core#virtualhost)` blocks is almost always the right way to go. In the event that you have an enormous number of virtual hosts, consider using `[mod\_vhost\_alias](../mod/mod_vhost_alias)` to create these hosts automatically. Modules such as `[mod\_macro](../mod/mod_macro)` are also useful for creating a large number of virtual hosts dynamically. Using `[mod\_rewrite](../mod/mod_rewrite)` for vitualhost creation may be appropriate if you are using a hosting service that does not provide you access to the server configuration files, and you are therefore restricted to configuration using `.htaccess` files. See the [virtual hosts with mod\_rewrite](vhosts) document for more details on how you might accomplish this if it still seems like the right approach. Simple Proxying --------------- `[RewriteRule](../mod/mod_rewrite#rewriterule)` provides the [[P]](flags#flag_p) flag to pass rewritten URIs through `[mod\_proxy](../mod/mod_proxy)`. ``` RewriteRule "^/?images(.*)" "http://imageserver.local/images$1" [P] ``` However, in many cases, when there is no actual pattern matching needed, as in the example shown above, the `[ProxyPass](../mod/mod_proxy#proxypass)` directive is a better choice. The example here could be rendered as: ``` ProxyPass "/images/" "http://imageserver.local/images/" ``` Note that whether you use `[RewriteRule](../mod/mod_rewrite#rewriterule)` or `[ProxyPass](../mod/mod_proxy#proxypass)`, you'll still need to use the `[ProxyPassReverse](../mod/mod_proxy#proxypassreverse)` directive to catch redirects issued from the back-end server: ``` ProxyPassReverse "/images/" "http://imageserver.local/images/" ``` You may need to use `RewriteRule` instead when there are other `RewriteRule`s in effect in the same scope, as a `RewriteRule` will usually take effect before a `ProxyPass`, and so may preempt what you're trying to accomplish. Environment Variable Testing ---------------------------- `[mod\_rewrite](../mod/mod_rewrite)` is frequently used to take a particular action based on the presence or absence of a particular environment variable or request header. This can be done more efficiently using the `[<If>](../mod/core#if)`. Consider, for example, the common scenario where `RewriteRule` is used to enforce a canonical hostname, such as `www.example.com` instead of `example.com`. This can be done using the `[<If>](../mod/core#if)` directive, as shown here: ``` <If "req('Host') != 'www.example.com'"> Redirect "/" "http://www.example.com/" </If> ``` This technique can be used to take actions based on any request header, response header, or environment variable, replacing `[mod\_rewrite](../mod/mod_rewrite)` in many common scenarios. See especially the [expression evaluation documentation](../expr) for a overview of what types of expressions you can use in `[<If>](../mod/core#if)` sections, and in certain other directives. apache_http_server Apache SSL/TLS Encryption Apache SSL/TLS Encryption ========================= The Apache HTTP Server module `[mod\_ssl](../mod/mod_ssl)` provides an interface to the [OpenSSL](http://www.openssl.org/) library, which provides Strong Encryption using the Secure Sockets Layer and Transport Layer Security protocols. Documentation ------------- * [mod\_ssl Configuration How-To](ssl_howto) * [Introduction To SSL](ssl_intro) * [Compatibility](ssl_compat) * [Frequently Asked Questions](ssl_faq) * [Glossary](https://httpd.apache.org/docs/2.4/en/glossary.html) mod\_ssl -------- Extensive documentation on the directives and environment variables provided by this module is provided in the [mod\_ssl reference documentation](../mod/mod_ssl). apache_http_server SSL/TLS Strong Encryption: FAQ SSL/TLS Strong Encryption: FAQ ============================== > The wise man doesn't give the right answers, he poses the right questions. > > -- Claude Levi-Strauss > > Installation ------------ * [Why do I get permission errors related to SSLMutex when I start Apache?](#mutex) * [Why does mod\_ssl stop with the error "Failed to generate temporary 512 bit RSA private key" when I start Apache?](#entropy) ### Why do I get permission errors related to SSLMutex when I start Apache? Errors such as ```mod_ssl: Child could not open SSLMutex lockfile /opt/apache/logs/ssl_mutex.18332 (System error follows) [...] System: Permission denied (errno: 13)`'' are usually caused by overly restrictive permissions on the *parent* directories. Make sure that all parent directories (here `/opt`, `/opt/apache` and `/opt/apache/logs`) have the x-bit set for, at minimum, the UID under which Apache's children are running (see the `[User](../mod/mod_unixd#user)` directive). ### Why does mod\_ssl stop with the error "Failed to generate temporary 512 bit RSA private key" when I start Apache? Cryptographic software needs a source of unpredictable data to work correctly. Many open source operating systems provide a "randomness device" that serves this purpose (usually named `/dev/random`). On other systems, applications have to seed the OpenSSL Pseudo Random Number Generator (PRNG) manually with appropriate data before generating keys or performing public key encryption. As of version 0.9.5, the OpenSSL functions that need randomness report an error if the PRNG has not been seeded with at least 128 bits of randomness. To prevent this error, `[mod\_ssl](../mod/mod_ssl)` has to provide enough entropy to the PRNG to allow it to work correctly. This can be done via the `[SSLRandomSeed](../mod/mod_ssl#sslrandomseed)` directive. Configuration ------------- * [Is it possible to provide HTTP and HTTPS from the same server?](#parallel) * [Which port does HTTPS use?](#ports) * [How do I speak HTTPS manually for testing purposes?](#httpstest) * [Why does the connection hang when I connect to my SSL-aware Apache server?](#hang) * [Why do I get ``Connection Refused'' errors, when trying to access my newly installed Apache+mod\_ssl server via HTTPS?](#refused) * [Why are the `SSL_XXX` variables not available to my CGI & SSI scripts?](#envvars) * [How can I switch between HTTP and HTTPS in relative hyperlinks?](#relative) ### Is it possible to provide HTTP and HTTPS from the same server? Yes. HTTP and HTTPS use different server ports (HTTP binds to port 80, HTTPS to port 443), so there is no direct conflict between them. You can either run two separate server instances bound to these ports, or use Apache's elegant virtual hosting facility to create two virtual servers, both served by the same instance of Apache - one responding over HTTP to requests on port 80, and the other responding over HTTPS to requests on port 443. ### Which port does HTTPS use? You can run HTTPS on any port, but the standards specify port 443, which is where any HTTPS compliant browser will look by default. You can force your browser to look on a different port by specifying it in the URL. For example, if your server is set up to serve pages over HTTPS on port 8080, you can access them at `https://example.com:8080/` ### How do I speak HTTPS manually for testing purposes? While you usually just use ``` $ telnet localhost 80 GET / HTTP/1.0 ``` for simple testing of Apache via HTTP, it's not so easy for HTTPS because of the SSL protocol between TCP and HTTP. With the help of OpenSSL's `s_client` command, however, you can do a similar check via HTTPS: ``` $ openssl s_client -connect localhost:443 -state -debug GET / HTTP/1.0 ``` Before the actual HTTP response you will receive detailed information about the SSL handshake. For a more general command line client which directly understands both HTTP and HTTPS, can perform GET and POST operations, can use a proxy, supports byte ranges, etc. you should have a look at the nifty [cURL](http://curl.haxx.se/) tool. Using this, you can check that Apache is responding correctly to requests via HTTP and HTTPS as follows: ``` $ curl http://localhost/ $ curl https://localhost/ ``` ### Why does the connection hang when I connect to my SSL-aware Apache server? This can happen when you try to connect to a HTTPS server (or virtual server) via HTTP (eg, using `http://example.com/` instead of `https://example.com`). It can also happen when trying to connect via HTTPS to a HTTP server (eg, using `https://example.com/` on a server which doesn't support HTTPS, or which supports it on a non-standard port). Make sure that you're connecting to a (virtual) server that supports SSL. ### Why do I get ``Connection Refused'' messages, when trying to access my newly installed Apache+mod\_ssl server via HTTPS? This error can be caused by an incorrect configuration. Please make sure that your `[Listen](../mod/mpm_common#listen)` directives match your `[<VirtualHost>](../mod/core#virtualhost)` directives. If all else fails, please start afresh, using the default configuration provided by `[mod\_ssl](../mod/mod_ssl)`. ### Why are the `SSL_XXX` variables not available to my CGI & SSI scripts? Please make sure you have ```SSLOptions +StdEnvVars`'' enabled for the context of your CGI/SSI requests. ### How can I switch between HTTP and HTTPS in relative hyperlinks? Usually, to switch between HTTP and HTTPS, you have to use fully-qualified hyperlinks (because you have to change the URL scheme). Using `[mod\_rewrite](../mod/mod_rewrite)` however, you can manipulate relative hyperlinks, to achieve the same effect. ``` RewriteEngine on RewriteRule "^/(.*)_SSL$" "https://%{SERVER_NAME}/$1" [R,L] RewriteRule "^/(.*)_NOSSL$" "http://%{SERVER_NAME}/$1" [R,L] ``` This rewrite ruleset lets you use hyperlinks of the form `<a href="document.html_SSL">`, to switch to HTTPS in a relative link. (Replace SSL with NOSSL to switch to HTTP.) Certificates ------------ * [What are RSA Private Keys, CSRs and Certificates?](#keyscerts) * [Is there a difference on startup between a non-SSL-aware Apache and an SSL-aware Apache?](#startup) * [How do I create a self-signed SSL Certificate for testing purposes?](#selfcert) * [How do I create a real SSL Certificate?](#realcert) * [How do I create and use my own Certificate Authority (CA)?](#ownca) * [How can I change the pass-phrase on my private key file?](#passphrase) * [How can I get rid of the pass-phrase dialog at Apache startup time?](#removepassphrase) * [How do I verify that a private key matches its Certificate?](#verify) * [How can I convert a certificate from PEM to DER format?](#pemder) * [Why do browsers complain that they cannot verify my server certificate?](#gid) ### What are RSA Private Keys, CSRs and Certificates? An RSA private key file is a digital file that you can use to decrypt messages sent to you. It has a public component which you distribute (via your Certificate file) which allows people to encrypt those messages to you. A Certificate Signing Request (CSR) is a digital file which contains your public key and your name. You send the CSR to a Certifying Authority (CA), who will convert it into a real Certificate, by signing it. A Certificate contains your RSA public key, your name, the name of the CA, and is digitally signed by the CA. Browsers that know the CA can verify the signature on that Certificate, thereby obtaining your RSA public key. That enables them to send messages which only you can decrypt. See the [Introduction](ssl_intro) chapter for a general description of the SSL protocol. ### Is there a difference on startup between a non-SSL-aware Apache and an SSL-aware Apache? Yes. In general, starting Apache with `[mod\_ssl](../mod/mod_ssl)` built-in is just like starting Apache without it. However, if you have a passphrase on your SSL private key file, a startup dialog will pop up which asks you to enter the pass phrase. Having to manually enter the passphrase when starting the server can be problematic - for example, when starting the server from the system boot scripts. In this case, you can follow the steps [below](#removepassphrase) to remove the passphrase from your private key. Bear in mind that doing so brings additional security risks - proceed with caution! ### How do I create a self-signed SSL Certificate for testing purposes? 1. Make sure OpenSSL is installed and in your `PATH`. 2. Run the following command, to create `server.key` and `server.crt` files: `$ openssl req -new -x509 -nodes -out server.crt -keyout server.key` These can be used as follows in your `httpd.conf` file: ``` SSLCertificateFile "/path/to/this/server.crt" SSLCertificateKeyFile "/path/to/this/server.key" ``` 3. It is important that you are aware that this `server.key` does *not* have any passphrase. To add a passphrase to the key, you should run the following command, and enter & verify the passphrase as requested. `$ openssl rsa -des3 -in server.key -out server.key.new` `$ mv server.key.new server.key` Please backup the `server.key` file, and the passphrase you entered, in a secure location. ### How do I create a real SSL Certificate? Here is a step-by-step description: 1. Make sure OpenSSL is installed and in your `PATH`. 2. Create a RSA private key for your Apache server (will be Triple-DES encrypted and PEM formatted): `$ openssl genrsa -des3 -out server.key 2048` Please backup this `server.key` file and the pass-phrase you entered in a secure location. You can see the details of this RSA private key by using the command: `$ openssl rsa -noout -text -in server.key` If necessary, you can also create a decrypted PEM version (not recommended) of this RSA private key with: `$ openssl rsa -in server.key -out server.key.unsecure` 3. Create a Certificate Signing Request (CSR) with the server RSA private key (output will be PEM formatted): `$ openssl req -new -key server.key -out server.csr` Make sure you enter the FQDN ("Fully Qualified Domain Name") of the server when OpenSSL prompts you for the "CommonName", i.e. when you generate a CSR for a website which will be later accessed via `https://www.foo.dom/`, enter "www.foo.dom" here. You can see the details of this CSR by using `$ openssl req -noout -text -in server.csr` 4. You now have to send this Certificate Signing Request (CSR) to a Certifying Authority (CA) to be signed. Once the CSR has been signed, you will have a real Certificate, which can be used by Apache. You can have a CSR signed by a commercial CA, or you can create your own CA to sign it. Commercial CAs usually ask you to post the CSR into a web form, pay for the signing, and then send a signed Certificate, which you can store in a server.crt file. For details on how to create your own CA, and use this to sign a CSR, see [below](#ownca). Once your CSR has been signed, you can see the details of the Certificate as follows: `$ openssl x509 -noout -text -in server.crt` 5. You should now have two files: `server.key` and `server.crt`. These can be used as follows in your `httpd.conf` file: ``` SSLCertificateFile "/path/to/this/server.crt" SSLCertificateKeyFile "/path/to/this/server.key" ``` The `server.csr` file is no longer needed. ### How do I create and use my own Certificate Authority (CA)? The short answer is to use the `CA.sh` or `CA.pl` script provided by OpenSSL. Unless you have a good reason not to, you should use these for preference. If you cannot, you can create a self-signed certificate as follows: 1. Create a RSA private key for your server (will be Triple-DES encrypted and PEM formatted): `$ openssl genrsa -des3 -out server.key 2048` Please backup this `server.key` file and the pass-phrase you entered in a secure location. You can see the details of this RSA private key by using the command: `$ openssl rsa -noout -text -in server.key` If necessary, you can also create a decrypted PEM version (not recommended) of this RSA private key with: `$ openssl rsa -in server.key -out server.key.unsecure` 2. Create a self-signed certificate (X509 structure) with the RSA key you just created (output will be PEM formatted): `$ openssl req -new -x509 -nodes -sha1 -days 365 -key server.key -out server.crt -extensions usr_cert` This signs the server CSR and results in a `server.crt` file. You can see the details of this Certificate using: `$ openssl x509 -noout -text -in server.crt` ### How can I change the pass-phrase on my private key file? You simply have to read it with the old pass-phrase and write it again, specifying the new pass-phrase. You can accomplish this with the following commands: `$ openssl rsa -des3 -in server.key -out server.key.new` `$ mv server.key.new server.key` The first time you're asked for a PEM pass-phrase, you should enter the old pass-phrase. After that, you'll be asked again to enter a pass-phrase - this time, use the new pass-phrase. If you are asked to verify the pass-phrase, you'll need to enter the new pass-phrase a second time. ### How can I get rid of the pass-phrase dialog at Apache startup time? The reason this dialog pops up at startup and every re-start is that the RSA private key inside your server.key file is stored in encrypted format for security reasons. The pass-phrase is needed to decrypt this file, so it can be read and parsed. Removing the pass-phrase removes a layer of security from your server - proceed with caution! 1. Remove the encryption from the RSA private key (while keeping a backup copy of the original file): `$ cp server.key server.key.org` `$ openssl rsa -in server.key.org -out server.key` 2. Make sure the server.key file is only readable by root: `$ chmod 400 server.key` Now `server.key` contains an unencrypted copy of the key. If you point your server at this file, it will not prompt you for a pass-phrase. HOWEVER, if anyone gets this key they will be able to impersonate you on the net. PLEASE make sure that the permissions on this file are such that only root or the web server user can read it (preferably get your web server to start as root but run as another user, and have the key readable only by root). As an alternative approach you can use the ```SSLPassPhraseDialog exec:/path/to/program`'' facility. Bear in mind that this is neither more nor less secure, of course. ### How do I verify that a private key matches its Certificate? A private key contains a series of numbers. Two of these numbers form the "public key", the others are part of the "private key". The "public key" bits are included when you generate a CSR, and subsequently form part of the associated Certificate. To check that the public key in your Certificate matches the public portion of your private key, you simply need to compare these numbers. To view the Certificate and the key run the commands: `$ openssl x509 -noout -text -in server.crt` `$ openssl rsa -noout -text -in server.key` The `modulus' and the `public exponent' portions in the key and the Certificate must match. As the public exponent is usually 65537 and it's difficult to visually check that the long modulus numbers are the same, you can use the following approach: `$ openssl x509 -noout -modulus -in server.crt | openssl md5` `$ openssl rsa -noout -modulus -in server.key | openssl md5` This leaves you with two rather shorter numbers to compare. It is, in theory, possible that these numbers may be the same, without the modulus numbers being the same, but the chances of this are overwhelmingly remote. Should you wish to check to which key or certificate a particular CSR belongs you can perform the same calculation on the CSR as follows: ``` $ openssl req -noout -modulus -in server.csr | openssl md5 ``` ### How can I convert a certificate from PEM to DER format? The default certificate format for OpenSSL is PEM, which is simply Base64 encoded DER, with header and footer lines. For some applications (e.g. Microsoft Internet Explorer) you need the certificate in plain DER format. You can convert a PEM file `cert.pem` into the corresponding DER file `cert.der` using the following command: `$ openssl x509 -in cert.pem -out cert.der -outform DER` ### Why do browsers complain that they cannot verify my server certificate? One reason this might happen is because your server certificate is signed by an intermediate CA. Various CAs, such as Verisign or Thawte, have started signing certificates not with their root certificate but with intermediate certificates. Intermediate CA certificates lie between the root CA certificate (which is installed in the browsers) and the server certificate (which you installed on the server). In order for the browser to be able to traverse and verify the trust chain from the server certificate to the root certificate it needs need to be given the intermediate certificates. The CAs should be able to provide you such intermediate certificate packages that can be installed on the server. You need to include those intermediate certificates with the `[SSLCertificateChainFile](../mod/mod_ssl#sslcertificatechainfile)` directive. The SSL Protocol ---------------- * [Why do I get lots of random SSL protocol errors under heavy server load?](#random) * [Why does my webserver have a higher load, now that it serves SSL encrypted traffic?](#load) * [Why do HTTPS connections to my server sometimes take up to 30 seconds to establish a connection?](#establishing) * [What SSL Ciphers are supported by mod\_ssl?](#ciphers) * [Why do I get ``no shared cipher'' errors, when trying to use Anonymous Diffie-Hellman (ADH) ciphers?](#adh) * [Why do I get a 'no shared ciphers' error when connecting to my newly installed server?](#sharedciphers) * [Why can't I use SSL with name-based/non-IP-based virtual hosts?](#vhosts) * [Is it possible to use Name-Based Virtual Hosting to identify different SSL virtual hosts?](#vhosts2) * [How do I get SSL compression working?](#comp) * [When I use Basic Authentication over HTTPS the lock icon in Netscape browsers stays unlocked when the dialog pops up. Does this mean the username/password is being sent unencrypted?](#lockicon) * [Why do I get I/O errors when connecting via HTTPS to an Apache+mod\_ssl server with Microsoft Internet Explorer (MSIE)?](#msie) * [How do I enable TLS-SRP?](#srp) * [Why do I get handshake failures with Java-based clients when using a certificate with more than 1024 bits?](#javadh) ### Why do I get lots of random SSL protocol errors under heavy server load? There can be a number of reasons for this, but the main one is problems with the SSL session Cache specified by the `[SSLSessionCache](../mod/mod_ssl#sslsessioncache)` directive. The DBM session cache is the most likely source of the problem, so using the SHM session cache (or no cache at all) may help. ### Why does my webserver have a higher load, now that it serves SSL encrypted traffic? SSL uses strong cryptographic encryption, which necessitates a lot of number crunching. When you request a webpage via HTTPS, everything (even the images) is encrypted before it is transferred. So increased HTTPS traffic leads to load increases. ### Why do HTTPS connections to my server sometimes take up to 30 seconds to establish a connection? This is usually caused by a `/dev/random` device for `[SSLRandomSeed](../mod/mod_ssl#sslrandomseed)` which blocks the read(2) call until enough entropy is available to service the request. More information is available in the reference manual for the `[SSLRandomSeed](../mod/mod_ssl#sslrandomseed)` directive. ### What SSL Ciphers are supported by mod\_ssl? Usually, any SSL ciphers supported by the version of OpenSSL in use, are also supported by `[mod\_ssl](../mod/mod_ssl)`. Which ciphers are available can depend on the way you built OpenSSL. Typically, at least the following ciphers are supported: 1. RC4 with SHA1 2. AES with SHA1 3. Triple-DES with SHA1 To determine the actual list of ciphers available, you should run the following: ``` $ openssl ciphers -v ``` ### Why do I get ``no shared cipher'' errors, when trying to use Anonymous Diffie-Hellman (ADH) ciphers? By default, OpenSSL does *not* allow ADH ciphers, for security reasons. Please be sure you are aware of the potential side-effects if you choose to enable these ciphers. In order to use Anonymous Diffie-Hellman (ADH) ciphers, you must build OpenSSL with ```-DSSL_ALLOW_ADH`'', and then add ```ADH`'' into your `[SSLCipherSuite](../mod/mod_ssl#sslciphersuite)`. ### Why do I get a 'no shared ciphers' error when connecting to my newly installed server? Either you have made a mistake with your `[SSLCipherSuite](../mod/mod_ssl#sslciphersuite)` directive (compare it with the pre-configured example in `extra/httpd-ssl.conf`) or you chose to use DSA/DH algorithms instead of RSA when you generated your private key and ignored or overlooked the warnings. If you have chosen DSA/DH, then your server cannot communicate using RSA-based SSL ciphers (at least until you configure an additional RSA-based certificate/key pair). Modern browsers like NS or IE can only communicate over SSL using RSA ciphers. The result is the "no shared ciphers" error. To fix this, regenerate your server certificate/key pair, using the RSA algorithm. ### Why can't I use SSL with name-based/non-IP-based virtual hosts? The reason is very technical, and a somewhat "chicken and egg" problem. The SSL protocol layer stays below the HTTP protocol layer and encapsulates HTTP. When an SSL connection (HTTPS) is established Apache/mod\_ssl has to negotiate the SSL protocol parameters with the client. For this, mod\_ssl has to consult the configuration of the virtual server (for instance it has to look for the cipher suite, the server certificate, etc.). But in order to go to the correct virtual server Apache has to know the `Host` HTTP header field. To do this, the HTTP request header has to be read. This cannot be done before the SSL handshake is finished, but the information is needed in order to complete the SSL handshake phase. See the next question for how to circumvent this issue. Note that if you have a wildcard SSL certificate, or a certificate that has multiple hostnames on it using subjectAltName fields, you can use SSL on name-based virtual hosts without further workarounds. ### Is it possible to use Name-Based Virtual Hosting to identify different SSL virtual hosts? Name-Based Virtual Hosting is a very popular method of identifying different virtual hosts. It allows you to use the same IP address and the same port number for many different sites. When people move on to SSL, it seems natural to assume that the same method can be used to have lots of different SSL virtual hosts on the same server. It is possible, but only if using a 2.2.12 or later web server, built with 0.9.8j or later OpenSSL. This is because it requires a feature that only the most recent revisions of the SSL specification added, called Server Name Indication (SNI). Note that if you have a wildcard SSL certificate, or a certificate that has multiple hostnames on it using subjectAltName fields, you can use SSL on name-based virtual hosts without further workarounds. The reason is that the SSL protocol is a separate layer which encapsulates the HTTP protocol. So the SSL session is a separate transaction, that takes place before the HTTP session has begun. The server receives an SSL request on IP address X and port Y (usually 443). Since the SSL request did not contain any Host: field, the server had no way to decide which SSL virtual host to use. Usually, it just used the first one it found which matched the port and IP address specified. If you are using a version of the web server and OpenSSL that support SNI, though, and the client's browser also supports SNI, then the hostname is included in the original SSL request, and the web server can select the correct SSL virtual host. You can, of course, use Name-Based Virtual Hosting to identify many non-SSL virtual hosts (all on port 80, for example) and then have a single SSL virtual host (on port 443). But if you do this, you must make sure to put the non-SSL port number on the NameVirtualHost directive, e.g. ``` NameVirtualHost 192.168.1.1:80 ``` Other workaround solutions include: Using separate IP addresses for different SSL hosts. Using different port numbers for different SSL hosts. ### How do I get SSL compression working? Although SSL compression negotiation was defined in the specification of SSLv2 and TLS, it took until May 2004 for RFC 3749 to define DEFLATE as a negotiable standard compression method. OpenSSL 0.9.8 started to support this by default when compiled with the `zlib` option. If both the client and the server support compression, it will be used. However, most clients still try to initially connect with an SSLv2 Hello. As SSLv2 did not include an array of preferred compression algorithms in its handshake, compression cannot be negotiated with these clients. If the client disables support for SSLv2, either an SSLv3 or TLS Hello may be sent, depending on which SSL library is used, and compression may be set up. You can verify whether clients make use of SSL compression by logging the `%{SSL_COMPRESS_METHOD}x` variable. ### When I use Basic Authentication over HTTPS the lock icon in Netscape browsers stays unlocked when the dialog pops up. Does this mean the username/password is being sent unencrypted? No, the username/password is transmitted encrypted. The icon in Netscape browsers is not actually synchronized with the SSL/TLS layer. It only toggles to the locked state when the first part of the actual webpage data is transferred, which may confuse people. The Basic Authentication facility is part of the HTTP layer, which is above the SSL/TLS layer in HTTPS. Before any HTTP data communication takes place in HTTPS, the SSL/TLS layer has already completed its handshake phase, and switched to encrypted communication. So don't be confused by this icon. ### Why do I get I/O errors when connecting via HTTPS to an Apache+mod\_ssl server with older versions of Microsoft Internet Explorer (MSIE)? The first reason is that the SSL implementation in some MSIE versions has some subtle bugs related to the HTTP keep-alive facility and the SSL close notify alerts on socket connection close. Additionally the interaction between SSL and HTTP/1.1 features are problematic in some MSIE versions. You can work around these problems by forcing Apache not to use HTTP/1.1, keep-alive connections or send the SSL close notify messages to MSIE clients. This can be done by using the following directive in your SSL-aware virtual host section: ``` SetEnvIf User-Agent "MSIE [2-5]" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 ``` Further, some MSIE versions have problems with particular ciphers. Unfortunately, it is not possible to implement a MSIE-specific workaround for this, because the ciphers are needed as early as the SSL handshake phase. So a MSIE-specific `[SetEnvIf](../mod/mod_setenvif#setenvif)` won't solve these problems. Instead, you will have to make more drastic adjustments to the global parameters. Before you decide to do this, make sure your clients really have problems. If not, do not make these changes - they will affect *all* your clients, MSIE or otherwise. ### How do I enable TLS-SRP? TLS-SRP (Secure Remote Password key exchange for TLS, specified in RFC 5054) can supplement or replace certificates in authenticating an SSL connection. To use TLS-SRP, set the `[SSLSRPVerifierFile](../mod/mod_ssl#sslsrpverifierfile)` directive to point to an OpenSSL SRP verifier file. To create the verifier file, use the `openssl` tool: ``` openssl srp -srpvfile passwd.srpv -add username ``` After creating this file, specify it in the SSL server configuration: ``` SSLSRPVerifierFile /path/to/passwd.srpv ``` To force clients to use non-certificate TLS-SRP cipher suites, use the following directive: ``` SSLCipherSuite "!DSS:!aRSA:SRP" ``` ### Why do I get handshake failures with Java-based clients when using a certificate with more than 1024 bits? Beginning with version 2.4.7, `[mod\_ssl](../mod/mod_ssl)` will use DH parameters which include primes with lengths of more than 1024 bits. Java 7 and earlier limit their support for DH prime sizes to a maximum of 1024 bits, however. If your Java-based client aborts with exceptions such as `java.lang.RuntimeException: Could not generate DH keypair` and `java.security.InvalidAlgorithmParameterException: Prime size must be multiple of 64, and can only range from 512 to 1024 (inclusive)`, and httpd logs `tlsv1 alert internal error (SSL alert number 80)` (at `[LogLevel](../mod/core#loglevel)` `info` or higher), you can either rearrange mod\_ssl's cipher list with `[SSLCipherSuite](../mod/mod_ssl#sslciphersuite)` (possibly in conjunction with `[SSLHonorCipherOrder](../mod/mod_ssl#sslhonorcipherorder)`), or you can use custom DH parameters with a 1024-bit prime, which will always have precedence over any of the built-in DH parameters. To generate custom DH parameters, use the `openssl dhparam 1024` command. Alternatively, you can use the following standard 1024-bit DH parameters from [RFC 2409](http://www.ietf.org/rfc/rfc2409.txt), section 6.2: ``` -----BEGIN DH PARAMETERS----- MIGHAoGBAP//////////yQ/aoiFowjTExmKLgNwc0SkCTgiKZ8x0Agu+pjsTmyJR Sgh5jjQE3e+VGbPNOkMbMCsKbfJfFDdP4TVtbVHCReSFtXZiXn7G9ExC6aY37WsL /1y29Aa37e44a/taiZ+lrp8kEXxLH+ZJKGZR7OZTgf//////////AgEC -----END DH PARAMETERS----- ``` Add the custom parameters including the "BEGIN DH PARAMETERS" and "END DH PARAMETERS" lines to the end of the first certificate file you have configured using the `[SSLCertificateFile](../mod/mod_ssl#sslcertificatefile)` directive. mod\_ssl Support ---------------- * [What information resources are available in case of mod\_ssl problems?](#resources) * [What support contacts are available in case of mod\_ssl problems?](#contact) * [What information should I provide when writing a bug report?](#reportdetails) * [I had a core dump, can you help me?](#coredumphelp) * [How do I get a backtrace, to help find the reason for my core dump?](#backtrace) ### What information resources are available in case of mod\_ssl problems? The following information resources are available. In case of problems you should search here first. Answers in the User Manual's F.A.Q. List (this) <http://httpd.apache.org/docs/2.4/ssl/ssl_faq.html> First check the F.A.Q. (this text). If your problem is a common one, it may have been answered several times before, and been included in this doc. ### What support contacts are available in case of mod\_ssl problems? The following lists all support possibilities for mod\_ssl, in order of preference. Please go through these possibilities *in this order* - don't just pick the one you like the look of. 1. *Send a Problem Report to the Apache httpd Users Support Mailing List* [[email protected]](mailto:[email protected]) This is the second way of submitting your problem report. Again, you must subscribe to the list first, but you can then easily discuss your problem with the whole Apache httpd user community. 2. *Write a Problem Report in the Bug Database* <http://httpd.apache.org/bug_report.html> This is the last way of submitting your problem report. You should only do this if you've already posted to the mailing lists, and had no success. Please follow the instructions on the above page *carefully*. ### What information should I provide when writing a bug report? You should always provide at least the following information: Apache httpd and OpenSSL version information The Apache version can be determined by running `httpd -v`. The OpenSSL version can be determined by running `openssl version`. Alternatively, if you have Lynx installed, you can run the command `lynx -mime_header http://localhost/ | grep Server` to gather this information in a single step. The details on how you built and installed Apache httpd and OpenSSL For this you can provide a logfile of your terminal session which shows the configuration and install steps. If this is not possible, you should at least provide the `[configure](../programs/configure)` command line you used. In case of core dumps please include a Backtrace If your Apache httpd dumps its core, please attach a stack-frame ``backtrace'' (see [below](#backtrace) for information on how to get this). This information is required in order to find a reason for your core dump. A detailed description of your problem Don't laugh, we really mean it! Many problem reports don't include a description of what the actual problem is. Without this, it's very difficult for anyone to help you. So, it's in your own interest (you want the problem be solved, don't you?) to include as much detail as possible, please. Of course, you should still include all the essentials above too. ### I had a core dump, can you help me? In general no, at least not unless you provide more details about the code location where Apache dumped core. What is usually always required in order to help you is a backtrace (see next question). Without this information it is mostly impossible to find the problem and help you in fixing it. ### How do I get a backtrace, to help find the reason for my core dump? Following are the steps you will need to complete, to get a backtrace: 1. Make sure you have debugging symbols available, at least in Apache. On platforms where you use GCC/GDB, you will have to build Apache+mod\_ssl with ```OPTIM="-g -ggdb3"`'' to get this. On other platforms at least ```OPTIM="-g"`'' is needed. 2. Start the server and try to reproduce the core-dump. For this you may want to use a directive like ```CoreDumpDirectory /tmp`'' to make sure that the core-dump file can be written. This should result in a `/tmp/core` or `/tmp/httpd.core` file. If you don't get one of these, try running your server under a non-root UID. Many modern kernels do not allow a process to dump core after it has done a `setuid()` (unless it does an `exec()`) for security reasons (there can be privileged information left over in memory). If necessary, you can run `/path/to/httpd -X` manually to force Apache to not fork. 3. Analyze the core-dump. For this, run `gdb /path/to/httpd /tmp/httpd.core` or a similar command. In GDB, all you have to do then is to enter `bt`, and voila, you get the backtrace. For other debuggers consult your local debugger manual.
programming_docs
apache_http_server SSL/TLS Strong Encryption: An Introduction SSL/TLS Strong Encryption: An Introduction ========================================== As an introduction this chapter is aimed at readers who are familiar with the Web, HTTP, and Apache, but are not security experts. It is not intended to be a definitive guide to the SSL protocol, nor does it discuss specific techniques for managing certificates in an organization, or the important legal issues of patents and import and export restrictions. Rather, it is intended to provide a common background to `[mod\_ssl](../mod/mod_ssl)` users by pulling together various concepts, definitions, and examples as a starting point for further exploration. Cryptographic Techniques ------------------------ Understanding SSL requires an understanding of cryptographic algorithms, message digest functions (aka. one-way or hash functions), and digital signatures. These techniques are the subject of entire books (see for instance [[AC96](#AC96)]) and provide the basis for privacy, integrity, and authentication. ### Cryptographic Algorithms Suppose Alice wants to send a message to her bank to transfer some money. Alice would like the message to be private, since it will include information such as her account number and transfer amount. One solution is to use a cryptographic algorithm, a technique that would transform her message into an encrypted form, unreadable until it is decrypted. Once in this form, the message can only be decrypted by using a secret key. Without the key the message is useless: good cryptographic algorithms make it so difficult for intruders to decode the original text that it isn't worth their effort. There are two categories of cryptographic algorithms: conventional and public key. Conventional cryptography also known as symmetric cryptography, requires the sender and receiver to share a key: a secret piece of information that may be used to encrypt or decrypt a message. As long as this key is kept secret, nobody other than the sender or recipient can read the message. If Alice and the bank know a secret key, then they can send each other private messages. The task of sharing a key between sender and recipient before communicating, while also keeping it secret from others, can be problematic. Public key cryptography also known as asymmetric cryptography, solves the key exchange problem by defining an algorithm which uses two keys, each of which may be used to encrypt a message. If one key is used to encrypt a message then the other must be used to decrypt it. This makes it possible to receive secure messages by simply publishing one key (the public key) and keeping the other secret (the private key). Anyone can encrypt a message using the public key, but only the owner of the private key will be able to read it. In this way, Alice can send private messages to the owner of a key-pair (the bank), by encrypting them using their public key. Only the bank will be able to decrypt them. ### Message Digests Although Alice may encrypt her message to make it private, there is still a concern that someone might modify her original message or substitute it with a different one, in order to transfer the money to themselves, for instance. One way of guaranteeing the integrity of Alice's message is for her to create a concise summary of her message and send this to the bank as well. Upon receipt of the message, the bank creates its own summary and compares it with the one Alice sent. If the summaries are the same then the message has been received intact. A summary such as this is called a message digest, *one-way function* or *hash function*. Message digests are used to create a short, fixed-length representation of a longer, variable-length message. Digest algorithms are designed to produce a unique digest for each message. Message digests are designed to make it impractically difficult to determine the message from the digest and (in theory) impossible to find two different messages which create the same digest -- thus eliminating the possibility of substituting one message for another while maintaining the same digest. Another challenge that Alice faces is finding a way to send the digest to the bank securely; if the digest is not sent securely, its integrity may be compromised and with it the possibility for the bank to determine the integrity of the original message. Only if the digest is sent securely can the integrity of the associated message be determined. One way to send the digest securely is to include it in a digital signature. ### Digital Signatures When Alice sends a message to the bank, the bank needs to ensure that the message is really from her, so an intruder cannot request a transaction involving her account. A *digital signature*, created by Alice and included with the message, serves this purpose. Digital signatures are created by encrypting a digest of the message and other information (such as a sequence number) with the sender's private key. Though anyone can *decrypt* the signature using the public key, only the sender knows the private key. This means that only the sender can have signed the message. Including the digest in the signature means the signature is only good for that message; it also ensures the integrity of the message since no one can change the digest and still sign it. To guard against interception and reuse of the signature by an intruder at a later date, the signature contains a unique sequence number. This protects the bank from a fraudulent claim from Alice that she did not send the message -- only she could have signed it (non-repudiation). Certificates ------------ Although Alice could have sent a private message to the bank, signed it and ensured the integrity of the message, she still needs to be sure that she is really communicating with the bank. This means that she needs to be sure that the public key she is using is part of the bank's key-pair, and not an intruder's. Similarly, the bank needs to verify that the message signature really was signed by the private key that belongs to Alice. If each party has a certificate which validates the other's identity, confirms the public key and is signed by a trusted agency, then both can be assured that they are communicating with whom they think they are. Such a trusted agency is called a *Certificate Authority* and certificates are used for authentication. ### Certificate Contents A certificate associates a public key with the real identity of an individual, server, or other entity, known as the subject. As shown in [Table 1](#table1), information about the subject includes identifying information (the distinguished name) and the public key. It also includes the identification and signature of the Certificate Authority that issued the certificate and the period of time during which the certificate is valid. It may have additional information (or extensions) as well as administrative information for the Certificate Authority's use, such as a serial number. #### Table 1: Certificate Information | | | | --- | --- | | Subject | Distinguished Name, Public Key | | Issuer | Distinguished Name, Signature | | Period of Validity | Not Before Date, Not After Date | | Administrative Information | Version, Serial Number | | Extended Information | Basic Constraints, Netscape Flags, etc. | A distinguished name is used to provide an identity in a specific context -- for instance, an individual might have a personal certificate as well as one for their identity as an employee. Distinguished names are defined by the X.509 standard [[X509](#X509)], which defines the fields, field names and abbreviations used to refer to the fields (see [Table 2](#table2)). #### Table 2: Distinguished Name Information | DN Field | Abbrev. | Description | Example | | --- | --- | --- | --- | | Common Name | CN | Name being certified | CN=Joe Average | | Organization or Company | O | Name is associated with thisorganization | O=Snake Oil, Ltd. | | Organizational Unit | OU | Name is associated with this organization unit, such as a department | OU=Research Institute | | City/Locality | L | Name is located in this City | L=Snake City | | State/Province | ST | Name is located in this State/Province | ST=Desert | | Country | C | Name is located in this Country (ISO code) | C=XZ | A Certificate Authority may define a policy specifying which distinguished field names are optional and which are required. It may also place requirements upon the field contents, as may users of certificates. For example, a Netscape browser requires that the Common Name for a certificate representing a server matches a wildcard pattern for the domain name of that server, such as `*.snakeoil.com`. The binary format of a certificate is defined using the ASN.1 notation [[ASN1](#ASN1)] [[PKCS](#PKCS)]. This notation defines how to specify the contents and encoding rules define how this information is translated into binary form. The binary encoding of the certificate is defined using Distinguished Encoding Rules (DER), which are based on the more general Basic Encoding Rules (BER). For those transmissions which cannot handle binary, the binary form may be translated into an ASCII form by using Base64 encoding [[MIME](#MIME)]. When placed between begin and end delimiter lines (as below), this encoded version is called a PEM ("Privacy Enhanced Mail") encoded certificate. ### Example of a PEM-encoded certificate (snakeoil.crt) ``` -----BEGIN CERTIFICATE----- MIIC7jCCAlegAwIBAgIBATANBgkqhkiG9w0BAQQFADCBqTELMAkGA1UEBhMCWFkx FTATBgNVBAgTDFNuYWtlIERlc2VydDETMBEGA1UEBxMKU25ha2UgVG93bjEXMBUG A1UEChMOU25ha2UgT2lsLCBMdGQxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhv cml0eTEVMBMGA1UEAxMMU25ha2UgT2lsIENBMR4wHAYJKoZIhvcNAQkBFg9jYUBz bmFrZW9pbC5kb20wHhcNOTgxMDIxMDg1ODM2WhcNOTkxMDIxMDg1ODM2WjCBpzEL MAkGA1UEBhMCWFkxFTATBgNVBAgTDFNuYWtlIERlc2VydDETMBEGA1UEBxMKU25h a2UgVG93bjEXMBUGA1UEChMOU25ha2UgT2lsLCBMdGQxFzAVBgNVBAsTDldlYnNl cnZlciBUZWFtMRkwFwYDVQQDExB3d3cuc25ha2VvaWwuZG9tMR8wHQYJKoZIhvcN AQkBFhB3d3dAc25ha2VvaWwuZG9tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQDH9Ge/s2zcH+da+rPTx/DPRp3xGjHZ4GG6pCmvADIEtBtKBFAcZ64n+Dy7Np8b vKR+yy5DGQiijsH1D/j8HlGE+q4TZ8OFk7BNBFazHxFbYI4OKMiCxdKzdif1yfaa lWoANFlAzlSdbxeGVHoT0K+gT5w3UxwZKv2DLbCTzLZyPwIDAQABoyYwJDAPBgNV HRMECDAGAQH/AgEAMBEGCWCGSAGG+EIBAQQEAwIAQDANBgkqhkiG9w0BAQQFAAOB gQAZUIHAL4D09oE6Lv2k56Gp38OBDuILvwLg1v1KL8mQR+KFjghCrtpqaztZqcDt 2q2QoyulCgSzHbEGmi0EsdkPfg6mp0penssIFePYNI+/8u9HT4LuKMJX15hxBam7 dUHzICxBVC1lnHyYGjDuAMhe396lYAn8bCld1/L4NMGBCQ== -----END CERTIFICATE----- ``` ### Certificate Authorities By verifying the information in a certificate request before granting the certificate, the Certificate Authority assures itself of the identity of the private key owner of a key-pair. For instance, if Alice requests a personal certificate, the Certificate Authority must first make sure that Alice really is the person the certificate request claims she is. #### Certificate Chains A Certificate Authority may also issue a certificate for another Certificate Authority. When examining a certificate, Alice may need to examine the certificate of the issuer, for each parent Certificate Authority, until reaching one which she has confidence in. She may decide to trust only certificates with a limited chain of issuers, to reduce her risk of a "bad" certificate in the chain. #### Creating a Root-Level CA As noted earlier, each certificate requires an issuer to assert the validity of the identity of the certificate subject, up to the top-level Certificate Authority (CA). This presents a problem: who can vouch for the certificate of the top-level authority, which has no issuer? In this unique case, the certificate is "self-signed", so the issuer of the certificate is the same as the subject. Browsers are preconfigured to trust well-known certificate authorities, but it is important to exercise extra care in trusting a self-signed certificate. The wide publication of a public key by the root authority reduces the risk in trusting this key -- it would be obvious if someone else publicized a key claiming to be the authority. A number of companies, such as [Thawte](http://www.thawte.com/) and [VeriSign](http://www.verisign.com/) have established themselves as Certificate Authorities. These companies provide the following services: * Verifying certificate requests * Processing certificate requests * Issuing and managing certificates It is also possible to create your own Certificate Authority. Although risky in the Internet environment, it may be useful within an Intranet where the organization can easily verify the identities of individuals and servers. #### Certificate Management Establishing a Certificate Authority is a responsibility which requires a solid administrative, technical and management framework. Certificate Authorities not only issue certificates, they also manage them -- that is, they determine for how long certificates remain valid, they renew them and keep lists of certificates that were issued in the past but are no longer valid (Certificate Revocation Lists, or CRLs). For example, if Alice is entitled to a certificate as an employee of a company but has now left that company, her certificate may need to be revoked. Because certificates are only issued after the subject's identity has been verified and can then be passed around to all those with whom the subject may communicate, it is impossible to tell from the certificate alone that it has been revoked. Therefore when examining certificates for validity it is necessary to contact the issuing Certificate Authority to check CRLs -- this is usually not an automated part of the process. **Note** If you use a Certificate Authority that browsers are not configured to trust by default, it is necessary to load the Certificate Authority certificate into the browser, enabling the browser to validate server certificates signed by that Certificate Authority. Doing so may be dangerous, since once loaded, the browser will accept all certificates signed by that Certificate Authority. Secure Sockets Layer (SSL) -------------------------- The Secure Sockets Layer protocol is a protocol layer which may be placed between a reliable connection-oriented network layer protocol (e.g. TCP/IP) and the application protocol layer (e.g. HTTP). SSL provides for secure communication between client and server by allowing mutual authentication, the use of digital signatures for integrity and encryption for privacy. The protocol is designed to support a range of choices for specific algorithms used for cryptography, digests and signatures. This allows algorithm selection for specific servers to be made based on legal, export or other concerns and also enables the protocol to take advantage of new algorithms. Choices are negotiated between client and server when establishing a protocol session. ### Table 4: Versions of the SSL protocol | Version | Source | Description | | --- | --- | --- | | SSL v2.0 | Vendor Standard (from Netscape Corp.) | First SSL protocol for which implementations exist | | SSL v3.0 | Expired Internet Draft (from Netscape Corp.) [[SSL3](#SSL3)] | Revisions to prevent specific security attacks, add non-RSA ciphers and support for certificate chains | | TLS v1.0 | Proposed Internet Standard (from IETF) [[TLS1](#TLS1)] | Revision of SSL 3.0 to update the MAC layer to HMAC, add block padding for block ciphers, message order standardization and more alert messages. | | TLS v1.1 | Proposed Internet Standard (from IETF) [[TLS11](#TLS11)] | Update of TLS 1.0 to add protection against Cipher block chaining (CBC) attacks. | | TLS v1.2 | Proposed Internet Standard (from IETF) [[TLS12](#TLS12)] | Update of TLS 1.1 deprecating MD5 as hash, and adding incompatibility to SSL so it will never negotiate the use of SSLv2. | There are a number of versions of the SSL protocol, as shown in [Table 4](#table4). As noted there, one of the benefits in SSL 3.0 is that it adds support of certificate chain loading. This feature allows a server to pass a server certificate along with issuer certificates to the browser. Chain loading also permits the browser to validate the server certificate, even if Certificate Authority certificates are not installed for the intermediate issuers, since they are included in the certificate chain. SSL 3.0 is the basis for the Transport Layer Security [[TLS](#TLS1)] protocol standard, currently in development by the Internet Engineering Task Force (IETF). ### Establishing a Session The SSL session is established by following a handshake sequence between client and server, as shown in [Figure 1](#figure1). This sequence may vary, depending on whether the server is configured to provide a server certificate or request a client certificate. Although cases exist where additional handshake steps are required for management of cipher information, this article summarizes one common scenario. See the SSL specification for the full range of possibilities. **Note** Once an SSL session has been established, it may be reused. This avoids the performance penalty of repeating the many steps needed to start a session. To do this, the server assigns each SSL session a unique session identifier which is cached in the server and which the client can use in future connections to reduce the handshake time (until the session identifier expires from the cache of the server). Figure 1: Simplified SSL Handshake Sequence The elements of the handshake sequence, as used by the client and server, are listed below: 1. Negotiate the Cipher Suite to be used during data transfer 2. Establish and share a session key between client and server 3. Optionally authenticate the server to the client 4. Optionally authenticate the client to the server The first step, Cipher Suite Negotiation, allows the client and server to choose a Cipher Suite supported by both of them. The SSL3.0 protocol specification defines 31 Cipher Suites. A Cipher Suite is defined by the following components: * Key Exchange Method * Cipher for Data Transfer * Message Digest for creating the Message Authentication Code (MAC) These three elements are described in the sections that follow. ### Key Exchange Method The key exchange method defines how the shared secret symmetric cryptography key used for application data transfer will be agreed upon by client and server. SSL 2.0 uses RSA key exchange only, while SSL 3.0 supports a choice of key exchange algorithms including RSA key exchange (when certificates are used), and Diffie-Hellman key exchange (for exchanging keys without certificates, or without prior communication between client and server). One variable in the choice of key exchange methods is digital signatures -- whether or not to use them, and if so, what kind of signatures to use. Signing with a private key provides protection against a man-in-the-middle-attack during the information exchange used to generating the shared key [[AC96](#AC96), p516]. ### Cipher for Data Transfer SSL uses conventional symmetric cryptography, as described earlier, for encrypting messages in a session. There are nine choices of how to encrypt, including the option not to encrypt: * No encryption * Stream Ciphers + RC4 with 40-bit keys + RC4 with 128-bit keys * CBC Block Ciphers + RC2 with 40 bit key + DES with 40 bit key + DES with 56 bit key + Triple-DES with 168 bit key + Idea (128 bit key) + Fortezza (96 bit key) "CBC" refers to Cipher Block Chaining, which means that a portion of the previously encrypted cipher text is used in the encryption of the current block. "DES" refers to the Data Encryption Standard [[AC96](#AC96), ch12], which has a number of variants (including DES40 and 3DES\_EDE). "Idea" is currently one of the best and cryptographically strongest algorithms available, and "RC2" is a proprietary algorithm from RSA DSI [[AC96](#AC96), ch13]. ### Digest Function The choice of digest function determines how a digest is created from a record unit. SSL supports the following: * No digest (Null choice) * MD5, a 128-bit hash * Secure Hash Algorithm (SHA-1), a 160-bit hash The message digest is used to create a Message Authentication Code (MAC) which is encrypted with the message to verify integrity and to protect against replay attacks. ### Handshake Sequence Protocol The handshake sequence uses three protocols: * The SSL Handshake Protocol for performing the client and server SSL session establishment. * The SSL Change Cipher Spec Protocol for actually establishing agreement on the Cipher Suite for the session. * The SSL Alert Protocol for conveying SSL error messages between client and server. These protocols, as well as application protocol data, are encapsulated in the SSL Record Protocol, as shown in [Figure 2](#figure2). An encapsulated protocol is transferred as data by the lower layer protocol, which does not examine the data. The encapsulated protocol has no knowledge of the underlying protocol. Figure 2: SSL Protocol Stack The encapsulation of SSL control protocols by the record protocol means that if an active session is renegotiated the control protocols will be transmitted securely. If there was no previous session, the Null cipher suite is used, which means there will be no encryption and messages will have no integrity digests, until the session has been established. ### Data Transfer The SSL Record Protocol, shown in [Figure 3](#figure3), is used to transfer application and SSL Control data between the client and server, where necessary fragmenting this data into smaller units, or combining multiple higher level protocol data messages into single units. It may compress, attach digest signatures, and encrypt these units before transmitting them using the underlying reliable transport protocol (Note: currently, no major SSL implementations include support for compression). Figure 3: SSL Record Protocol ### Securing HTTP Communication One common use of SSL is to secure Web HTTP communication between a browser and a webserver. This does not preclude the use of non-secured HTTP - the secure version (called HTTPS) is the same as plain HTTP over SSL, but uses the URL scheme `https` rather than `http`, and a different server port (by default, port 443). This functionality is a large part of what `[mod\_ssl](../mod/mod_ssl)` provides for the Apache webserver. References ---------- [AC96] Bruce Schneier, Applied Cryptography, 2nd Edition, Wiley, 1996. See <http://www.counterpane.com/> for various other materials by Bruce Schneier. [ASN1] ITU-T Recommendation X.208, Specification of Abstract Syntax Notation One (ASN.1), last updated 2008. See <http://www.itu.int/ITU-T/asn1/>. [X509] ITU-T Recommendation X.509, The Directory - Authentication Framework. For references, see <http://en.wikipedia.org/wiki/X.509>. [PKCS] Public Key Cryptography Standards (PKCS), RSA Laboratories Technical Notes, See <http://www.rsasecurity.com/rsalabs/pkcs/>. [MIME] N. Freed, N. Borenstein, Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies, RFC2045. See for instance <http://tools.ietf.org/html/rfc2045>. [SSL3] Alan O. Freier, Philip Karlton, Paul C. Kocher, The SSL Protocol Version 3.0, 1996. See <http://www.netscape.com/eng/ssl3/draft302.txt>. [TLS1] Tim Dierks, Christopher Allen, The TLS Protocol Version 1.0, 1999. See <http://ietf.org/rfc/rfc2246.txt>. [TLS11] The TLS Protocol Version 1.1, 2006. See <http://tools.ietf.org/html/rfc4346>. [TLS12] The TLS Protocol Version 1.2, 2008. See <http://tools.ietf.org/html/rfc5246>.
programming_docs
apache_http_server SSL/TLS Strong Encryption: Compatibility SSL/TLS Strong Encryption: Compatibility ======================================== This page covers backwards compatibility between mod\_ssl and other SSL solutions. mod\_ssl is not the only SSL solution for Apache; four additional products are (or were) also available: Ben Laurie's freely available [Apache-SSL](http://www.apache-ssl.org/) (from where mod\_ssl were originally derived in 1998), Red Hat's commercial Secure Web Server (which was based on mod\_ssl), Covalent's commercial Raven SSL Module (also based on mod\_ssl) and finally C2Net's (now Red Hat's) commercial product [Stronghold](http://www.redhat.com/explore/stronghold/) (based on a different evolution branch, named Sioux up to Stronghold 2.x, and based on mod\_ssl since Stronghold 3.x). mod\_ssl mostly provides a superset of the functionality of all the other solutions, so it's simple to migrate from one of the older modules to mod\_ssl. The configuration directives and environment variable names used by the older SSL solutions vary from those used in mod\_ssl; mapping tables are included here to give the equivalents used by mod\_ssl. Configuration Directives ------------------------ The mapping between configuration directives used by Apache-SSL 1.x and mod\_ssl 2.0.x is given in [Table 1](#table1). The mapping from Sioux 1.x and Stronghold 2.x is only partial because of special functionality in these interfaces which mod\_ssl doesn't provide. ### Table 1: Configuration Directive Mapping | Old Directive | mod\_ssl Directive | Comment | | --- | --- | --- | | Apache-SSL 1.x & mod\_ssl 2.0.x compatibility: | | `SSLEnable` | ``` SSLEngine on ``` | compactified | | `SSLDisable` | ``` SSLEngine off ``` | compactified | | `SSLLogFile` *file* | | Use per-module `[LogLevel](../mod/core#loglevel)` setting instead. | | `SSLRequiredCiphers` *spec* | `SSLCipherSuite` *spec* | renamed | | `SSLRequireCipher` *c1* ... | `SSLRequire %{SSL_CIPHER} in {"`*c1*`", ...}` | generalized | | `SSLBanCipher` *c1* ... | `SSLRequire not (%{SSL_CIPHER} in {"`*c1*`", ...})` | generalized | | `SSLFakeBasicAuth` | ``` SSLOptions +FakeBasicAuth ``` | merged | | `SSLCacheServerPath` *dir* | - | functionality removed | | `SSLCacheServerPort` *integer* | - | functionality removed | | Apache-SSL 1.x compatibility: | | `SSLExportClientCertificates` | ``` SSLOptions +ExportCertData ``` | merged | | `SSLCacheServerRunDir` *dir* | - | functionality not supported | | Sioux 1.x compatibility: | | `SSL_CertFile` *file* | `SSLCertificateFile` *file* | renamed | | `SSL_KeyFile` *file* | `SSLCertificateKeyFile` *file* | renamed | | `SSL_CipherSuite` *arg* | `SSLCipherSuite` *arg* | renamed | | `SSL_X509VerifyDir` *arg* | `SSLCACertificatePath` *arg* | renamed | | `SSL_Log` *file* | `-` | Use per-module `[LogLevel](../mod/core#loglevel)` setting instead. | | `SSL_Connect` *flag* | `SSLEngine` *flag* | renamed | | `SSL_ClientAuth` *arg* | `SSLVerifyClient` *arg* | renamed | | `SSL_X509VerifyDepth` *arg* | `SSLVerifyDepth` *arg* | renamed | | `SSL_FetchKeyPhraseFrom` *arg* | - | not directly mappable; use SSLPassPhraseDialog | | `SSL_SessionDir` *dir* | - | not directly mappable; use SSLSessionCache | | `SSL_Require` *expr* | - | not directly mappable; use SSLRequire | | `SSL_CertFileType` *arg* | - | functionality not supported | | `SSL_KeyFileType` *arg* | - | functionality not supported | | `SSL_X509VerifyPolicy` *arg* | - | functionality not supported | | `SSL_LogX509Attributes` *arg* | - | functionality not supported | | Stronghold 2.x compatibility: | | `StrongholdAccelerator` *engine* | `SSLCryptoDevice` *engine* | renamed | | `StrongholdKey` *dir* | - | functionality not needed | | `StrongholdLicenseFile` *dir* | - | functionality not needed | | `SSLFlag` *flag* | `SSLEngine` *flag* | renamed | | `SSLSessionLockFile` *file* | `SSLMutex` *file* | renamed | | `SSLCipherList` *spec* | `SSLCipherSuite` *spec* | renamed | | `RequireSSL` | `SSLRequireSSL` | renamed | | `SSLErrorFile` *file* | - | functionality not supported | | `SSLRoot` *dir* | - | functionality not supported | | `SSL_CertificateLogDir` *dir* | - | functionality not supported | | `AuthCertDir` *dir* | - | functionality not supported | | `SSL_Group` *name* | - | functionality not supported | | `SSLProxyMachineCertPath` *dir* | `SSLProxyMachineCertificatePath` *dir* | renamed | | `SSLProxyMachineCertFile` *file* | `SSLProxyMachineCertificateFile` *file* | renamed | | `SSLProxyCipherList` *spec* | `SSLProxyCipherSpec` *spec* | renamed | Environment Variables --------------------- The mapping between environment variable names used by the older SSL solutions and the names used by mod\_ssl is given in [Table 2](#table2). ### Table 2: Environment Variable Derivation | Old Variable | mod\_ssl Variable | Comment | | --- | --- | --- | | `SSL_PROTOCOL_VERSION` | `SSL_PROTOCOL` | renamed | | `SSLEAY_VERSION` | `SSL_VERSION_LIBRARY` | renamed | | `HTTPS_SECRETKEYSIZE` | `SSL_CIPHER_USEKEYSIZE` | renamed | | `HTTPS_KEYSIZE` | `SSL_CIPHER_ALGKEYSIZE` | renamed | | `HTTPS_CIPHER` | `SSL_CIPHER` | renamed | | `HTTPS_EXPORT` | `SSL_CIPHER_EXPORT` | renamed | | `SSL_SERVER_KEY_SIZE` | `SSL_CIPHER_ALGKEYSIZE` | renamed | | `SSL_SERVER_CERTIFICATE` | `SSL_SERVER_CERT` | renamed | | `SSL_SERVER_CERT_START` | `SSL_SERVER_V_START` | renamed | | `SSL_SERVER_CERT_END` | `SSL_SERVER_V_END` | renamed | | `SSL_SERVER_CERT_SERIAL` | `SSL_SERVER_M_SERIAL` | renamed | | `SSL_SERVER_SIGNATURE_ALGORITHM` | `SSL_SERVER_A_SIG` | renamed | | `SSL_SERVER_DN` | `SSL_SERVER_S_DN` | renamed | | `SSL_SERVER_CN` | `SSL_SERVER_S_DN_CN` | renamed | | `SSL_SERVER_EMAIL` | `SSL_SERVER_S_DN_Email` | renamed | | `SSL_SERVER_O` | `SSL_SERVER_S_DN_O` | renamed | | `SSL_SERVER_OU` | `SSL_SERVER_S_DN_OU` | renamed | | `SSL_SERVER_C` | `SSL_SERVER_S_DN_C` | renamed | | `SSL_SERVER_SP` | `SSL_SERVER_S_DN_SP` | renamed | | `SSL_SERVER_L` | `SSL_SERVER_S_DN_L` | renamed | | `SSL_SERVER_IDN` | `SSL_SERVER_I_DN` | renamed | | `SSL_SERVER_ICN` | `SSL_SERVER_I_DN_CN` | renamed | | `SSL_SERVER_IEMAIL` | `SSL_SERVER_I_DN_Email` | renamed | | `SSL_SERVER_IO` | `SSL_SERVER_I_DN_O` | renamed | | `SSL_SERVER_IOU` | `SSL_SERVER_I_DN_OU` | renamed | | `SSL_SERVER_IC` | `SSL_SERVER_I_DN_C` | renamed | | `SSL_SERVER_ISP` | `SSL_SERVER_I_DN_SP` | renamed | | `SSL_SERVER_IL` | `SSL_SERVER_I_DN_L` | renamed | | `SSL_CLIENT_CERTIFICATE` | `SSL_CLIENT_CERT` | renamed | | `SSL_CLIENT_CERT_START` | `SSL_CLIENT_V_START` | renamed | | `SSL_CLIENT_CERT_END` | `SSL_CLIENT_V_END` | renamed | | `SSL_CLIENT_CERT_SERIAL` | `SSL_CLIENT_M_SERIAL` | renamed | | `SSL_CLIENT_SIGNATURE_ALGORITHM` | `SSL_CLIENT_A_SIG` | renamed | | `SSL_CLIENT_DN` | `SSL_CLIENT_S_DN` | renamed | | `SSL_CLIENT_CN` | `SSL_CLIENT_S_DN_CN` | renamed | | `SSL_CLIENT_EMAIL` | `SSL_CLIENT_S_DN_Email` | renamed | | `SSL_CLIENT_O` | `SSL_CLIENT_S_DN_O` | renamed | | `SSL_CLIENT_OU` | `SSL_CLIENT_S_DN_OU` | renamed | | `SSL_CLIENT_C` | `SSL_CLIENT_S_DN_C` | renamed | | `SSL_CLIENT_SP` | `SSL_CLIENT_S_DN_SP` | renamed | | `SSL_CLIENT_L` | `SSL_CLIENT_S_DN_L` | renamed | | `SSL_CLIENT_IDN` | `SSL_CLIENT_I_DN` | renamed | | `SSL_CLIENT_ICN` | `SSL_CLIENT_I_DN_CN` | renamed | | `SSL_CLIENT_IEMAIL` | `SSL_CLIENT_I_DN_Email` | renamed | | `SSL_CLIENT_IO` | `SSL_CLIENT_I_DN_O` | renamed | | `SSL_CLIENT_IOU` | `SSL_CLIENT_I_DN_OU` | renamed | | `SSL_CLIENT_IC` | `SSL_CLIENT_I_DN_C` | renamed | | `SSL_CLIENT_ISP` | `SSL_CLIENT_I_DN_SP` | renamed | | `SSL_CLIENT_IL` | `SSL_CLIENT_I_DN_L` | renamed | | `SSL_EXPORT` | `SSL_CIPHER_EXPORT` | renamed | | `SSL_KEYSIZE` | `SSL_CIPHER_ALGKEYSIZE` | renamed | | `SSL_SECKEYSIZE` | `SSL_CIPHER_USEKEYSIZE` | renamed | | `SSL_SSLEAY_VERSION` | `SSL_VERSION_LIBRARY` | renamed | | `SSL_STRONG_CRYPTO` | `-` | Not supported by mod\_ssl | | `SSL_SERVER_KEY_EXP` | `-` | Not supported by mod\_ssl | | `SSL_SERVER_KEY_ALGORITHM` | `-` | Not supported by mod\_ssl | | `SSL_SERVER_KEY_SIZE` | `-` | Not supported by mod\_ssl | | `SSL_SERVER_SESSIONDIR` | `-` | Not supported by mod\_ssl | | `SSL_SERVER_CERTIFICATELOGDIR` | `-` | Not supported by mod\_ssl | | `SSL_SERVER_CERTFILE` | `-` | Not supported by mod\_ssl | | `SSL_SERVER_KEYFILE` | `-` | Not supported by mod\_ssl | | `SSL_SERVER_KEYFILETYPE` | `-` | Not supported by mod\_ssl | | `SSL_CLIENT_KEY_EXP` | `-` | Not supported by mod\_ssl | | `SSL_CLIENT_KEY_ALGORITHM` | `-` | Not supported by mod\_ssl | | `SSL_CLIENT_KEY_SIZE` | `-` | Not supported by mod\_ssl | Custom Log Functions -------------------- When mod\_ssl is enabled, additional functions exist for the [Custom Log Format](../mod/mod_log_config#formats) of `[mod\_log\_config](../mod/mod_log_config)` as documented in the Reference Chapter. Beside the ```%{`*varname*`}x`'' eXtension format function which can be used to expand any variables provided by any module, an additional Cryptography ```%{`*name*`}c`'' cryptography format function exists for backward compatibility. The currently implemented function calls are listed in [Table 3](#table3). ### Table 3: Custom Log Cryptography Function | Function Call | Description | | --- | --- | | `%...{version}c` | SSL protocol version | | `%...{cipher}c` | SSL cipher | | `%...{subjectdn}c` | Client Certificate Subject Distinguished Name | | `%...{issuerdn}c` | Client Certificate Issuer Distinguished Name | | `%...{errcode}c` | Certificate Verification Error (numerical) | | `%...{errstr}c` | Certificate Verification Error (string) | apache_http_server SSL/TLS Strong Encryption: How-To SSL/TLS Strong Encryption: How-To ================================= This document is intended to get you started, and get a few things working. You are strongly encouraged to read the rest of the SSL documentation, and arrive at a deeper understanding of the material, before progressing to the advanced techniques. Basic Configuration Example --------------------------- Your SSL configuration will need to contain, at minimum, the following directives. ``` LoadModule ssl_module modules/mod_ssl.so Listen 443 <VirtualHost *:443> ServerName www.example.com SSLEngine on SSLCertificateFile "/path/to/www.example.com.cert" SSLCertificateKeyFile "/path/to/www.example.com.key" </VirtualHost> ``` Cipher Suites and Enforcing Strong Security ------------------------------------------- * [How can I create an SSL server which accepts strong encryption only?](#onlystrong) * [How can I create an SSL server which accepts all types of ciphers in general, but requires a strong cipher for access to a particular URL?](#strongurl) ### How can I create an SSL server which accepts strong encryption only? The following enables only the strongest ciphers: ``` SSLCipherSuite HIGH:!aNULL:!MD5 ``` While with the following configuration you specify a preference for specific speed-optimized ciphers (which will be selected by mod\_ssl, provided that they are supported by the client): ``` SSLCipherSuite RC4-SHA:AES128-SHA:HIGH:!aNULL:!MD5 SSLHonorCipherOrder on ``` ### How can I create an SSL server which accepts all types of ciphers in general, but requires a strong ciphers for access to a particular URL? Obviously, a server-wide `[SSLCipherSuite](../mod/mod_ssl#sslciphersuite)` which restricts ciphers to the strong variants, isn't the answer here. However, `[mod\_ssl](../mod/mod_ssl)` can be reconfigured within `Location` blocks, to give a per-directory solution, and can automatically force a renegotiation of the SSL parameters to meet the new configuration. This can be done as follows: ``` # be liberal in general SSLCipherSuite ALL:!aNULL:RC4+RSA:+HIGH:+MEDIUM:+LOW:+EXP:+eNULL <Location "/strong/area"> # but https://hostname/strong/area/ and below # requires strong ciphers SSLCipherSuite HIGH:!aNULL:!MD5 </Location> ``` OCSP Stapling ------------- The Online Certificate Status Protocol (OCSP) is a mechanism for determining whether or not a server certificate has been revoked, and OCSP Stapling is a special form of this in which the server, such as httpd and mod\_ssl, maintains current OCSP responses for its certificates and sends them to clients which communicate with the server. Most certificates contain the address of an OCSP responder maintained by the issuing Certificate Authority, and mod\_ssl can communicate with that responder to obtain a signed response that can be sent to clients communicating with the server. Because the client can obtain the certificate revocation status from the server, without requiring an extra connection from the client to the Certificate Authority, OCSP Stapling is the preferred way for the revocation status to be obtained. Other benefits of eliminating the communication between clients and the Certificate Authority are that the client browsing history is not exposed to the Certificate Authority and obtaining status is more reliable by not depending on potentially heavily loaded Certificate Authority servers. Because the response obtained by the server can be reused for all clients using the same certificate during the time that the response is valid, the overhead for the server is minimal. Once general SSL support has been configured properly, enabling OCSP Stapling generally requires only very minor modifications to the httpd configuration — the addition of these two directives: ``` SSLUseStapling On SSLStaplingCache "shmcb:logs/ssl_stapling(32768)" ``` These directives are placed at global scope (i.e., not within a virtual host definition) wherever other global SSL configuration directives are placed, such as in `conf/extra/httpd-ssl.conf` for normal open source builds of httpd, `/etc/apache2/mods-enabled/ssl.conf` for the Ubuntu or Debian-bundled httpd, etc. The path on the `SSLStaplingCache` directive (e.g., `logs/`) should match the one on the `SSLSessionCache` directive. This path is relative to `ServerRoot`. This particular `SSLStaplingCache` directive requires `[mod\_socache\_shmcb](../mod/mod_socache_shmcb)` (from the `shmcb` prefix on the directive's argument). This module is usually enabled already for `SSLSessionCache` or on behalf of some module other than `[mod\_ssl](../mod/mod_ssl)`. If you enabled an SSL session cache using a mechanism other than `[mod\_socache\_shmcb](../mod/mod_socache_shmcb)`, use that alternative mechanism for `SSLStaplingCache` as well. For example: ``` SSLSessionCache "dbm:logs/ssl_scache" SSLStaplingCache "dbm:logs/ssl_stapling" ``` You can use the openssl command-line program to verify that an OCSP response is sent by your server: ``` $ openssl s_client -connect www.example.com:443 -status -servername www.example.com ... OCSP response: ====================================== OCSP Response Data: OCSP Response Status: successful (0x0) Response Type: Basic OCSP Response ... Cert Status: Good ... ``` The following sections highlight the most common situations which require further modification to the configuration. Refer also to the `[mod\_ssl](../mod/mod_ssl)` reference manual. ### If more than a few SSL certificates are used for the server OCSP responses are stored in the SSL stapling cache. While the responses are typically a few hundred to a few thousand bytes in size, mod\_ssl supports OCSP responses up to around 10K bytes in size. With more than a few certificates, the stapling cache size (32768 bytes in the example above) may need to be increased. Error message AH01929 will be logged in case of an error storing a response. ### If the certificate does not point to an OCSP responder, or if a different address must be used Refer to the `[SSLStaplingForceURL](../mod/mod_ssl#sslstaplingforceurl)` directive. You can confirm that a server certificate points to an OCSP responder using the openssl command-line program, as follows: ``` $ openssl x509 -in ./www.example.com.crt -text | grep 'OCSP.*http' OCSP - URI:http://ocsp.example.com ``` If the OCSP URI is provided and the web server can communicate to it directly without using a proxy, no configuration is required. Note that firewall rules that control outbound connections from the web server may need to be adjusted. If no OCSP URI is provided, contact your Certificate Authority to determine if one is available; if so, configure it with `[SSLStaplingForceURL](../mod/mod_ssl#sslstaplingforceurl)` in the virtual host that uses the certificate. ### If multiple SSL-enabled virtual hosts are configured and OCSP Stapling should be disabled for some Add `SSLUseStapling Off` to the virtual hosts for which OCSP Stapling should be disabled. ### If the OCSP responder is slow or unreliable Several directives are available to handle timeouts and errors. Refer to the documentation for the `[SSLStaplingFakeTryLater](../mod/mod_ssl#sslstaplingfaketrylater)`, `[SSLStaplingResponderTimeout](../mod/mod_ssl#sslstaplingrespondertimeout)`, and `[SSLStaplingReturnResponderErrors](../mod/mod_ssl#sslstaplingreturnrespondererrors)` directives. ### If mod\_ssl logs error AH02217 ``` AH02217: ssl_stapling_init_cert: Can't retrieve issuer certificate! ``` In order to support OCSP Stapling when a particular server certificate is used, the certificate chain for that certificate must be configured. If it was not configured as part of enabling SSL, the AH02217 error will be issued when stapling is enabled, and an OCSP response will not be provided for clients using the certificate. Refer to the `[SSLCertificateChainFile](../mod/mod_ssl#sslcertificatechainfile)` and `[SSLCertificateFile](../mod/mod_ssl#sslcertificatefile)` for instructions for configuring the certificate chain. Client Authentication and Access Control ---------------------------------------- * [How can I force clients to authenticate using certificates?](#allclients) * [How can I force clients to authenticate using certificates for a particular URL, but still allow arbitrary clients to access the rest of the server?](#arbitraryclients) * [How can I allow only clients who have certificates to access a particular URL, but allow all clients to access the rest of the server?](#certauthenticate) * [How can I require HTTPS with strong ciphers, and either basic authentication or client certificates, for access to part of the Intranet website, for clients coming from the Internet?](#intranet) ### How can I force clients to authenticate using certificates? When you know all of your users (eg, as is often the case on a corporate Intranet), you can require plain certificate authentication. All you need to do is to create client certificates signed by your own CA certificate (`ca.crt`) and then verify the clients against this certificate. ``` # require a client certificate which has to be directly # signed by our CA certificate in ca.crt SSLVerifyClient require SSLVerifyDepth 1 SSLCACertificateFile "conf/ssl.crt/ca.crt" ``` ### How can I force clients to authenticate using certificates for a particular URL, but still allow arbitrary clients to access the rest of the server? To force clients to authenticate using certificates for a particular URL, you can use the per-directory reconfiguration features of `[mod\_ssl](../mod/mod_ssl)`: ``` SSLVerifyClient none SSLCACertificateFile "conf/ssl.crt/ca.crt" <Location "/secure/area"> SSLVerifyClient require SSLVerifyDepth 1 </Location> ``` ### How can I allow only clients who have certificates to access a particular URL, but allow all clients to access the rest of the server? The key to doing this is checking that part of the client certificate matches what you expect. Usually this means checking all or part of the Distinguished Name (DN), to see if it contains some known string. There are two ways to do this, using either `[mod\_auth\_basic](../mod/mod_auth_basic)` or `[SSLRequire](../mod/mod_ssl#sslrequire)`. The `[mod\_auth\_basic](../mod/mod_auth_basic)` method is generally required when the certificates are completely arbitrary, or when their DNs have no common fields (usually the organisation, etc.). In this case, you should establish a password database containing *all* clients allowed, as follows: ``` SSLVerifyClient none SSLCACertificateFile "conf/ssl.crt/ca.crt" SSLCACertificatePath "conf/ssl.crt" <Directory "/usr/local/apache2/htdocs/secure/area"> SSLVerifyClient require SSLVerifyDepth 5 SSLOptions +FakeBasicAuth SSLRequireSSL AuthName "Snake Oil Authentication" AuthType Basic AuthBasicProvider file AuthUserFile "/usr/local/apache2/conf/httpd.passwd" Require valid-user </Directory> ``` The password used in this example is the DES encrypted string "password". See the `[SSLOptions](../mod/mod_ssl#ssloptions)` docs for more information. ### httpd.passwd ``` /C=DE/L=Munich/O=Snake Oil, Ltd./OU=Staff/CN=Foo:xxj31ZMTZzkVA /C=US/L=S.F./O=Snake Oil, Ltd./OU=CA/CN=Bar:xxj31ZMTZzkVA /C=US/L=L.A./O=Snake Oil, Ltd./OU=Dev/CN=Quux:xxj31ZMTZzkVA ``` When your clients are all part of a common hierarchy, which is encoded into the DN, you can match them more easily using `[SSLRequire](../mod/mod_ssl#sslrequire)`, as follows: ``` SSLVerifyClient none SSLCACertificateFile "conf/ssl.crt/ca.crt" SSLCACertificatePath "conf/ssl.crt" <Directory "/usr/local/apache2/htdocs/secure/area"> SSLVerifyClient require SSLVerifyDepth 5 SSLOptions +FakeBasicAuth SSLRequireSSL SSLRequire %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \ and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} </Directory> ``` ### How can I require HTTPS with strong ciphers, and either basic authentication or client certificates, for access to part of the Intranet website, for clients coming from the Internet? I still want to allow plain HTTP access for clients on the Intranet. These examples presume that clients on the Intranet have IPs in the range 192.168.1.0/24, and that the part of the Intranet website you want to allow internet access to is `/usr/local/apache2/htdocs/subarea`. This configuration should remain outside of your HTTPS virtual host, so that it applies to both HTTPS and HTTP. ``` SSLCACertificateFile "conf/ssl.crt/company-ca.crt" <Directory "/usr/local/apache2/htdocs"> # Outside the subarea only Intranet access is granted Require ip 192.168.1.0/24 </Directory> <Directory "/usr/local/apache2/htdocs/subarea"> # Inside the subarea any Intranet access is allowed # but from the Internet only HTTPS + Strong-Cipher + Password # or the alternative HTTPS + Strong-Cipher + Client-Certificate # If HTTPS is used, make sure a strong cipher is used. # Additionally allow client certs as alternative to basic auth. SSLVerifyClient optional SSLVerifyDepth 1 SSLOptions +FakeBasicAuth +StrictRequire SSLRequire %{SSL_CIPHER_USEKEYSIZE} >= 128 # Force clients from the Internet to use HTTPS RewriteEngine on RewriteCond "%{REMOTE_ADDR}" "!^192\.168\.1\.[0-9]+$" RewriteCond "%{HTTPS}" "!=on" RewriteRule "." "-" [F] # Allow Network Access and/or Basic Auth Satisfy any # Network Access Control Require ip 192.168.1.0/24 # HTTP Basic Authentication AuthType basic AuthName "Protected Intranet Area" AuthBasicProvider file AuthUserFile "conf/protected.passwd" Require valid-user </Directory> ``` Logging ------- `[mod\_ssl](../mod/mod_ssl)` can log extremely verbose debugging information to the error log, when its `[LogLevel](../mod/core#loglevel)` is set to the higher trace levels. On the other hand, on a very busy server, level `info` may already be too much. Remember that you can configure the `[LogLevel](../mod/core#loglevel)` per module to suite your needs.
programming_docs
apache_http_server Platform Specific Notes Platform Specific Notes ======================= Microsoft Windows ----------------- Using Apache This document explains how to install, configure and run Apache 2.4 under Microsoft Windows. See: [Using Apache with Microsoft Windows](windows) Compiling Apache There are many important points before you begin compiling Apache. This document explain them. See: [Compiling Apache for Microsoft Windows](win_compiling) Unix Systems ------------ RPM Based Systems (Redhat / CentOS / Fedora) This document explains how to build, install, and run Apache 2.4 on systems supporting the RPM packaging format. See: [Using Apache With RPM Based Systems](rpm) Other Platforms --------------- Novell NetWare This document explains how to install, configure and run Apache 2.4 under Novell NetWare 5.1 and above. See: [Using Apache With Novell NetWare](netware) EBCDIC Version 1.3 of the Apache HTTP Server is the first version which includes a port to a (non-ASCII) mainframe machine which uses the EBCDIC character set as its native codeset. **Warning:** This document has not been updated to take into account changes made in the 2.4 version of the Apache HTTP Server. Some of the information may still be relevant, but please use it with care. See: [The Apache EBCDIC Port](ebcdic) apache_http_server Compiling Apache for Microsoft Windows Compiling Apache for Microsoft Windows ====================================== There are many important points to consider before you begin compiling Apache HTTP Server (httpd). See [Using Apache HTTP Server on Microsoft Windows](windows) before you begin. httpd can be built on Windows using a cmake-based build system or with Visual Studio project files maintained by httpd developers. The cmake-based build system directly supports more versions of Visual Studio but currently has considerable functional limitations. Building httpd with the included Visual Studio project files ------------------------------------------------------------ ### Requirements Compiling Apache requires the following environment to be properly installed: * Disk Space Make sure you have at least 200 MB of free disk space available. After installation Apache requires approximately 80 MB of disk space, plus space for log and cache files, which can grow rapidly. The actual disk space requirements will vary considerably based on your chosen configuration and any third-party modules or libraries, especially when OpenSSL is also built. Because many files are text and very easily compressed, NTFS filesystem compression cuts these requirements in half. * Appropriate Patches The httpd binary is built with the help of several patches to third party packages, which ensure the released code is buildable and debuggable. These patches are available and distributed from <http://www.apache.org/dist/httpd/binaries/win32/patches_applied/> and are recommended to be applied to obtain identical results as the "official" ASF distributed binaries. * Microsoft Visual C++ 6.0 (Visual Studio 97) or later. Apache can be built using the command line tools, or from within the Visual Studio IDE Workbench. The command line build requires the environment to reflect the `PATH`, `INCLUDE`, `LIB` and other variables that can be configured with the `vcvars32.bat` script. You may want the Visual Studio Processor Pack for your older version of Visual Studio, or a full (not Express) version of newer Visual Studio editions, for the ml.exe assembler. This will allow you to build OpenSSL, if desired, using the more efficient assembly code implementation. Only the Microsoft compiler tool chain is actively supported by the active httpd contributors. Although the project regularly accepts patches to ensure MinGW and other alternative builds work and improve upon them, they are not actively maintained and are often broken in the course of normal development. * Updated Microsoft Windows Platform SDK, February 2003 or later. An appropriate Windows Platform SDK is included by default in the full (not express/lite) versions of Visual C++ 7.1 (Visual Studio 2002) and later, these users can ignore these steps unless explicitly choosing a newer or different version of the Platform SDK. To use Visual C++ 6.0 or 7.0 (Studio 2000 .NET), the Platform SDK environment must be prepared using the `setenv.bat` script (installed by the Platform SDK) before starting the command line build or launching the msdev/devenv GUI environment. Installing the Platform SDK for Visual Studio Express versions (2003 and later) should adjust the default environment appropriately. ``` "c:\Program Files\Microsoft Visual Studio\VC98\Bin\VCVARS32" "c:\Program Files\Platform SDK\setenv.bat" ``` * Perl and awk Several steps recommended here require a perl interpreter during the build preparation process, but it is otherwise not required. To install Apache within the build system, several files are modified using the `awk.exe` utility. awk was chosen since it is a very small download (compared with Perl or WSH/VB) and accomplishes the task of modifying configuration files upon installation. Brian Kernighan's <http://www.cs.princeton.edu/~bwk/btl.mirror/> site has a compiled native Win32 binary, <http://www.cs.princeton.edu/~bwk/btl.mirror/awk95.exe> which you must save with the name `awk.exe` (rather than `awk95.exe`). If awk.exe is not found, Makefile.win's install target will not perform substitutions in the installed .conf files. You must manually modify the installed .conf files to allow the server to start. Search and replace all "@token@" tags as appropriate. The Visual Studio IDE will only find `awk.exe` from the PATH, or executable path specified in the menu option Tools -> Options -> (Projects ->) Directories. Ensure awk.exe is in your system path. Also note that if you are using Cygwin tools (<http://www.cygwin.com/>) the awk utility is named `gawk.exe` and that the file `awk.exe` is really a symlink to the `gawk.exe` file. The Windows command shell does not recognize symlinks, and because of this building InstallBin will fail. A workaround is to delete `awk.exe` from the cygwin installation and copy `gawk.exe` to `awk.exe`. Also note the cygwin/mingw ports of gawk 3.0.x were buggy, please upgrade to 3.1.x before attempting to use any gawk port. * [Optional] zlib library (for `[mod\_deflate](../mod/mod_deflate)`) Zlib must be installed into a `srclib` subdirectory named `zlib`. This must be built in-place. Zlib can be obtained from <http://www.zlib.net/> -- the `[mod\_deflate](../mod/mod_deflate)` is confirmed to work correctly with version 1.2.3. ``` nmake -f win32\Makefile.msc nmake -f win32\Makefile.msc test ``` * [Optional] OpenSSL libraries (for `[mod\_ssl](../mod/mod_ssl)` and `ab.exe` with ssl support) The OpenSSL library is cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted. See <http://www.wassenaar.org/> for more information. Configuring and building OpenSSL requires perl to be installed. OpenSSL must be installed into a `srclib` subdirectory named `openssl`, obtained from <http://www.openssl.org/source/>, in order to compile `[mod\_ssl](../mod/mod_ssl)` or the `abs.exe` project, which is ab.c with SSL support enabled. To prepare OpenSSL to be linked to Apache mod\_ssl or abs.exe, and disable patent encumbered features in OpenSSL, you might use the following build commands: ``` perl Configure no-rc5 no-idea enable-mdc2 enable-zlib VC-WIN32 -Ipath/to/srclib/zlib -Lpath/to/srclib/zlib ms\do_masm.bat nmake -f ms\ntdll.mak ``` It is not advisable to use zlib-dynamic, as that transfers the cost of deflating SSL streams to the first request which must load the zlib dll. Note the suggested patch enables the -L flag to work with windows builds, corrects the name of zdll.lib and ensures .pdb files are generated for troubleshooting. If the assembler is not installed, you would add no-asm above and use ms\do\_ms.bat instead of the ms\do\_masm.bat script. * [Optional] Database libraries (for `[mod\_dbd](../mod/mod_dbd)` and `[mod\_authn\_dbm](../mod/mod_authn_dbm)`) The apr-util library exposes dbm (keyed database) and dbd (query oriented database) client functionality to the httpd server and its modules, such as authentication and authorization. The sdbm dbm and odbc dbd providers are compiled unconditionally. The dbd support includes the Oracle instantclient package, MySQL, PostgreSQL and sqlite. To build these all, for example, set up the LIB to include the library path, INCLUDE to include the headers path, and PATH to include the dll bin path of all four SDK's, and set the DBD\_LIST environment variable to inform the build which client driver SDKs are installed correctly, e.g.; ``` set DBD_LIST=sqlite3 pgsql oracle mysql ``` Similarly, the dbm support can be extended with DBM\_LIST to build a Berkeley DB provider (db) and/or gdbm provider, by similarly configuring LIB, INCLUDE and PATH first to ensure the client library libs and headers are available. ``` set DBM_LIST=db gdbm ``` Depending on the choice of database distributions, it may be necessary to change the actual link target name (e.g. gdbm.lib vs. libgdb.lib) that are listed in the corresponding .dsp/.mak files within the directories srclib\apr-util\dbd or ...\dbm. See the README-win32.txt file for more hints on obtaining the various database driver SDKs. ### Building from Unix sources The policy of the Apache HTTP Server project is to only release Unix sources. Windows source packages made available for download have been supplied by volunteers and may not be available for every release. You can still build the server on Windows from the Unix source tarball with just a few additional steps. 1. Download and unpack the Unix source tarball for the latest version. 2. Download and unpack the Unix source tarball for latest version of APR, AR-Util and APR-Iconv, place these sources in directories httpd-2.x.x\srclib\apr, httpd-2.x.x\srclib\apr-util and httpd-2.x.x\srclib\apr-iconv 3. Open a Command Prompt and CD to the httpd-2.x.x folder 4. Run the line endings conversion utility at the prompt; ``` perl srclib\apr\build\lineends.pl ``` You can now build the server with the Visual Studio development environment using the IDE. Command-Line builds of the server are not possible from Unix sources unless you export .mak files as explained below. ### Command-Line Build `Makefile.win` is the top level Apache makefile. To compile Apache on Windows, simply use one of the following commands to build the `release` or `debug` flavor: ``` nmake /f Makefile.win _apacher nmake /f Makefile.win _apached ``` Either command will compile Apache. The latter will disable optimization of the resulting files, making it easier to single step the code to find bugs and track down problems. You can add your apr-util dbd and dbm provider choices with the additional make (environment) variables DBD\_LIST and DBM\_LIST, see the comments about [Optional] Database libraries, above. Review the initial comments in Makefile.win for additional options that can be provided when invoking the build. ### Developer Studio Workspace IDE Build Apache can also be compiled using VC++'s Visual Studio development environment. To simplify this process, a Visual Studio workspace, `Apache.dsw`, is provided. This workspace exposes the entire list of working `.dsp` projects that are required for the complete Apache binary release. It includes dependencies between the projects to assure that they are built in the appropriate order. Open the `Apache.dsw` workspace, and select `InstallBin` (`Release` or `Debug` build, as desired) as the Active Project. `InstallBin` causes all related project to be built, and then invokes `Makefile.win` to move the compiled executables and dlls. You may personalize the `INSTDIR=` choice by changing `InstallBin`'s Settings, General tab, Build command line entry. `INSTDIR` defaults to the `/Apache2` directory. If you only want a test compile (without installing) you may build the `BuildBin` project instead. The `.dsp` project files are distributed in Visual Studio 6.0 (98) format. Visual C++ 5.0 (97) will recognize them. Visual Studio 2002 (.NET) and later users must convert `Apache.dsw` plus the `.dsp` files into an `Apache.sln` plus `.msproj` files. Be sure you reconvert the `.msproj` file again if its source `.dsp` file changes! This is really trivial, just open `Apache.dsw` in the VC++ 7.0 IDE once again and reconvert. There is a flaw in the .vcproj conversion of .dsp files. devenv.exe will mis-parse the /D flag for RC flags containing long quoted /D'efines which contain spaces. The command: ``` perl srclib\apr\build\cvtdsp.pl -2005 ``` will convert the /D flags for RC flags to use an alternate, parseable syntax; unfortunately this syntax isn't supported by Visual Studio 97 or its exported .mak files. These /D flags are used to pass the long description of the mod\_apachemodule.so files to the shared .rc resource version-identifier build. **Building with OpenSSL 1.1.0 and up** Due to difference in the build structure of OpenSSL begining with version 1.1.0 you will need to convert the dsp files affected with cvtdsp.pl from APR 1.6 or greater. The command: ``` perl srclib\apr\build\cvtdsp.pl -ossl11 ``` Visual Studio 2002 (.NET) and later users should also use the Build menu, Configuration Manager dialog to uncheck both the `Debug` and `Release` Solution modules `abs`, `[mod\_deflate](../mod/mod_deflate)` and `[mod\_ssl](../mod/mod_ssl)` components, as well as every component starting with `apr_db*`. These modules are built by invoking `nmake`, or the IDE directly with the `BinBuild` target, which builds those modules conditionally if the `srclib` directories `openssl` and/or `zlib` exist, and based on the setting of `DBD_LIST` and `DBM_LIST` environment variables. ### Exporting command-line .mak files Exported `.mak` files pose a greater hassle, but they are required for Visual C++ 5.0 users to build `[mod\_ssl](../mod/mod_ssl)`, abs (`[ab](../programs/ab)` with SSL support) and/or `[mod\_deflate](../mod/mod_deflate)`. The .mak files also support a broader range of C++ tool chain distributions, such as Visual Studio Express. You must first build all projects in order to create all dynamic auto-generated targets, so that dependencies can be parsed correctly. Build the entire project from within the Visual Studio 6.0 (98) IDE, using the `BuildAll` target, then use the Project Menu Export for all makefiles (checking on "with dependencies".) Run the following command to correct absolute paths into relative paths so they will build anywhere: ``` perl srclib\apr\build\fixwin32mak.pl ``` You must type this command from the *top level* directory of the httpd source tree. Every `.mak` and `.dep` project file within the current directory and below will be corrected, and the timestamps adjusted to reflect the `.dsp`. Always review the generated `.mak` and `.dep` files for Platform SDK or other local, machine specific file paths. The `DevStudio\Common\MSDev98\bin\` (VC6) directory contains a `sysincl.dat` file, which lists all exceptions. Update this file (including both forward and backslashed paths, such as both `sys/time.h` and `sys\time.h`) to ignore such newer dependencies. Including local-install paths in a distributed `.mak` file will cause the build to fail completely. If you contribute back a patch that revises project files, we must commit project files in Visual Studio 6.0 format. Changes should be simple, with minimal compilation and linkage flags that can be recognized by all Visual Studio environments. ### Installation Once Apache has been compiled, it needs to be installed in its server root directory. The default is the `\Apache2` directory, of the same drive. To build and install all the files into the desired folder *dir* automatically, use one of the following `nmake` commands: ``` nmake /f Makefile.win installr INSTDIR=dir nmake /f Makefile.win installd INSTDIR=dir ``` The *dir* argument to `INSTDIR` provides the installation directory; it can be omitted if Apache is to be installed into `\Apache22` (of the current drive). ### Warning about building Apache from the development tree Note only the `.dsp` files are maintained between `release` builds. The `.mak` files are NOT regenerated, due to the tremendous waste of reviewer's time. Therefore, you cannot rely on the `NMAKE` commands above to build revised `.dsp` project files unless you then export all `.mak` files yourself from the project. This is unnecessary if you build from within the Microsoft Developer Studio environment. Building httpd with cmake ------------------------- The primary documentation for this build mechanism is in the `README.cmake` file in the source distribution. Refer to that file for detailed instructions. Building httpd with cmake requires building APR and APR-util separately. Refer to their `README.cmake` files for instructions. The primary limitations of the cmake-based build are inherited from the APR-util project, and are listed below because of their impact on httpd: * No cmake build for the APR-iconv subproject is available, and the APR-util cmake build cannot consume an existing APR-iconv build. Thus, `[mod\_charset\_lite](../mod/mod_charset_lite)` and possibly some third-party modules cannot be used. * The cmake build for the APR-util subproject does not support most of the optional DBM and DBD libraries supported by the included Visual Studio project files. This limits the database backends supported by a number of bundled and third-party modules. apache_http_server Using Apache HTTP Server on Microsoft Windows Using Apache HTTP Server on Microsoft Windows ============================================= This document explains how to install, configure and run Apache 2.4 under Microsoft Windows. If you have questions after reviewing the documentation (and any event and error logs), you should consult the peer-supported [users' mailing list](http://httpd.apache.org/userslist.html). This document assumes that you are installing a binary distribution of Apache. If you want to compile Apache yourself (possibly to help with development or tracking down bugs), see [Compiling Apache for Microsoft Windows](win_compiling). Operating System Requirements ----------------------------- The primary Windows platform for running Apache 2.4 is Windows 2000 or later. Always obtain and install the current service pack to avoid operating system bugs. Apache HTTP Server versions later than 2.2 will not run on any operating system earlier than Windows 2000. Downloading Apache for Windows ------------------------------ The Apache HTTP Server Project itself does not provide binary releases of software, only source code. Individual committers *may* provide binary packages as a convenience, but it is not a release deliverable. If you cannot compile the Apache HTTP Server yourself, you can obtain a binary package from numerous binary distributions available on the Internet. Popular options for deploying Apache httpd, and, optionally, PHP and MySQL, on Microsoft Windows, include: * [ApacheHaus](http://www.apachehaus.com/cgi-bin/download.plx) * [Apache Lounge](http://www.apachelounge.com/download/) * [Bitnami WAMP Stack](http://bitnami.com/stack/wamp) * [WampServer](http://www.wampserver.com/) * [XAMPP](http://www.apachefriends.org/en/xampp.html) Customizing Apache for Windows ------------------------------ Apache is configured by the files in the `conf` subdirectory. These are the same files used to configure the Unix version, but there are a few different directives for Apache on Windows. See the [directive index](https://httpd.apache.org/docs/2.4/en/mod/directives.html) for all the available directives. The main differences in Apache for Windows are: * Because Apache for Windows is multithreaded, it does not use a separate process for each request, as Apache can on Unix. Instead there are usually only two Apache processes running: a parent process, and a child which handles the requests. Within the child process each request is handled by a separate thread. The process management directives are also different: `[MaxConnectionsPerChild](../mod/mpm_common#maxconnectionsperchild)`: Like the Unix directive, this controls how many connections a single child process will serve before exiting. However, unlike on Unix, a replacement process is not instantly available. Use the default `MaxConnectionsPerChild 0`, unless instructed to change the behavior to overcome a memory leak in third party modules or in-process applications. **Warning: The server configuration file is reread when a new child process is started. If you have modified `httpd.conf`, the new child may not start or you may receive unexpected results.** `[ThreadsPerChild](../mod/mpm_common#threadsperchild)`: This directive is new. It tells the server how many threads it should use. This is the maximum number of connections the server can handle at once, so be sure to set this number high enough for your site if you get a lot of hits. The recommended default is `ThreadsPerChild 150`, but this must be adjusted to reflect the greatest anticipated number of simultaneous connections to accept. * The directives that accept filenames as arguments must use Windows filenames instead of Unix ones. However, because Apache may interpret backslashes as an "escape character" sequence, you should consistently use forward slashes in path names, not backslashes. * While filenames are generally case-insensitive on Windows, URLs are still treated internally as case-sensitive before they are mapped to the filesystem. For example, the `[<Location>](../mod/core#location)`, `[Alias](../mod/mod_alias#alias)`, and `[ProxyPass](../mod/mod_proxy#proxypass)` directives all use case-sensitive arguments. For this reason, it is particularly important to use the `[<Directory>](../mod/core#directory)` directive when attempting to limit access to content in the filesystem, since this directive applies to any content in a directory, regardless of how it is accessed. If you wish to assure that only lowercase is used in URLs, you can use something like: ``` RewriteEngine On RewriteMap lowercase int:tolower RewriteCond "%{REQUEST_URI}" "[A-Z]" RewriteRule "(.*)" "${lowercase:$1}" [R,L] ``` * When running, Apache needs write access only to the logs directory and any configured cache directory tree. Due to the issue of case insensitive and short 8.3 format names, Apache must validate all path names given. This means that each directory which Apache evaluates, from the drive root up to the directory leaf, must have read, list and traverse directory permissions. If Apache2.4 is installed at C:\Program Files, then the root directory, Program Files and Apache2.4 must all be visible to Apache. * Apache for Windows contains the ability to load modules at runtime, without recompiling the server. If Apache is compiled normally, it will install a number of optional modules in the `\Apache2.4\modules` directory. To activate these or other modules, the `[LoadModule](../mod/mod_so#loadmodule)` directive must be used. For example, to activate the status module, use the following (in addition to the status-activating directives in `access.conf`): ``` LoadModule status_module "modules/mod_status.so" ``` Information on [creating loadable modules](../mod/mod_so#creating) is also available. * Apache can also load ISAPI (Internet Server Application Programming Interface) extensions such as those used by Microsoft IIS and other Windows servers. [More information is available](../mod/mod_isapi). Note that Apache **cannot** load ISAPI Filters, and ISAPI Handlers with some Microsoft feature extensions will not work. * When running CGI scripts, the method Apache uses to find the interpreter for the script is configurable using the `[ScriptInterpreterSource](../mod/core#scriptinterpretersource)` directive. * Since it is often difficult to manage files with names like `.htaccess` in Windows, you may find it useful to change the name of this per-directory configuration file using the `[AccessFilename](../mod/core#accessfilename)` directive. * Any errors during Apache startup are logged into the Windows event log when running on Windows NT. This mechanism acts as a backup for those situations where Apache is not yet prepared to use the `error.log` file. You can review the Windows Application Event Log by using the Event Viewer, e.g. Start - Settings - Control Panel - Administrative Tools - Event Viewer. Running Apache as a Service --------------------------- Apache comes with a utility called the Apache Service Monitor. With it you can see and manage the state of all installed Apache services on any machine on your network. To be able to manage an Apache service with the monitor, you have to first install the service (either automatically via the installation or manually). You can install Apache as a Windows NT service as follows from the command prompt at the Apache `bin` subdirectory: ``` httpd.exe -k install ``` If you need to specify the name of the service you want to install, use the following command. You have to do this if you have several different service installations of Apache on your computer. If you specify a name during the install, you have to also specify it during any other -k operation. ``` httpd.exe -k install -n "MyServiceName" ``` If you need to have specifically named configuration files for different services, you must use this: ``` httpd.exe -k install -n "MyServiceName" -f "c:\files\my.conf" ``` If you use the first command without any special parameters except `-k install`, the service will be called `Apache2.4` and the configuration will be assumed to be `conf\httpd.conf`. Removing an Apache service is easy. Just use: ``` httpd.exe -k uninstall ``` The specific Apache service to be uninstalled can be specified by using: ``` httpd.exe -k uninstall -n "MyServiceName" ``` Normal starting, restarting and shutting down of an Apache service is usually done via the Apache Service Monitor, by using commands like `NET START Apache2.4` and `NET STOP Apache2.4` or via normal Windows service management. Before starting Apache as a service by any means, you should test the service's configuration file by using: ``` httpd.exe -n "MyServiceName" -t ``` You can control an Apache service by its command line switches, too. To start an installed Apache service you'll use this: ``` httpd.exe -k start -n "MyServiceName" ``` To stop an Apache service via the command line switches, use this: ``` httpd.exe -k stop -n "MyServiceName" ``` or ``` httpd.exe -k shutdown -n "MyServiceName" ``` You can also restart a running service and force it to reread its configuration file by using: ``` httpd.exe -k restart -n "MyServiceName" ``` By default, all Apache services are registered to run as the system user (the `LocalSystem` account). The `LocalSystem` account has no privileges to your network via any Windows-secured mechanism, including the file system, named pipes, DCOM, or secure RPC. It has, however, wide privileges locally. **Never grant any network privileges to the `LocalSystem` account! If you need Apache to be able to access network resources, create a separate account for Apache as noted below.** It is recommended that users create a separate account for running Apache service(s). If you have to access network resources via Apache, this is required. 1. Create a normal domain user account, and be sure to memorize its password. 2. Grant the newly-created user a privilege of `Log on as a service` and `Act as part of the operating system`. On Windows NT 4.0 these privileges are granted via User Manager for Domains, but on Windows 2000 and XP you probably want to use Group Policy for propagating these settings. You can also manually set these via the Local Security Policy MMC snap-in. 3. Confirm that the created account is a member of the Users group. 4. Grant the account read and execute (RX) rights to all document and script folders (`htdocs` and `cgi-bin` for example). 5. Grant the account change (RWXD) rights to the Apache `logs` directory. 6. Grant the account read and execute (RX) rights to the `httpd.exe` binary executable. It is usually a good practice to grant the user the Apache service runs as read and execute (RX) access to the whole Apache2.4 directory, except the `logs` subdirectory, where the user has to have at least change (RWXD) rights. If you allow the account to log in as a user and as a service, then you can log on with that account and test that the account has the privileges to execute the scripts, read the web pages, and that you can start Apache in a console window. If this works, and you have followed the steps above, Apache should execute as a service with no problems. **Error code 2186** is a good indication that you need to review the "Log On As" configuration for the service, since Apache cannot access a required network resource. Also, pay close attention to the privileges of the user Apache is configured to run as. When starting Apache as a service you may encounter an error message from the Windows Service Control Manager. For example, if you try to start Apache by using the Services applet in the Windows Control Panel, you may get the following message: ``` Could not start the Apache2.4 service on \\COMPUTER Error 1067; The process terminated unexpectedly. ``` You will get this generic error if there is any problem with starting the Apache service. In order to see what is really causing the problem you should follow the instructions for Running Apache for Windows from the Command Prompt. If you are having problems with the service, it is suggested you follow the instructions below to try starting httpd.exe from a console window, and work out the errors before struggling to start it as a service again. Running Apache as a Console Application --------------------------------------- Running Apache as a service is usually the recommended way to use it, but it is sometimes easier to work from the command line, especially during initial configuration and testing. To run Apache from the command line as a console application, use the following command: `httpd.exe` Apache will execute, and will remain running until it is stopped by pressing Control-C. You can also run Apache via the shortcut Start Apache in Console placed to `Start Menu --> Programs --> Apache HTTP Server 2.4.xx --> Control Apache Server` during the installation. This will open a console window and start Apache inside it. If you don't have Apache installed as a service, the window will remain visible until you stop Apache by pressing Control-C in the console window where Apache is running in. The server will exit in a few seconds. However, if you do have Apache installed as a service, the shortcut starts the service. If the Apache service is running already, the shortcut doesn't do anything. If Apache is running as a service, you can tell it to stop by opening another console window and entering: ``` httpd.exe -k shutdown ``` Running as a service should be preferred over running in a console window because this lets Apache end any current operations and clean up gracefully. But if the server is running in a console window, you can only stop it by pressing Control-C in the same window. You can also tell Apache to restart. This forces it to reread the configuration file. Any operations in progress are allowed to complete without interruption. To restart Apache, either press Control-Break in the console window you used for starting Apache, or enter ``` httpd.exe -k restart ``` if the server is running as a service. Note for people familiar with the Unix version of Apache: these commands provide a Windows equivalent to `kill -TERM *pid*` and `kill -USR1 *pid*`. The command line option used, `-k`, was chosen as a reminder of the `kill` command used on Unix. If the Apache console window closes immediately or unexpectedly after startup, open the Command Prompt from the Start Menu --> Programs. Change to the folder to which you installed Apache, type the command `httpd.exe`, and read the error message. Then change to the logs folder, and review the `error.log` file for configuration mistakes. Assuming httpd was installed into `C:\Program Files\Apache Software Foundation\Apache2.4\`, you can do the following: ``` c: cd "\Program Files\Apache Software Foundation\Apache2.4\bin" httpd.exe ``` Then wait for Apache to stop, or press Control-C. Then enter the following: ``` cd ..\logs more < error.log ``` When working with Apache it is important to know how it will find the configuration file. You can specify a configuration file on the command line in two ways: * `-f` specifies an absolute or relative path to a particular configuration file: ``` httpd.exe -f "c:\my server files\anotherconfig.conf" ``` or ``` httpd.exe -f files\anotherconfig.conf ``` * `-n` specifies the installed Apache service whose configuration file is to be used: ``` httpd.exe -n "MyServiceName" ``` In both of these cases, the proper `[ServerRoot](../mod/core#serverroot)` should be set in the configuration file. If you don't specify a configuration file with `-f` or `-n`, Apache will use the file name compiled into the server, such as `conf\httpd.conf`. This built-in path is relative to the installation directory. You can verify the compiled file name from a value labelled as `SERVER_CONFIG_FILE` when invoking Apache with the `-V` switch, like this: ``` httpd.exe -V ``` Apache will then try to determine its `[ServerRoot](../mod/core#serverroot)` by trying the following, in this order: 1. A `[ServerRoot](../mod/core#serverroot)` directive via the `-C` command line switch. 2. The `-d` switch on the command line. 3. Current working directory. 4. A registry entry which was created if you did a binary installation. 5. The server root compiled into the server. This is `/apache` by default, you can verify it by using `httpd.exe -V` and looking for a value labelled as `HTTPD_ROOT`. If you did not do a binary install, Apache will in some scenarios complain about the missing registry key. This warning can be ignored if the server was otherwise able to find its configuration file. The value of this key is the `[ServerRoot](../mod/core#serverroot)` directory which contains the `conf` subdirectory. When Apache starts it reads the `httpd.conf` file from that directory. If this file contains a `[ServerRoot](../mod/core#serverroot)` directive which contains a different directory from the one obtained from the registry key above, Apache will forget the registry key and use the directory from the configuration file. If you copy the Apache directory or configuration files to a new location it is vital that you update the `[ServerRoot](../mod/core#serverroot)` directive in the `httpd.conf` file to reflect the new location. Testing the Installation ------------------------ After starting Apache (either in a console window or as a service) it will be listening on port 80 (unless you changed the `[Listen](../mod/mpm_common#listen)` directive in the configuration files or installed Apache only for the current user). To connect to the server and access the default page, launch a browser and enter this URL: `http://localhost/` Apache should respond with a welcome page and you should see "It Works!". If nothing happens or you get an error, look in the `error.log` file in the `logs` subdirectory. If your host is not connected to the net, or if you have serious problems with your DNS (Domain Name Service) configuration, you may have to use this URL: `http://127.0.0.1/` If you happen to be running Apache on an alternate port, you need to explicitly put that in the URL: `http://127.0.0.1:8080/` Once your basic installation is working, you should configure it properly by editing the files in the `conf` subdirectory. Again, if you change the configuration of the Windows NT service for Apache, first attempt to start it from the command line to make sure that the service starts with no errors. Because Apache **cannot** share the same port with another TCP/IP application, you may need to stop, uninstall or reconfigure certain other services before running Apache. These conflicting services include other WWW servers, some firewall implementations, and even some client applications (such as Skype) which will use port 80 to attempt to bypass firewall issues. Configuring Access to Network Resources --------------------------------------- Access to files over the network can be specified using two mechanisms provided by Windows: Mapped drive letters e.g., `Alias "/images/" "Z:/"` UNC paths e.g., `Alias "/images/" "//imagehost/www/images/"` Mapped drive letters allow the administrator to maintain the mapping to a specific machine and path outside of the Apache httpd configuration. However, these mappings are associated only with interactive sessions and are not directly available to Apache httpd when it is started as a service. **Use only UNC paths for network resources in httpd.conf** so that the resources can be accessed consistently regardless of how Apache httpd is started. (Arcane and error prone procedures may work around the restriction on mapped drive letters, but this is not recommended.) ### Example DocumentRoot with UNC path ``` DocumentRoot "//dochost/www/html/" ``` ### Example DocumentRoot with IP address in UNC path ``` DocumentRoot "//192.168.1.50/docs/" ``` ### Example Alias and corresponding Directory with UNC path ``` Alias "/images/" "//imagehost/www/images/" <Directory "//imagehost/www/images/"> #... </Directory> ``` When running Apache httpd as a service, you must create a separate account in order to access network resources, as described above. Windows Tuning -------------- * If more than a few dozen piped loggers are used on an operating system instance, scaling up the "desktop heap" is often necessary. For more detailed information, refer to the [piped logging](../logs#piped) documentation.
programming_docs
apache_http_server Using Apache With RPM Based Systems (Redhat / CentOS / Fedora) Using Apache With RPM Based Systems (Redhat / CentOS / Fedora) ============================================================== While many distributions make Apache httpd available as operating system supported packages, it can sometimes be desirable to install and use the canonical version of Apache httpd on these systems, replacing the natively provided versions of the packages. While the Apache httpd project does not currently create binary RPMs for the various distributions out there, it is easy to build your own binary RPMs from the canonical Apache httpd tarball. This document explains how to build, install, configure and run Apache httpd 2.4 under Unix systems supporting the RPM packaging format. Creating a Source RPM --------------------- The Apache httpd source tarball can be converted into an SRPM as follows: ``` rpmbuild -ts httpd-2.4.x.tar.bz2 ``` Building RPMs ------------- RPMs can be built directly from the Apache httpd source tarballs using the following command: ``` rpmbuild -tb httpd-2.4.x.tar.bz2 ``` Corresponding "-devel" packages will be required to be installed on your build system prior to building the RPMs, the `rpmbuild` command will automatically calculate what RPMs are required and will list any dependencies that are missing on your system. These "-devel" packages will not be required after the build is completed, and can be safely removed. If successful, the following RPMs will be created: httpd-2.4.x-1.i686.rpm The core server and basic module set. httpd-debuginfo-2.4.x-1.i686.rpm Debugging symbols for the server and all modules. httpd-devel-2.4.x-1.i686.rpm Headers and development files for the server. httpd-manual-2.4.x-1.i686.rpm The webserver manual. httpd-tools-2.4.x-1.i686.rpm Supporting tools for the webserver. mod\_authnz\_ldap-2.4.x-1.i686.rpm `[mod\_ldap](../mod/mod_ldap)` and `[mod\_authnz\_ldap](../mod/mod_authnz_ldap)`, with corresponding dependency on openldap. mod\_lua-2.4.x-1.i686.rpm `[mod\_lua](../mod/mod_lua)` module, with corresponding dependency on lua. mod\_proxy\_html-2.4.x-1.i686.rpm `[mod\_proxy\_html](../mod/mod_proxy_html)` module, with corresponding dependency on libxml2. mod\_socache\_dc-2.4.x-1.i686.rpm `[mod\_socache\_dc](../mod/mod_socache_dc)` module, with corresponding dependency on distcache. mod\_ssl-2.4.x-1.i686.rpm `[mod\_ssl](../mod/mod_ssl)` module, with corresponding dependency on openssl. Installing the Server --------------------- The `httpd` RPM is the only RPM necessary to get a basic server to run. Install it as follows: ``` rpm -U httpd-2.4.x-1.i686.rpm ``` Self contained modules are included with the server. Modules that depend on external libraries are provided as separate RPMs to install if needed. Configuring the Default Instance of Apache httpd ------------------------------------------------ The default configuration for the server is installed by default beneath the `/etc/httpd` directory, with logs written by default to `/var/log/httpd`. The environment for the webserver is set by default within the optional `/etc/sysconfig/httpd` file. Start the server as follows: ``` service httpd restart ``` Configuring Additional Instances of Apache httpd on the Same Machine -------------------------------------------------------------------- It is possible to configure additional instances of the Apache httpd server running independently alongside each other on the same machine. These instances can have independent configurations, and can potentially run as separate users if so configured. This was done by making the httpd startup script aware of its own name. This name is then used to find the environment file for the server, and in turn, the server root of the server instance. To create an additional instance called `httpd-additional`, follow these steps: * Create a symbolic link to the startup script for the additional server: ``` ln -s /etc/rc.d/init.d/httpd /etc/rc.d/init.d/httpd-additional chkconfig --add httpd-additional ``` * Create an environment file for the server, using the `/etc/sysconfig/httpd` file as a template: ``` # template from httpd cp /etc/sysconfig/httpd /etc/sysconfig/httpd-additional ``` ``` # blank template touch /etc/sysconfig/httpd-additional ``` Edit `/etc/sysconfig/httpd-additional` and pass the server root of the new server instance within the `OPTIONS` environment variable. ``` OPTIONS="-d /etc/httpd-additional -f conf/httpd-additional.conf" ``` * Edit the server configuration file `/etc/httpd-additional/conf/httpd-additional.conf` to ensure the correct ports and paths are configured. * Start the server as follows: ``` service httpd-additional restart ``` * Repeat this process as required for each server instance. apache_http_server The Apache EBCDIC Port The Apache EBCDIC Port ====================== **Warning:** This document has not been updated to take into account changes made in the 2.0 version of the Apache HTTP Server. Some of the information may still be relevant, but please use it with care. Overview of the Apache EBCDIC Port ---------------------------------- Version 1.3 of the Apache HTTP Server was the first version which included a port to a (non-ASCII) mainframe machine which uses the EBCDIC character set as its native codeset. (It is the SIEMENS family of mainframes running the [BS2000/OSD operating system](http://www.siemens.de/servers/bs2osd/osdbc_us.htm). This mainframe OS nowadays features a SVR4-derived POSIX subsystem). The port was started initially to * prove the feasibility of porting [the Apache HTTP server](http://httpd.apache.org/) to this platform * find a "worthy and capable" successor for the venerable [CERN-3.0](http://www.w3.org/Daemon/) daemon (which was ported a couple of years ago), and to * prove that Apache's preforking process model can on this platform easily outperform the accept-fork-serve model used by CERN by a factor of 5 or more. This document serves as a rationale to describe some of the design decisions of the port to this machine. Design Goals ------------ One objective of the EBCDIC port was to maintain enough backwards compatibility with the (EBCDIC) CERN server to make the transition to the new server attractive and easy. This required the addition of a configurable method to define whether a HTML document was stored in ASCII (the only format accepted by the old server) or in EBCDIC (the native document format in the POSIX subsystem, and therefore the only realistic format in which the other POSIX tools like `grep` or `sed` could operate on the documents). The current solution to this is a "pseudo-MIME-format" which is intercepted and interpreted by the Apache server (see below). Future versions might solve the problem by defining an "ebcdic-handler" for all documents which must be converted. Technical Solution ------------------ Since all Apache input and output is based upon the BUFF data type and its methods, the easiest solution was to add the conversion to the BUFF handling routines. The conversion must be settable at any time, so a BUFF flag was added which defines whether a BUFF object has currently enabled conversion or not. This flag is modified at several points in the HTTP protocol: * **set** before a request is received (because the request and the request header lines are always in ASCII format) * **set/unset** when the request body is received - depending on the content type of the request body (because the request body may contain ASCII text or a binary file) * **set** before a reply header is sent (because the response header lines are always in ASCII format) * **set/unset** when the response body is sent - depending on the content type of the response body (because the response body may contain text or a binary file) Porting Notes ------------- 1. The relevant changes in the source are `#ifdef`'ed into two categories: `#ifdef CHARSET_EBCDIC` Code which is needed for any EBCDIC based machine. This includes character translations, differences in contiguity of the two character sets, flags which indicate which part of the HTTP protocol has to be converted and which part doesn't *etc.* `#ifdef _OSD_POSIX` Code which is needed for the SIEMENS BS2000/OSD mainframe platform only. This deals with include file differences and socket implementation topics which are only required on the BS2000/OSD platform. 2. The possibility to translate between ASCII and EBCDIC at the socket level (on BS2000 POSIX, there is a socket option which supports this) was intentionally *not* chosen, because the byte stream at the HTTP protocol level consists of a mixture of protocol related strings and non-protocol related raw file data. HTTP protocol strings are always encoded in ASCII (the `GET` request, any Header: lines, the chunking information *etc.*) whereas the file transfer parts (*i.e.*, GIF images, CGI output *etc.*) should usually be just "passed through" by the server. This separation between "protocol string" and "raw data" is reflected in the server code by functions like `bgets()` or `rvputs()` for strings, and functions like `bwrite()` for binary data. A global translation of everything would therefore be inadequate. (In the case of text files of course, provisions must be made so that EBCDIC documents are always served in ASCII) 3. This port therefore features a built-in protocol level conversion for the server-internal strings (which the compiler translated to EBCDIC strings) and thus for all server-generated documents. The hard coded ASCII escapes `\012` and `\015` which are ubiquitous in the server code are an exception: they are already the binary encoding of the ASCII `\n` and `\r` and must not be converted to ASCII a second time. This exception is only relevant for server-generated strings; and *external* EBCDIC documents are not expected to contain ASCII newline characters. 4. By examining the call hierarchy for the BUFF management routines, I added an "ebcdic/ascii conversion layer" which would be crossed on every puts/write/get/gets, and a conversion flag which allowed enabling/disabling the conversions on-the-fly. Usually, a document crosses this layer twice from its origin source (a file or CGI output) to its destination (the requesting client): `file -> Apache`, and `Apache -> client`. The server can now read the header lines of a CGI-script output in EBCDIC format, and then find out that the remainder of the script's output is in ASCII (like in the case of the output of a WWW Counter program: the document body contains a GIF image). All header processing is done in the native EBCDIC format; the server then determines, based on the type of document being served, whether the document body (except for the chunking information, of course) is in ASCII already or must be converted from EBCDIC. 5. For Text documents (MIME types text/plain, text/html *etc.*), an implicit translation to ASCII can be used, or (if the users prefer to store some documents in raw ASCII form for faster serving, or because the files reside on a NFS-mounted directory tree) can be served without conversion. **Example:** to serve files with the suffix `.ahtml` as a raw ASCII `text/html` document without implicit conversion (and suffix `.ascii` as ASCII `text/plain`), use the directives: ``` AddType text/x-ascii-html .ahtml AddType text/x-ascii-plain .ascii ``` Similarly, any `text/foo` MIME type can be served as "raw ASCII" by configuring a MIME type "`text/x-ascii-foo`" for it using `AddType`. 6. Non-text documents are always served "binary" without conversion. This seems to be the most sensible choice for, .*e.g.*, GIF/ZIP/AU file types. This of course requires the user to copy them to the mainframe host using the "`rcp -b`" binary switch. 7. Server parsed files are always assumed to be in native (*i.e.*, EBCDIC) format as used on the machine, and are converted after processing. 8. For CGI output, the CGI script determines whether a conversion is needed or not: by setting the appropriate Content-Type, text files can be converted, or GIF output can be passed through unmodified. An example for the latter case is the wwwcount program which we ported as well. Document Storage Notes ---------------------- ### Binary Files All files with a `Content-Type:` which does not start with `text/` are regarded as *binary files* by the server and are not subject to any conversion. Examples for binary files are GIF images, gzip-compressed files and the like. When exchanging binary files between the mainframe host and a Unix machine or Windows PC, be sure to use the ftp "binary" (`TYPE I`) command, or use the `rcp -b` command from the mainframe host (the `-b` switch is not supported in unix `rcp`'s). ### Text Documents The default assumption of the server is that Text Files (*i.e.*, all files whose `Content-Type:` starts with `text/`) are stored in the native character set of the host, EBCDIC. ### Server Side Included Documents SSI documents must currently be stored in EBCDIC only. No provision is made to convert it from ASCII before processing. Apache Modules' Status ---------------------- | Module | Status | Notes | | --- | --- | --- | | `core` | + | | | `mod_access` | + | | | `mod_actions` | + | | | `mod_alias` | + | | | `mod_asis` | + | | | `mod_auth` | + | | | `mod_authn_anon` | + | | | `mod_authn_dbm` | ? | with own `libdb.a` | | `mod_authz_dbm` | ? | with own `libdb.a` | | `mod_autoindex` | + | | | `mod_cern_meta` | ? | | | `mod_cgi` | + | | | `mod_digest` | + | | | `mod_dir` | + | | | `mod_so` | - | no shared libs | | `mod_env` | + | | | `mod_example` | - | (test bed only) | | `mod_expires` | + | | | `mod_headers` | + | | | `mod_imagemap` | + | | | `mod_include` | + | | | `mod_info` | + | | | `mod_log_agent` | + | | | `mod_log_config` | + | | | `mod_log_referer` | + | | | `mod_mime` | + | | | `mod_mime_magic` | ? | not ported yet | | `mod_negotiation` | + | | | `mod_proxy` | + | | | `mod_rewrite` | + | untested | | `mod_setenvif` | + | | | `mod_speling` | + | | | `mod_status` | + | | | `mod_unique_id` | + | | | `mod_userdir` | + | | | `mod_usertrack` | ? | untested | Third Party Modules' Status --------------------------- | Module | Status | Notes | | --- | --- | --- | | ``` JK (Formerly mod_jserv) ``` | - | JAVA still being ported. | | `mod_php3` | + | `mod_php3` runs fine, with LDAP and GD and FreeType libraries. | | `mod_put` | ? | untested | | `mod_session` | - | untested | apache_http_server Using Apache With Novell NetWare Using Apache With Novell NetWare ================================ This document explains how to install, configure and run Apache 2.0 under Novell NetWare 6.0 and above. If you find any bugs, or wish to contribute in other ways, please use our [bug reporting page.](http://httpd.apache.org/bug_report.html) The bug reporting page and dev-httpd mailing list are *not* provided to answer questions about configuration or running Apache. Before you submit a bug report or request, first consult this document, the [Frequently Asked Questions](http://wiki.apache.org/httpd/FAQ) page and the other relevant documentation topics. If you still have a question or problem, post it to the [novell.devsup.webserver](news://developer-forums.novell.com/novell.devsup.webserver) newsgroup, where many Apache users are more than willing to answer new and obscure questions about using Apache on NetWare. Most of this document assumes that you are installing Apache from a binary distribution. If you want to compile Apache yourself (possibly to help with development, or to track down bugs), see the section on [Compiling Apache for NetWare](#comp) below. Requirements ------------ Apache 2.0 is designed to run on NetWare 6.0 service pack 3 and above. If you are running a service pack less than SP3, you must install the latest [NetWare Libraries for C (LibC)](http://developer.novell.com/ndk/libc.htm). NetWare service packs are available [here](http://support.novell.com/misc/patlst.htm#nw). Apache 2.0 for NetWare can also be run in a NetWare 5.1 environment as long as the latest service pack or the latest version of the [NetWare Libraries for C (LibC)](http://developer.novell.com/ndk/libc.htm) has been installed . **WARNING:** Apache 2.0 for NetWare has not been targeted for or tested in this environment. Downloading Apache for NetWare ------------------------------ Information on the latest version of Apache can be found on the Apache web server at <http://www.apache.org/>. This will list the current release, any more recent alpha or beta-test releases, together with details of mirror web and anonymous ftp sites. Binary builds of the latest releases of Apache 2.0 for NetWare can be downloaded from [here](http://www.apache.org/dist/httpd/binaries/netware). Installing Apache for NetWare ----------------------------- There is no Apache install program for NetWare currently. If you are building Apache 2.0 for NetWare from source, you will need to copy the files over to the server manually. Follow these steps to install Apache on NetWare from the binary download (assuming you will install to `sys:/apache2`): * Unzip the binary download file to the root of the `SYS:` volume (may be installed to any volume) * Edit the `httpd.conf` file setting `[ServerRoot](../mod/core#serverroot)` and `[ServerName](../mod/core#servername)` along with any file path values to reflect your correct server settings * Add `SYS:/APACHE2` to the search path, for example: ``` SEARCH ADD SYS:\APACHE2 ``` Follow these steps to install Apache on NetWare manually from your own build source (assuming you will install to `sys:/apache2`): * Create a directory called `Apache2` on a NetWare volume * Copy `APACHE2.NLM`, `APRLIB.NLM` to `SYS:/APACHE2` * Create a directory under `SYS:/APACHE2` called `BIN` * Copy `HTDIGEST.NLM`, `HTPASSWD.NLM`, `HTDBM.NLM`, `LOGRES.NLM`, `ROTLOGS.NLM` to `SYS:/APACHE2/BIN` * Create a directory under `SYS:/APACHE2` called `CONF` * Copy the `HTTPD-STD.CONF` file to the `SYS:/APACHE2/CONF` directory and rename to `HTTPD.CONF` * Copy the `MIME.TYPES`, `CHARSET.CONV` and `MAGIC` files to `SYS:/APACHE2/CONF` directory * Copy all files and subdirectories in `\HTTPD-2.0\DOCS\ICONS` to `SYS:/APACHE2/ICONS` * Copy all files and subdirectories in `\HTTPD-2.0\DOCS\MANUAL` to `SYS:/APACHE2/MANUAL` * Copy all files and subdirectories in `\HTTPD-2.0\DOCS\ERROR` to `SYS:/APACHE2/ERROR` * Copy all files and subdirectories in `\HTTPD-2.0\DOCS\DOCROOT` to `SYS:/APACHE2/HTDOCS` * Create the directory `SYS:/APACHE2/LOGS` on the server * Create the directory `SYS:/APACHE2/CGI-BIN` on the server * Create the directory `SYS:/APACHE2/MODULES` and copy all nlm modules into the `modules` directory * Edit the `HTTPD.CONF` file searching for all `@@Value@@` markers and replacing them with the appropriate setting * Add `SYS:/APACHE2` to the search path, for example: ``` SEARCH ADD SYS:\APACHE2 ``` Apache may be installed to other volumes besides the default `SYS` volume. During the build process, adding the keyword "install" to the makefile command line will automatically produce a complete distribution package under the subdirectory `DIST`. Install Apache by simply copying the distribution that was produced by the makfiles to the root of a NetWare volume (see: [Compiling Apache for NetWare](#comp) below). Running Apache for NetWare -------------------------- To start Apache just type `apache` at the console. This will load apache in the OS address space. If you prefer to load Apache in a protected address space you may specify the address space with the load statement as follows: ``` load address space = apache2 apache2 ``` This will load Apache into an address space called apache2. Running multiple instances of Apache concurrently on NetWare is possible by loading each instance into its own protected address space. After starting Apache, it will be listening to port 80 (unless you changed the `[Listen](../mod/mpm_common#listen)` directive in the configuration files). To connect to the server and access the default page, launch a browser and enter the server's name or address. This should respond with a welcome page, and a link to the Apache manual. If nothing happens or you get an error, look in the `error_log` file in the `logs` directory. Once your basic installation is working, you should configure it properly by editing the files in the `conf` directory. To unload Apache running in the OS address space just type the following at the console: ``` unload apache2 ``` or ``` apache2 shutdown ``` If apache is running in a protected address space specify the address space in the unload statement: ``` unload address space = apache2 apache2 ``` When working with Apache it is important to know how it will find the configuration files. You can specify a configuration file on the command line in two ways: * `-f` specifies a path to a particular configuration file ``` apache2 -f "vol:/my server/conf/my.conf" ``` ``` apache -f test/test.conf ``` In these cases, the proper `[ServerRoot](../mod/core#serverroot)` should be set in the configuration file. If you don't specify a configuration file name with `-f`, Apache will use the file name compiled into the server, usually `conf/httpd.conf`. Invoking Apache with the `-V` switch will display this value labeled as `SERVER_CONFIG_FILE`. Apache will then determine its `[ServerRoot](../mod/core#serverroot)` by trying the following, in this order: * A `ServerRoot` directive via a `-C` switch. * The `-d` switch on the command line. * Current working directory * The server root compiled into the server. The server root compiled into the server is usually `sys:/apache2`. invoking apache with the `-V` switch will display this value labeled as `HTTPD_ROOT`. Apache 2.0 for NetWare includes a set of command line directives that can be used to modify or display information about the running instance of the web server. These directives are only available while Apache is running. Each of these directives must be preceded by the keyword `APACHE2`. RESTART Instructs Apache to terminate all running worker threads as they become idle, reread the configuration file and restart each worker thread based on the new configuration. VERSION Displays version information about the currently running instance of Apache. MODULES Displays a list of loaded modules both built-in and external. DIRECTIVES Displays a list of all available directives. SETTINGS Enables or disables the thread status display on the console. When enabled, the state of each running threads is displayed on the Apache console screen. SHUTDOWN Terminates the running instance of the Apache web server. HELP Describes each of the runtime directives. By default these directives are issued against the instance of Apache running in the OS address space. To issue a directive against a specific instance running in a protected address space, include the -p parameter along with the name of the address space. For more information type "apache2 Help" on the command line. Configuring Apache for NetWare ------------------------------ Apache is configured by reading configuration files usually stored in the `conf` directory. These are the same as files used to configure the Unix version, but there are a few different directives for Apache on NetWare. See the [Apache module documentation](../mod/index) for all the available directives. The main differences in Apache for NetWare are: * Because Apache for NetWare is multithreaded, it does not use a separate process for each request, as Apache does on some Unix implementations. Instead there are only threads running: a parent thread, and multiple child or worker threads which handle the requests. Therefore the "process"-management directives are different: `[MaxConnectionsPerChild](../mod/mpm_common#maxconnectionsperchild)` - Like the Unix directive, this controls how many connections a worker thread will serve before exiting. The recommended default, `MaxConnectionsPerChild 0`, causes the thread to continue servicing request indefinitely. It is recommended on NetWare, unless there is some specific reason, that this directive always remain set to `0`. `[StartThreads](../mod/mpm_common#startthreads)` - This directive tells the server how many threads it should start initially. The recommended default is `StartThreads 50`. `[MinSpareThreads](../mod/mpm_common#minsparethreads)` - This directive instructs the server to spawn additional worker threads if the number of idle threads ever falls below this value. The recommended default is `MinSpareThreads 10`. `[MaxSpareThreads](../mod/mpm_common#maxsparethreads)` - This directive instructs the server to begin terminating worker threads if the number of idle threads ever exceeds this value. The recommended default is `MaxSpareThreads 100`. `[MaxThreads](../mod/mpm_netware#maxthreads)` - This directive limits the total number of work threads to a maximum value. The recommended default is `ThreadsPerChild 250`. `[ThreadStackSize](../mod/mpm_common#threadstacksize)` - This directive tells the server what size of stack to use for the individual worker thread. The recommended default is `ThreadStackSize 65536`. * The directives that accept filenames as arguments must use NetWare filenames instead of Unix names. However, because Apache uses Unix-style names internally, forward slashes must be used rather than backslashes. It is recommended that all rooted file paths begin with a volume name. If omitted, Apache will assume the `SYS:` volume which may not be correct. * Apache for NetWare has the ability to load modules at runtime, without recompiling the server. If Apache is compiled normally, it will install a number of optional modules in the `\Apache2\modules` directory. To activate these, or other modules, the `[LoadModule](../mod/mod_so#loadmodule)` directive must be used. For example, to active the status module, use the following: ``` LoadModule status_module modules/status.nlm ``` Information on [creating loadable modules](../mod/mod_so#creating) is also available. ### Additional NetWare specific directives: * `[CGIMapExtension](../mod/core#cgimapextension)` - This directive maps a CGI file extension to a script interpreter. * `[SecureListen](../mod/mod_nw_ssl#securelisten)` - Enables SSL encryption for a specified port. * `[NWSSLTrustedCerts](../mod/mod_nw_ssl#nwssltrustedcerts)` - Adds trusted certificates that are used to create secure connections to proxied servers. * `[NWSSLUpgradeable](../mod/mod_nw_ssl#nwsslupgradeable)` - Allow a connection created on the specified address/port to be upgraded to an SSL connection. Compiling Apache for NetWare ---------------------------- Compiling Apache requires MetroWerks CodeWarrior 6.x or higher. Once Apache has been built, it can be installed to the root of any NetWare volume. The default is the `sys:/Apache2` directory. Before running the server you must fill out the `conf` directory. Copy the file `HTTPD-STD.CONF` from the distribution `conf` directory and rename it to `HTTPD.CONF`. Edit the `HTTPD.CONF` file searching for all `@@Value@@` markers and replacing them with the appropriate setting. Copy over the `conf/magic` and `conf/mime.types` files as well. Alternatively, a complete distribution can be built by including the keyword `install` when invoking the makefiles. ### Requirements: The following development tools are required to build Apache 2.0 for NetWare: * Metrowerks CodeWarrior 6.0 or higher with the [NetWare PDK 3.0](http://developer.novell.com/ndk/cwpdk.htm) or higher. * [NetWare Libraries for C (LibC)](http://developer.novell.com/ndk/libc.htm) * [LDAP Libraries for C](http://developer.novell.com/ndk/cldap.htm) * [ZLIB Compression Library source code](http://www.gzip.org/zlib/) * AWK utility (awk, gawk or similar). AWK can be downloaded from <http://developer.novell.com/ndk/apache.htm>. The utility must be found in your windows path and must be named `awk.exe`. * To build using the makefiles, you will need GNU make version 3.78.1 (GMake) available at <http://developer.novell.com/ndk/apache.htm>. ### Building Apache using the NetWare makefiles: * Set the environment variable `NOVELLLIBC` to the location of the NetWare Libraries for C SDK, for example: ``` Set NOVELLLIBC=c:\novell\ndk\libc ``` * Set the environment variable `METROWERKS` to the location where you installed the Metrowerks CodeWarrior compiler, for example: ``` Set METROWERKS=C:\Program Files\Metrowerks\CodeWarrior ``` If you installed to the default location `C:\Program Files\Metrowerks\CodeWarrior`, you don't need to set this. * Set the environment variable `LDAPSDK` to the location where you installed the LDAP Libraries for C, for example: ``` Set LDAPSDK=c:\Novell\NDK\cldapsdk\NetWare\libc ``` * Set the environment variable `ZLIBSDK` to the location where you installed the source code for the ZLib Library, for example: ``` Set ZLIBSDK=D:\NOVELL\zlib ``` * Set the environment variable `PCRESDK` to the location where you installed the source code for the PCRE Library, for example: ``` Set PCRESDK=D:\NOVELL\pcre ``` * Set the environment variable `AP_WORK` to the full path of the `httpd` source code directory. ``` Set AP_WORK=D:\httpd-2.0.x ``` * Set the environment variable `APR_WORK` to the full path of the `apr` source code directory. Typically `\httpd\srclib\apr` but the APR project can be outside of the httpd directory structure. ``` Set APR_WORK=D:\apr-1.x.x ``` * Set the environment variable `APU_WORK` to the full path of the `apr-util` source code directory. Typically `\httpd\srclib\apr-util` but the APR-UTIL project can be outside of the httpd directory structure. ``` Set APU_WORK=D:\apr-util-1.x.x ``` * Make sure that the path to the AWK utility and the GNU make utility (`gmake.exe`) have been included in the system's `PATH` environment variable. * Download the source code and unzip to an appropriate directory on your workstation. * Change directory to `\httpd-2.0` and build the prebuild utilities by running "`gmake -f nwgnumakefile prebuild`". This target will create the directory `\httpd-2.0\nwprebuild` and copy each of the utilities to this location that are necessary to complete the following build steps. * Copy the files `\httpd-2.0\nwprebuild\GENCHARS.nlm` and `\httpd-2.0\nwprebuild\DFTABLES.nlm` to the `SYS:` volume of a NetWare server and run them using the following commands: ``` SYS:\genchars > sys:\test_char.h SYS:\dftables sys:\chartables.c ``` * Copy the files `test_char.h` and `chartables.c` to the directory `\httpd-2.0\os\netware` on the build machine. * Change directory to `\httpd-2.0` and build Apache by running "`gmake -f nwgnumakefile`". You can create a distribution directory by adding an install parameter to the command, for example: ``` gmake -f nwgnumakefile install ``` ### Additional make options * `gmake -f nwgnumakefile`Builds release versions of all of the binaries and copies them to a `\release` destination directory. * `gmake -f nwgnumakefile DEBUG=1`Builds debug versions of all of the binaries and copies them to a `\debug` destination directory. * `gmake -f nwgnumakefile install`Creates a complete Apache distribution with binaries, docs and additional support files in a `\dist\Apache2` directory. * `gmake -f nwgnumakefile prebuild`Builds all of the prebuild utilities and copies them to the `\nwprebuild` directory. * `gmake -f nwgnumakefile installdev`Same as install but also creates a `\lib` and `\include` directory in the destination directory and copies headers and import files. * `gmake -f nwgnumakefile clean`Cleans all object files and binaries from the `\release.o` or `\debug.o` build areas depending on whether `DEBUG` has been defined. * `gmake -f nwgnumakefile clobber_all`Same as clean and also deletes the distribution directory if it exists. ### Additional environment variable options * To build all of the experimental modules, set the environment variable `EXPERIMENTAL`: ``` Set EXPERIMENTAL=1 ``` * To build Apache using standard BSD style sockets rather than Winsock, set the environment variable `USE_STDSOCKETS`: ``` Set USE_STDSOCKETS=1 ``` ### Building mod\_ssl for the NetWare platform By default Apache for NetWare uses the built-in module `[mod\_nw\_ssl](../mod/mod_nw_ssl)` to provide SSL services. This module simply enables the native SSL services implemented in NetWare OS to handle all encryption for a given port. Alternatively, mod\_ssl can also be used in the same manner as on other platforms. Before mod\_ssl can be built for the NetWare platform, the OpenSSL libraries must be provided. This can be done through the following steps: * Download the recent OpenSSL 0.9.8 release source code from the [OpenSSL Source](http://www.openssl.org/source/) page (older 0.9.7 versions need to be patched and are therefore not recommended). * Edit the file `NetWare/set_env.bat` and modify any tools and utilities paths so that they correspond to your build environment. * From the root of the OpenSSL source directory, run the following scripts: ``` Netware\set_env netware-libc Netware\build netware-libc ``` For performance reasons you should enable to build with ASM code. Download NASM from the [SF site](http://nasm.sourceforge.net/). Then configure OpenSSL to use ASM code: ``` Netware\build netware-libc nw-nasm enable-mdc2 enable-md5 ``` Warning: don't use the CodeWarrior Assembler - it produces broken code! * Before building Apache, set the environment variable `OSSLSDK` to the full path to the root of the openssl source code directory, and set WITH\_MOD\_SSL to 1. ``` Set OSSLSDK=d:\openssl-0.9.8x Set WITH_MOD_SSL=1 ```
programming_docs
apache_http_server Server and Supporting Programs Server and Supporting Programs ============================== This page documents all the executable programs included with the Apache HTTP Server. Index ----- `<httpd>` Apache hypertext transfer protocol server `<apachectl>` Apache HTTP server control interface `<ab>` Apache HTTP server benchmarking tool `<apxs>` APache eXtenSion tool `<configure>` Configure the source tree `<dbmmanage>` Create and update user authentication files in DBM format for basic authentication `<fcgistarter>` Start a FastCGI program `<htcacheclean>` Clean up the disk cache `<htdigest>` Create and update user authentication files for digest authentication `<htdbm>` Manipulate DBM password databases. `<htpasswd>` Create and update user authentication files for basic authentication `<httxt2dbm>` Create dbm files for use with RewriteMap `<logresolve>` Resolve hostnames for IP-addresses in Apache logfiles `<log_server_status>` Periodically log the server's status `<rotatelogs>` Rotate Apache logs without having to kill the server `<split-logfile>` Split a multi-vhost logfile into per-host logfiles `<suexec>` Switch User For Exec apache_http_server apachectl - Apache HTTP Server Control Interface apachectl - Apache HTTP Server Control Interface ================================================ `apachectl` is a front end to the Apache HyperText Transfer Protocol (HTTP) server. It is designed to help the administrator control the functioning of the Apache `<httpd>` daemon. The `apachectl` script can operate in two modes. First, it can act as a simple front-end to the `<httpd>` command that simply sets any necessary environment variables and then invokes `<httpd>`, passing through any command line arguments. Second, `apachectl` can act as a SysV init script, taking simple one-word arguments like `start`, `restart`, and `stop`, and translating them into appropriate signals to `<httpd>`. If your Apache installation uses non-standard paths, you will need to edit the `apachectl` script to set the appropriate paths to the `<httpd>` binary. You can also specify any necessary `<httpd>` command line arguments. See the comments in the script for details. The `apachectl` script returns a 0 exit value on success, and >0 if an error occurs. For more details, view the comments in the script. Synopsis -------- When acting in pass-through mode, `apachectl` can take all the arguments available for the `<httpd>` binary. ``` apachectl [ httpd-argument ] ``` When acting in SysV init mode, `apachectl` takes simple, one-word commands, defined below. ``` apachectl command ``` Options ------- Only the SysV init-style options are defined here. Other arguments are defined on the `<httpd>` manual page. `start` Start the Apache `<httpd>` daemon. Gives an error if it is already running. This is equivalent to `apachectl -k start`. `stop` Stops the Apache `<httpd>` daemon. This is equivalent to `apachectl -k stop`. `restart` Restarts the Apache `<httpd>` daemon. If the daemon is not running, it is started. This command automatically checks the configuration files as in `configtest` before initiating the restart to make sure the daemon doesn't die. This is equivalent to `apachectl -k restart`. `fullstatus` Displays a full status report from `[mod\_status](../mod/mod_status)`. For this to work, you need to have `[mod\_status](../mod/mod_status)` enabled on your server and a text-based browser such as `lynx` available on your system. The URL used to access the status report can be set by editing the `STATUSURL` variable in the script. `status` Displays a brief status report. Similar to the `fullstatus` option, except that the list of requests currently being served is omitted. `graceful` Gracefully restarts the Apache `<httpd>` daemon. If the daemon is not running, it is started. This differs from a normal restart in that currently open connections are not aborted. A side effect is that old log files will not be closed immediately. This means that if used in a log rotation script, a substantial delay may be necessary to ensure that the old log files are closed before processing them. This command automatically checks the configuration files as in `configtest` before initiating the restart to make sure Apache doesn't die. This is equivalent to `apachectl -k graceful`. `graceful-stop` Gracefully stops the Apache `<httpd>` daemon. This differs from a normal stop in that currently open connections are not aborted. A side effect is that old log files will not be closed immediately. This is equivalent to `apachectl -k graceful-stop`. `configtest` Run a configuration file syntax test. It parses the configuration files and either reports `Syntax Ok` or detailed information about the particular syntax error. This is equivalent to `apachectl -t`. The following option was available in earlier versions but has been removed. `startssl` To start `<httpd>` with SSL support, you should edit your configuration file to include the relevant directives and then use the normal `apachectl start`. apache_http_server split-logfile - Split up multi-vhost logfiles split-logfile - Split up multi-vhost logfiles ============================================= This perl script will take a combined Web server access log file and break its contents into separate files. It assumes that the first field of each line is the virtual host identity, put there using the "`%v`" variable in `[LogFormat](../mod/mod_log_config#logformat)`. Usage ----- Create a log file with virtual host information in it: ``` LogFormat "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined_plus_vhost CustomLog logs/access_log combined_plus_vhost ``` Log files will be created, in the directory where you run the script, for each virtual host name that appears in the combined log file. These logfiles will named after the hostname, with a `.log` file extension. The combined log file is read from stdin. Records read will be appended to any existing log files. ``` split-logfile < access_log ``` apache_http_server httxt2dbm - Generate dbm files for use with RewriteMap httxt2dbm - Generate dbm files for use with RewriteMap ====================================================== `httxt2dbm` is used to generate dbm files from text input, for use in `[RewriteMap](../mod/mod_rewrite#rewritemap)` with the `dbm` map type. If the output file already exists, it will not be truncated. New keys will be added and existing keys will be updated. Synopsis -------- ``` httxt2dbm [ -v ] [ -f DBM_TYPE ] -i SOURCE_TXT -o OUTPUT_DBM ``` Options ------- `-v` More verbose output `-f DBM_TYPE` Specify the DBM type to be used for the output. If not specified, will use the [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary") Default. Available types are: `GDBM` for GDBM files, `SDBM` for SDBM files, `DB` for berkeley DB files, `NDBM` for NDBM files, `default` for the default DBM type. `-i SOURCE_TXT` Input file from which the dbm is to be created. The file should be formatted with one record per line, of the form: `key value`. See the documentation for `[RewriteMap](../mod/mod_rewrite#rewritemap)` for further details of this file's format and meaning. `-o OUTPUT_DBM` Name of the output dbm files. Examples -------- ``` httxt2dbm -i rewritemap.txt -o rewritemap.dbm httxt2dbm -f SDBM -i rewritemap.txt -o rewritemap.dbm ``` apache_http_server fcgistarter - Start a FastCGI program fcgistarter - Start a FastCGI program ===================================== Note ---- Currently only works on Unix systems. Synopsis -------- ``` fcgistarter -c command -p port [ -i interface ] -N num ``` Options ------- `-c command` Absolute path of the FastCGI program `-p port` Port which the program will listen on `-i interface` Interface which the program will listen on `-N num` Number of instances of the program apache_http_server htpasswd - Manage user files for basic authentication htpasswd - Manage user files for basic authentication ===================================================== `htpasswd` is used to create and update the flat-files used to store usernames and password for basic authentication of HTTP users. If `htpasswd` cannot access a file, such as not being able to write to the output file or not being able to read the file in order to update it, it returns an error status and makes no changes. Resources available from the Apache HTTP server can be restricted to just the users listed in the files created by `htpasswd`. This program can only manage usernames and passwords stored in a flat-file. It can encrypt and display password information for use in other types of data stores, though. To use a DBM database see `<dbmmanage>` or `<htdbm>`. `htpasswd` encrypts passwords using either bcrypt, a version of MD5 modified for Apache, SHA1, or the system's `crypt()` routine. Files managed by `htpasswd` may contain a mixture of different encoding types of passwords; some user records may have bcrypt or MD5-encrypted passwords while others in the same file may have passwords encrypted with `crypt()`. This manual page only lists the command line arguments. For details of the directives necessary to configure user authentication in `<httpd>` see the Apache manual, which is part of the Apache distribution or can be found at [http://httpd.apache.org/](http://httpd.apache.org). Synopsis -------- ``` htpasswd [ -c ] [ -i ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -D ] [ -v ] passwdfile username ``` ``` htpasswd -b [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -D ] [ -v ] passwdfile username password ``` ``` htpasswd -n [ -i ] [ -m | -B | -d | -s | -p ] [ -C cost ] username ``` ``` htpasswd -nb [ -m | -B | -d | -s | -p ] [ -C cost ] username password ``` Options ------- `-b` Use batch mode; *i.e.*, get the password from the command line rather than prompting for it. This option should be used with extreme care, since **the password is clearly visible** on the command line. For script use see the `-i` option. Available in 2.4.4 and later. `-i` Read the password from stdin without verification (for script usage). `-c` Create the passwdfile. If passwdfile already exists, it is rewritten and truncated. This option cannot be combined with the `-n` option. `-n` Display the results on standard output rather than updating a file. This is useful for generating password records acceptable to Apache for inclusion in non-text data stores. This option changes the syntax of the command line, since the passwdfile argument (usually the first one) is omitted. It cannot be combined with the `-c` option. `-m` Use MD5 encryption for passwords. This is the default (since version 2.2.18). `-B` Use bcrypt encryption for passwords. This is currently considered to be very secure. `-C` This flag is only allowed in combination with `-B` (bcrypt encryption). It sets the computing time used for the bcrypt algorithm (higher is more secure but slower, default: 5, valid: 4 to 17). `-d` Use `crypt()` encryption for passwords. This is not supported by the `<httpd>` server on Windows and Netware. This algorithm limits the password length to 8 characters. This algorithm is **insecure** by today's standards. It used to be the default algorithm until version 2.2.17. `-s` Use SHA encryption for passwords. Facilitates migration from/to Netscape servers using the LDAP Directory Interchange Format (ldif). This algorithm is **insecure** by today's standards. `-p` Use plaintext passwords. Though `htpasswd` will support creation on all platforms, the `<httpd>` daemon will only accept plain text passwords on Windows and Netware. `-D` Delete user. If the username exists in the specified htpasswd file, it will be deleted. `-v` Verify password. Verify that the given password matches the password of the user stored in the specified htpasswd file. Available in 2.4.5 and later. `passwdfile` Name of the file to contain the user name and password. If `-c` is given, this file is created if it does not already exist, or rewritten and truncated if it does exist. `username` The username to create or update in passwdfile. If username does not exist in this file, an entry is added. If it does exist, the password is changed. `password` The plaintext password to be encrypted and stored in the file. Only used with the `-b` flag. Exit Status ----------- `htpasswd` returns a zero status ("true") if the username and password have been successfully added or updated in the passwdfile. `htpasswd` returns `1` if it encounters some problem accessing files, `2` if there was a syntax problem with the command line, `3` if the password was entered interactively and the verification entry didn't match, `4` if its operation was interrupted, `5` if a value is too long (username, filename, password, or final computed record), `6` if the username contains illegal characters (see the [Restrictions section](#restrictions)), and `7` if the file is not a valid password file. Examples -------- ``` htpasswd /usr/local/etc/apache/.htpasswd-users jsmith ``` Adds or modifies the password for user `jsmith`. The user is prompted for the password. The password will be encrypted using the modified Apache MD5 algorithm. If the file does not exist, `htpasswd` will do nothing except return an error. ``` htpasswd -c /home/doe/public_html/.htpasswd jane ``` Creates a new file and stores a record in it for user `jane`. The user is prompted for the password. If the file exists and cannot be read, or cannot be written, it is not altered and `htpasswd` will display a message and return an error status. ``` htpasswd -db /usr/web/.htpasswd-all jones Pwd4Steve ``` Encrypts the password from the command line (`Pwd4Steve`) using the `crypt()` algorithm, and stores it in the specified file. Security Considerations ----------------------- Web password files such as those managed by `htpasswd` should *not* be within the Web server's URI space -- that is, they should not be fetchable with a browser. This program is not safe as a setuid executable. Do *not* make it setuid. The use of the `-b` option is discouraged, since when it is used the unencrypted password appears on the command line. When using the `crypt()` algorithm, note that only the first 8 characters of the password are used to form the password. If the supplied password is longer, the extra characters will be silently discarded. The SHA encryption format does not use salting: for a given password, there is only one encrypted representation. The `crypt()` and MD5 formats permute the representation by prepending a random salt string, to make dictionary attacks against the passwords more difficult. The SHA and `crypt()` formats are insecure by today's standards. Restrictions ------------ On the Windows platform, passwords encrypted with `htpasswd` are limited to no more than `255` characters in length. Longer passwords will be truncated to 255 characters. The MD5 algorithm used by `htpasswd` is specific to the Apache software; passwords encrypted using it will not be usable with other Web servers. Usernames are limited to `255` bytes and may not include the character `:`. The cost of computing a bcrypt password hash value increases with the number of rounds specified by the `-C` option. The `apr-util` library enforces a maximum number of rounds of 17 in version `1.6.0` and later. apache_http_server htcacheclean - Clean up the disk cache htcacheclean - Clean up the disk cache ====================================== `htcacheclean` is used to keep the size of `[mod\_cache\_disk](../mod/mod_cache_disk)`'s storage within a given size limit, or limit on inodes in use. This tool can run either manually or in daemon mode. When running in daemon mode, it sleeps in the background and checks the cache directory at regular intervals for cached content to be removed. You can stop the daemon cleanly by sending it a TERM or INT signal. When run manually, a once off check of the cache directory is made for cached content to be removed. If one or more URLs are specified, each URL will be deleted from the cache, if present. Synopsis -------- ``` htcacheclean [ -D ] [ -v ] [ -t ] [ -r ] [ -n ] [ -Rround ] -ppath [ -llimit ] [ -Llimit ] ``` ``` htcacheclean [ -n ] [ -t ] [ -i ] [ -Ppidfile ] [ -Rround ] -dinterval -ppath [ -llimit ] [ -Llimit ] ``` ``` htcacheclean [ -v ] [ -Rround ] -ppath [ -a ] [ -A ] ``` ``` htcacheclean [ -D ] [ -v ] [ -t ] [ -Rround ] -ppath url ``` Options ------- `-dinterval` Daemonize and repeat cache cleaning every interval minutes. This option is mutually exclusive with the `-D`, `-v` and `-r` options. To shutdown the daemon cleanly, just send it a `SIGTERM` or `SIGINT`. `-D` Do a dry run and don't delete anything. This option is mutually exclusive with the `-d` option. When doing a dry run and deleting directories with `-t`, the inodes reported deleted in the stats cannot take into account the directories deleted, and will be marked as an estimate. `-v` Be verbose and print statistics. This option is mutually exclusive with the `-d` option. `-r` Clean thoroughly. This assumes that the Apache web server is not running (otherwise you may get garbage in the cache). This option is mutually exclusive with the `-d` option and implies the `-t` option. `-n` Be nice. This causes slower processing in favour of other processes. `htcacheclean` will sleep from time to time so that (a) the disk IO will be delayed and (b) the kernel can schedule other processes in the meantime. `-t` Delete all empty directories. By default only cache files are removed, however with some configurations the large number of directories created may require attention. If your configuration requires a very large number of directories, to the point that inode or file allocation table exhaustion may become an issue, use of this option is advised. `-ppath` Specify path as the root directory of the disk cache. This should be the same value as specified with the `[CacheRoot](../mod/mod_cache_disk#cacheroot)` directive. `-Ppidfile` Specify pidfile as the name of the file to write the process ID to when daemonized. `-Rround` Specify round as the amount to round sizes up to, to compensate for disk block sizes. Set to the block size of the cache partition. `-llimit` Specify limit as the total disk cache size limit. The value is expressed in bytes by default (or attaching `B` to the number). Attach `K` for Kbytes, `M` for MBytes or `G` for Gbytes. `-Llimit` Specify limit as the total disk cache inode limit. `K`, `M` or `G` suffix can also be used. `-i` Be intelligent and run only when there was a modification of the disk cache. This option is only possible together with the `-d` option. `-a` List the URLs currently stored in the cache. Variants of the same URL will be listed once for each variant. `-A` List the URLs currently stored in the cache, along with their attributes in the following order: url, header size, body size, status, entity version, date, expiry, request time, response time, body present, head request. Deleting a specific URL ----------------------- If `htcacheclean` is passed one or more URLs, each URL will be deleted from the cache. If multiple variants of an URL exists, all variants would be deleted. When a reverse proxied URL is to be deleted, the effective URL is constructed from the **Host** header, the **port**, the **path** and the **query**. Note the '?' in the URL must always be specified explicitly, whether a query string is present or not. For example, an attempt to delete the path **/** from the server **localhost**, the URL to delete would be **http://localhost:80/?**. Listing URLs in the Cache ------------------------- By passing the `-a` or `-A` options to `htcacheclean`, the URLs within the cache will be listed as they are found, one URL per line. The `-A` option dumps the full cache entry after the URL, with fields in the following order: url The URL of the entry. header size The size of the header in bytes. body size The size of the body in bytes. status Status of the cached response. entity version The number of times this entry has been revalidated without being deleted. date Date of the response. expiry Expiry date of the response. request time Time of the start of the request. response time Time of the end of the request. body present If 0, no body is stored with this request, 1 otherwise. head request If 1, the entry contains a cached HEAD request with no body, 0 otherwise. Exit Status ----------- `htcacheclean` returns a zero status ("true") if all operations were successful, `1` otherwise. If an URL is specified, and the URL was cached and successfully removed, `0` is returned, `2` otherwise. If an error occurred during URL removal, `1` is returned.
programming_docs
apache_http_server logresolve - Resolve IP-addresses to hostnames in Apache log files logresolve - Resolve IP-addresses to hostnames in Apache log files ================================================================== `logresolve` is a post-processing program to resolve IP-addresses in Apache's access logfiles. To minimize impact on your nameserver, logresolve has its very own internal hash-table cache. This means that each IP number will only be looked up the first time it is found in the log file. Takes an Apache log file on standard input. The IP addresses must be the first thing on each line and must be separated from the remainder of the line by a space. Synopsis -------- ``` logresolve [ -s filename ] [ -c ] < access_log > access_log.new ``` Options ------- `-s filename` Specifies a filename to record statistics. `-c` This causes `logresolve` to apply some DNS checks: after finding the hostname from the IP address, it looks up the IP addresses for the hostname and checks that one of these matches the original address. apache_http_server httpd - Apache Hypertext Transfer Protocol Server httpd - Apache Hypertext Transfer Protocol Server ================================================= `httpd` is the Apache HyperText Transfer Protocol (HTTP) server program. It is designed to be run as a standalone daemon process. When used like this it will create a pool of child processes or threads to handle requests. In general, `httpd` should not be invoked directly, but rather should be invoked via `<apachectl>` on Unix-based systems or [as a service on Windows NT, 2000 and XP](../platform/windows#winsvc) and [as a console application on Windows 9x and ME](../platform/windows#wincons). Synopsis -------- ``` httpd [ -d serverroot ] [ -f config ] [ -C directive ] [ -c directive ] [ -D parameter ] [ -e level ] [ -E file ] [ -k start|restart|graceful|stop|graceful-stop ] [ -h ] [ -l ] [ -L ] [ -S ] [ -t ] [ -v ] [ -V ] [ -X ] [ -M ] [ -T ] ``` On [Windows systems](../platform/windows), the following additional arguments are available: ``` httpd [ -k install|config|uninstall ] [ -n name ] [ -w ] ``` Options ------- `-d serverroot` Set the initial value for the `[ServerRoot](../mod/core#serverroot)` directive to serverroot. This can be overridden by the ServerRoot directive in the configuration file. The default is `/usr/local/apache2`. `-f config` Uses the directives in the file config on startup. If config does not begin with a /, then it is taken to be a path relative to the `[ServerRoot](../mod/core#serverroot)`. The default is `conf/httpd.conf`. `-k `start|restart|graceful|stop|graceful-stop`` Signals `httpd` to start, restart, or stop. See [Stopping Apache httpd](../stopping) for more information. `-C directive` Process the configuration directive before reading config files. `-c directive` Process the configuration directive after reading config files. `-D parameter` Sets a configuration parameter which can be used with `[<IfDefine>](../mod/core#ifdefine)` sections in the configuration files to conditionally skip or process commands at server startup and restart. Also can be used to set certain less-common startup parameters including `-DNO_DETACH` (prevent the parent from forking) and `-DFOREGROUND` (prevent the parent from calling `setsid()` et al). `-e level` Sets the `[LogLevel](../mod/core#loglevel)` to level during server startup. This is useful for temporarily increasing the verbosity of the error messages to find problems during startup. `-E file` Send error messages during server startup to file. `-h` Output a short summary of available command line options. `-l` Output a list of modules compiled into the server. This will **not** list dynamically loaded modules included using the `[LoadModule](../mod/mod_so#loadmodule)` directive. `-L` Output a list of directives provided by static modules, together with expected arguments and places where the directive is valid. Directives provided by shared modules are not listed. `-M` Dump a list of loaded Static and Shared Modules. `-S` Show the settings as parsed from the config file (currently only shows the virtualhost settings). `-T` (Available in 2.3.8 and later) Skip document root check at startup/restart. `-t` Run syntax tests for configuration files only. The program immediately exits after these syntax parsing tests with either a return code of 0 (Syntax OK) or return code not equal to 0 (Syntax Error). If -D DUMP\_VHOSTS is also set, details of the virtual host configuration will be printed. If -D DUMP\_MODULES is set, all loaded modules will be printed. `-v` Print the version of `httpd`, and then exit. `-V` Print the version and build parameters of `httpd`, and then exit. `-X` Run httpd in debug mode. Only one worker will be started and the server will not detach from the console. The following arguments are available only on the [Windows platform](../platform/windows): `-k install|config|uninstall` Install Apache httpd as a Windows NT service; change startup options for the Apache httpd service; and uninstall the Apache httpd service. `-n name` The name of the Apache httpd service to signal. `-w` Keep the console window open on error so that the error message can be read. apache_http_server configure - Configure the source tree configure - Configure the source tree ===================================== The `configure` script configures the source tree for compiling and installing the Apache HTTP Server on your particular platform. Various options allow the compilation of a server corresponding to your personal requirements. This script, included in the root directory of the source distribution, is for compilation on Unix and Unix-like systems only. For other platforms, see the [platform](../platform/index) documentation. Synopsis -------- You should call the `configure` script from within the root directory of the distribution. ``` ./configure [OPTION]... [VAR=VALUE]... ``` To assign environment variables (e.g. `CC`, `CFLAGS` ...), specify them as `VAR=VALUE`. See [below](#env) for descriptions of some of the useful variables. Options ------- * [Configuration options](#configurationoptions) * [Installation directories](#installationdirectories) * [System types](#systemtypes) * [Optional features](#optionalfeatures) * [Options for support programs](#supportopt) ### Configuration options The following options influence the behavior of `configure` itself. `-C` `--config-cache` This is an alias for `--cache-file=config.cache` `--cache-file=FILE` The test results will be cached in file FILE. This option is disabled by default. `-h` `--help [short|recursive]` Output the help and exit. With the argument `short` only options specific to this package will displayed. The argument `recursive` displays the short help of all the included packages. `-n` `--no-create` The `configure` script is run normally but does not create output files. This is useful to check the test results before generating makefiles for compilation. `-q` `--quiet` Do not print `checking ...` messages during the configure process. `--srcdir=DIR` Defines directory DIR to be the source file directory. Default is the directory where `configure` is located, or the parent directory. `--silent` Same as `--quiet` -V --version Display copyright information and exit. ### Installation directories These options define the installation directory. The installation tree depends on the selected layout. `--prefix=PREFIX` Install architecture-independent files in PREFIX. By default the installation directory is set to `/usr/local/apache2`. `--exec-prefix=EPREFIX` Install architecture-dependent files in EPREFIX. By default the installation directory is set to the PREFIX directory. By default, `make install` will install all the files in `/usr/local/apache2/bin`, `/usr/local/apache2/lib` etc. You can specify an installation prefix other than `/usr/local/apache2` using `--prefix`, for instance `--prefix=$HOME`. #### Define a directory layout `--enable-layout=LAYOUT` Configure the source code and build scripts to assume an installation tree based on the layout LAYOUT. This allows you to separately specify the locations for each type of file within the Apache HTTP Server installation. The `config.layout` file contains several example configurations, and you can also create your own custom configuration following the examples. The different layouts in this file are grouped into `<Layout FOO>...</Layout>` sections and referred to by name as in `FOO`. The default layout is `Apache`. #### Fine tuning of the installation directories For better control of the installation directories, use the options below. Please note that the directory defaults are set by `autoconf` and are overwritten by the corresponding layout setting. `--bindir=DIR` Install user executables in DIR. The user executables are supporting programs like `<htpasswd>`, `<dbmmanage>`, etc. which are useful for site administrators. By default DIR is set to `EPREFIX/bin`. `--datadir=DIR` Install read-only architecture-independent data in DIR. By default `datadir` is set to `PREFIX/share`. This option is offered by `autoconf` and currently unused. `--includedir=DIR` Install C header files in DIR. By default `includedir` is set to `EPREFIX/include`. `--infodir=DIR` Install info documentation in DIR. By default `infodir` is set to `PREFIX/info`. This option is currently unused. `--libdir=DIR` Install object code libraries in DIR. By default `libdir` is set to `EPREFIX/lib`. `--libexecdir=DIR` Install the program executables (i.e., shared modules) in DIR. By default `libexecdir` is set to `EPREFIX/modules`. `--localstatedir=DIR` Install modifiable single-machine data in DIR. By default `localstatedir` is set to `PREFIX/var`. This option is offered by `autoconf` and currently unused. `--mandir=DIR` Install the man documentation in DIR. By default `mandir` is set to `EPREFIX/man`. `--oldincludedir=DIR` Install C header files for non-gcc in DIR. By default `oldincludedir` is set to `/usr/include`. This option is offered by `autoconf` and currently unused. `--sbindir=DIR` Install the system administrator executables in DIR. Those are server programs like `<httpd>`, `<apachectl>`, `<suexec>`, etc. which are necessary to run the Apache HTTP Server. By default `sbindir` is set to `EPREFIX/sbin`. `--sharedstatedir=DIR` Install modifiable architecture-independent data in DIR. By default `sharedstatedir` is set to `PREFIX/com`. This option is offered by `autoconf` and currently unused. `--sysconfdir=DIR` Install read-only single-machine data like the server configuration files `httpd.conf`, `mime.types`, etc. in DIR. By default `sysconfdir` is set to `PREFIX/conf`. ### System types These options are used to cross-compile the Apache HTTP Server to run on another system. In normal cases, when building and running the server on the same system, these options are not used. `--build=BUILD` Defines the system type of the system on which the tools are being built. It defaults to the result of the script `config.guess`. `--host=HOST` Defines the system type of the system on which the server will run. HOST defaults to BUILD. `--target=TARGET` Configure for building compilers for the system type TARGET. It defaults to HOST. This option is offered by `autoconf` and not necessary for the Apache HTTP Server. ### Optional Features These options are used to fine tune the features your HTTP server will have. #### General syntax Generally you can use the following syntax to enable or disable a feature: `--disable-FEATURE` Do not include FEATURE. This is the same as `--enable-FEATURE=no`. `--enable-FEATURE[=ARG]` Include FEATURE. The default value for ARG is `yes`. `--enable-MODULE=shared` The corresponding module will be built as a DSO module. By default enabled modules are linked dynamically. `--enable-MODULE=static` The corresponding module will be linked statically. **Note** `configure` will not complain about `--enable-foo` even if foo doesn't exist, so you need to type carefully. #### Choosing modules to compile Most modules are compiled by default and have to be disabled explicitly or by using the keyword `few` (see `--enable-modules`, `--enable-mods-shared` and `--enable-mods-static` below for further explanation) or `--enable-modules=none` to be removed as a group. Other modules are not compiled by default and have to be enabled explicitly or by using the keywords `all` or `reallyall` to be available. To find out which modules are compiled by default, run `./configure -h` or `./configure --help` and look under `Optional Features`. Suppose you are interested in `mod_example1` and `mod_example2`, and you see this: ``` Optional Features: ... --disable-example1 example module 1 --enable-example2 example module 2 ... ``` Then `mod_example1` is enabled by default, and you would use `--disable-example1` to not compile it. `mod_example2` is disabled by default, and you would use `--enable-example2` to compile it. #### Multi-Processing Modules [Multi-Processing Modules](../mpm), or MPMs, implement the basic behavior of the server. A single MPM must be active in order for the server to function. The list of available MPMs appears on the [module index page](../mod/index). MPMs can be built as DSOs for dynamic loading or statically linked with the server, and are enabled using the following options: `--with-mpm=MPM` Choose the default MPM for your server. If MPMs are built as DSO modules (see `--enable-mpms-shared`), this directive selects the MPM which will be loaded in the default configuration file. Otherwise, this directive selects the only available MPM, which will be statically linked into the server. If this option is omitted, the [default MPM](../mpm#defaults) for your operating system will be used. `--enable-mpms-shared=MPM-LIST` Enable a list of MPMs as dynamic shared modules. One of these modules must be loaded dynamically using the `[LoadModule](../mod/mod_so#loadmodule)` directive. MPM-LIST is a space-separated list of MPM names enclosed by quotation marks. For example: ``` --enable-mpms-shared='prefork worker' ``` Additionally you can use the special keyword `all`, which will select all MPMs which support dynamic loading on the current platform and build them as DSO modules. For example: `--enable-mpms-shared=all` #### Third-party modules To add additional third-party modules use the following options: `--with-module=module-type:module-file[, module-type:module-file]` Add one or more third-party modules to the list of statically linked modules. The module source file `module-file` will be searched in the `modules/module-type` subdirectory of your Apache HTTP server source tree. If it is not found there `configure` is considering module-file to be an absolute file path and tries to copy the source file into the module-type subdirectory. If the subdirectory doesn't exist it will be created and populated with a standard `Makefile.in`. This option is useful to add small external modules consisting of one source file. For more complex modules you should read the vendor's documentation. **Note** If you want to build a DSO module instead of a statically linked use `<apxs>`. #### Cumulative and other options `--enable-maintainer-mode` Turn on debugging and compile time warnings and load all compiled modules. `--enable-mods-shared=MODULE-LIST` Defines a list of modules to be enabled and build as dynamic shared modules. This mean, these module have to be loaded dynamically by using the `[LoadModule](../mod/mod_so#loadmodule)` directive. MODULE-LIST is a space separated list of modulenames enclosed by quotation marks. The module names are given without the preceding `mod_`. For example: ``` --enable-mods-shared='headers rewrite dav' ``` Additionally you can use the special keywords `reallyall`, `all`, `most` and `few`. For example, `--enable-mods-shared=most` will compile most modules and build them as DSO modules, `--enable-mods-shared=few` will only compile a very basic set of modules. The default set is `most`. The `[LoadModule](../mod/mod_so#loadmodule)` directives for the chosen modules will be automatically generated in the main configuration file. By default, all those directives will be commented out except for the modules that are either required or explicitly selected by a configure `--enable-foo` argument. You can change the set of loaded modules by activating or deactivating the `[LoadModule](../mod/mod_so#loadmodule)` directives in `httpd.conf`. In addition the `[LoadModule](../mod/mod_so#loadmodule)` directives for all built modules can be activated via the configure option `--enable-load-all-modules`. `--enable-mods-static=MODULE-LIST` This option behaves similar to `--enable-mods-shared`, but will link the given modules statically. This mean, these modules will always be present while running `<httpd>`. They need not be loaded with `[LoadModule](../mod/mod_so#loadmodule)`. `--enable-modules=MODULE-LIST` This option behaves like to `--enable-mods-shared`, and will also link the given modules dynamically. The special keyword `none` disables the build of all modules. `--enable-v4-mapped` Allow IPv6 sockets to handle IPv4 connections. `--with-port=PORT` This defines the port on which `<httpd>` will listen. This port number is used when generating the configuration file `httpd.conf`. The default is 80. `--with-program-name` Define an alternative executable name. The default is `httpd`. ### Optional packages These options are used to define optional packages. #### General syntax Generally you can use the following syntax to define an optional package: `--with-PACKAGE[=ARG]` Use the package PACKAGE. The default value for ARG is `yes`. `--without-PACKAGE` Do not use the package PACKAGE. This is the same as `--with-PACKAGE=no`. This option is provided by `autoconf` but not very useful for the Apache HTTP Server. #### Specific packages `--with-apr=DIR|FILE` The [Apache Portable Runtime](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary") (APR) is part of the httpd source distribution and will automatically be build together with the HTTP server. If you want to use an already installed APR instead you have to tell `configure` the path to the `apr-config` script. You may set the absolute path and name or the directory to the installed APR. `apr-config` must exist within this directory or the subdirectory `bin`. `--with-apr-util=DIR|FILE` The Apache Portable Runtime Utilities (APU) are part of the httpd source distribution and will automatically be build together with the HTTP server. If you want to use an already installed APU instead you have to tell `configure` the path to the `apu-config` script. You may set the absolute path and name or the directory to the installed APU. `apu-config` must exist within this directory or the subdirectory `bin`. `--with-ssl=DIR` If `[mod\_ssl](../mod/mod_ssl)` has been enabled `configure` searches for an installed OpenSSL. You can set the directory path to the SSL/TLS toolkit instead. `--with-z=DIR` `configure` searches automatically for an installed `zlib` library if your source configuration requires one (e.g., when `[mod\_deflate](../mod/mod_deflate)` is enabled). You can set the directory path to the compression library instead. Several features of the Apache HTTP Server, including `[mod\_authn\_dbm](../mod/mod_authn_dbm)` and `[mod\_rewrite](../mod/mod_rewrite)`'s DBM `[RewriteMap](../mod/mod_rewrite#rewritemap)` use simple key/value databases for quick lookups of information. SDBM is included in the APU, so this database is always available. If you would like to use other database types, use the following options to enable them: `--with-gdbm[=path]` If no path is specified, `configure` will search for the include files and libraries of a GNU DBM installation in the usual search paths. An explicit path will cause `configure` to look in `path/lib` and `path/include` for the relevant files. Finally, the path may specify specific include and library paths separated by a colon. `--with-ndbm[=path]` Like `--with-gdbm`, but searches for a New DBM installation. `--with-berkeley-db[=path]` Like `--with-gdbm`, but searches for a Berkeley DB installation. **Note** The DBM options are provided by the APU and passed through to its configuration script. They are useless when using an already installed APU defined by `--with-apr-util`. You may use more then one DBM implementation together with your HTTP server. The appropriated DBM type will be configured within the runtime configuration at each time. ### Options for support programs `--enable-static-support` Build a statically linked version of the support binaries. This means, a stand-alone executable will be built with all the necessary libraries integrated. Otherwise the support binaries are linked dynamically by default. `--enable-suexec` Use this option to enable `<suexec>`, which allows you to set uid and gid for spawned processes. **Do not use this option unless you understand all the security implications of running a suid binary on your server.** Further options to configure `<suexec>` are described [below](#suexec). It is possible to create a statically linked binary of a single support program by using the following options: `--enable-static-ab` Build a statically linked version of `<ab>`. `--enable-static-checkgid` Build a statically linked version of `checkgid`. `--enable-static-htdbm` Build a statically linked version of `<htdbm>`. `--enable-static-htdigest` Build a statically linked version of `<htdigest>`. `--enable-static-htpasswd` Build a statically linked version of `<htpasswd>`. `--enable-static-logresolve` Build a statically linked version of `<logresolve>`. `--enable-static-rotatelogs` Build a statically linked version of `<rotatelogs>`. #### `suexec` configuration options The following options are used to fine tune the behavior of `<suexec>`. See [Configuring and installing suEXEC](suexec#install) for further information. `--with-suexec-bin` This defines the path to `<suexec>` binary. Default is `--sbindir` (see [Fine tuning of installation directories](#directoryfinetuning)). `--with-suexec-caller` This defines the user allowed to call `<suexec>`. It should be the same as the user under which `<httpd>` normally runs. `--with-suexec-docroot` This defines the directory tree under which `<suexec>` access is allowed for executables. Default value is `--datadir/htdocs`. `--with-suexec-gidmin` Define this as the lowest GID allowed to be a target user for `<suexec>`. The default value is 100. `--with-suexec-logfile` This defines the filename of the `<suexec>` logfile. By default the logfile is named `suexec_log` and located in `--logfiledir`. `--with-suexec-safepath` Define the value of the environment variable `PATH` to be set for processes started by `<suexec>`. Default value is `/usr/local/bin:/usr/bin:/bin`. `--with-suexec-userdir` This defines the subdirectory under the user's directory that contains all executables for which `<suexec>` access is allowed. This setting is necessary when you want to use `<suexec>` together with user-specific directories (as provided by `[mod\_userdir](../mod/mod_userdir)`). The default is `public_html`. `--with-suexec-uidmin` Define this as the lowest UID allowed to be a target user for `<suexec>`. The default value is 100. `--with-suexec-umask` Set `umask` for processes started by `<suexec>`. It defaults to your system settings. Environment variables --------------------- There are some useful environment variables to override the choices made by `configure` or to help it to find libraries and programs with nonstandard names or locations. `CC` Define the C compiler command to be used for compilation. `CFLAGS` Set C compiler flags you want to use for compilation. `CPP` Define the C preprocessor command to be used. `CPPFLAGS` Set C/C++ preprocessor flags, e.g. `-Iincludedir` if you have headers in a nonstandard directory includedir. `LDFLAGS` Set linker flags, e.g. `-Llibdir` if you have libraries in a nonstandard directory libdir.
programming_docs
apache_http_server ab - Apache HTTP server benchmarking tool ab - Apache HTTP server benchmarking tool ========================================= `ab` is a tool for benchmarking your Apache Hypertext Transfer Protocol (HTTP) server. It is designed to give you an impression of how your current Apache installation performs. This especially shows you how many requests per second your Apache installation is capable of serving. Synopsis -------- ``` ab [ -A auth-username:password ] [ -b windowsize ] [ -B local-address ] [ -c concurrency ] [ -C cookie-name=value ] [ -d ] [ -e csv-file ] [ -E client-certificate file ] [ -f protocol ] [ -g gnuplot-file ] [ -h ] [ -H custom-header ] [ -i ] [ -k ] [ -l ] [ -m HTTP-method ] [ -n requests ] [ -p POST-file ] [ -P proxy-auth-username:password ] [ -q ] [ -r ] [ -s timeout ] [ -S ] [ -t timelimit ] [ -T content-type ] [ -u PUT-file ] [ -v verbosity] [ -V ] [ -w ] [ -x <table>-attributes ] [ -X proxy[:port] ] [ -y <tr>-attributes ] [ -z <td>-attributes ] [ -Z ciphersuite ] [http[s]://]hostname[:port]/path ``` Options ------- `-A auth-username:password` Supply BASIC Authentication credentials to the server. The username and password are separated by a single `:` and sent on the wire base64 encoded. The string is sent regardless of whether the server needs it (*i.e.*, has sent an 401 authentication needed). `-b windowsize` Size of TCP send/receive buffer, in bytes. `-B local-address` Address to bind to when making outgoing connections. `-c concurrency` Number of multiple requests to perform at a time. Default is one request at a time. `-C cookie-name=value` Add a `Cookie:` line to the request. The argument is typically in the form of a `name=value` pair. This field is repeatable. `-d` Do not display the "percentage served within XX [ms] table". (legacy support). `-e csv-file` Write a Comma separated value (CSV) file which contains for each percentage (from 1% to 100%) the time (in milliseconds) it took to serve that percentage of the requests. This is usually more useful than the 'gnuplot' file; as the results are already 'binned'. `-E client-certificate-file` When connecting to an SSL website, use the provided client certificate in PEM format to authenticate with the server. The file is expected to contain the client certificate, followed by intermediate certificates, followed by the private key. Available in 2.4.36 and later. `-f protocol` Specify SSL/TLS protocol (SSL2, SSL3, TLS1, TLS1.1, TLS1.2, or ALL). TLS1.1 and TLS1.2 support available in 2.4.4 and later. `-g gnuplot-file` Write all measured values out as a 'gnuplot' or TSV (Tab separate values) file. This file can easily be imported into packages like Gnuplot, IDL, Mathematica, Igor or even Excel. The labels are on the first line of the file. `-h` Display usage information. `-H custom-header` Append extra headers to the request. The argument is typically in the form of a valid header line, containing a colon-separated field-value pair (*i.e.*, `"Accept-Encoding: zip/zop;8bit"`). `-i` Do `HEAD` requests instead of `GET`. `-k` Enable the HTTP KeepAlive feature, *i.e.*, perform multiple requests within one HTTP session. Default is no KeepAlive. `-l` Do not report errors if the length of the responses is not constant. This can be useful for dynamic pages. Available in 2.4.7 and later. `-m HTTP-method` Custom HTTP method for the requests. Available in 2.4.10 and later. `-n requests` Number of requests to perform for the benchmarking session. The default is to just perform a single request which usually leads to non-representative benchmarking results. `-p POST-file` File containing data to POST. Remember to also set `-T`. `-P proxy-auth-username:password` Supply BASIC Authentication credentials to a proxy en-route. The username and password are separated by a single `:` and sent on the wire base64 encoded. The string is sent regardless of whether the proxy needs it (*i.e.*, has sent an 407 proxy authentication needed). `-q` When processing more than 150 requests, `ab` outputs a progress count on `stderr` every 10% or 100 requests or so. The `-q` flag will suppress these messages. `-r` Don't exit on socket receive errors. `-s timeout` Maximum number of seconds to wait before the socket times out. Default is 30 seconds. Available in 2.4.4 and later. `-S` Do not display the median and standard deviation values, nor display the warning/error messages when the average and median are more than one or two times the standard deviation apart. And default to the min/avg/max values. (legacy support). `-t timelimit` Maximum number of seconds to spend for benchmarking. This implies a `-n 50000` internally. Use this to benchmark the server within a fixed total amount of time. Per default there is no timelimit. `-T content-type` Content-type header to use for POST/PUT data, eg. `application/x-www-form-urlencoded`. Default is `text/plain`. `-u PUT-file` File containing data to PUT. Remember to also set `-T`. `-v verbosity` Set verbosity level - `4` and above prints information on headers, `3` and above prints response codes (404, 200, etc.), `2` and above prints warnings and info. `-V` Display version number and exit. `-w` Print out results in HTML tables. Default table is two columns wide, with a white background. `-x <table>-attributes` String to use as attributes for `<table>`. Attributes are inserted `<table here >`. `-X proxy[:port]` Use a proxy server for the requests. `-y <tr>-attributes` String to use as attributes for `<tr>`. `-z <td>-attributes` String to use as attributes for `<td>`. `-Z ciphersuite` Specify SSL/TLS cipher suite (See openssl ciphers) Output ------ The following list describes the values returned by `ab`: Server Software The value, if any, returned in the server HTTP header of the first successful response. This includes all characters in the header from beginning to the point a character with decimal value of 32 (most notably: a space or CR/LF) is detected. Server Hostname The DNS or IP address given on the command line Server Port The port to which ab is connecting. If no port is given on the command line, this will default to 80 for http and 443 for https. SSL/TLS Protocol The protocol parameters negotiated between the client and server. This will only be printed if SSL is used. Document Path The request URI parsed from the command line string. Document Length This is the size in bytes of the first successfully returned document. If the document length changes during testing, the response is considered an error. Concurrency Level The number of concurrent clients used during the test Time taken for tests This is the time taken from the moment the first socket connection is created to the moment the last response is received Complete requests The number of successful responses received Failed requests The number of requests that were considered a failure. If the number is greater than zero, another line will be printed showing the number of requests that failed due to connecting, reading, incorrect content length, or exceptions. Write errors The number of errors that failed during write (broken pipe). Non-2xx responses The number of responses that were not in the 200 series of response codes. If all responses were 200, this field is not printed. Keep-Alive requests The number of connections that resulted in Keep-Alive requests Total body sent If configured to send data as part of the test, this is the total number of bytes sent during the tests. This field is omitted if the test did not include a body to send. Total transferred The total number of bytes received from the server. This number is essentially the number of bytes sent over the wire. HTML transferred The total number of document bytes received from the server. This number excludes bytes received in HTTP headers Requests per second This is the number of requests per second. This value is the result of dividing the number of requests by the total time taken Time per request The average time spent per request. The first value is calculated with the formula `concurrency * timetaken * 1000 / done` while the second value is calculated with the formula `timetaken * 1000 / done` Transfer rate The rate of transfer as calculated by the formula `totalread / 1024 / timetaken` Bugs ---- There are various statically declared buffers of fixed length. Combined with the lazy parsing of the command line arguments, the response headers from the server and other external inputs, this might bite you. It does not implement HTTP/1.x fully; only accepts some 'expected' forms of responses. The rather heavy use of `strstr(3)` shows up top in profile, which might indicate a performance problem; *i.e.*, you would measure the `ab` performance rather than the server's. apache_http_server dbmmanage - Manage user authentication files in DBM format dbmmanage - Manage user authentication files in DBM format ========================================================== `dbmmanage` is used to create and update the DBM format files used to store usernames and password for basic authentication of HTTP users via `[mod\_authn\_dbm](../mod/mod_authn_dbm)`. Resources available from the Apache HTTP server can be restricted to just the users listed in the files created by `dbmmanage`. This program can only be used when the usernames are stored in a DBM file. To use a flat-file database see `<htpasswd>`. Another tool to maintain a DBM password database is `<htdbm>`. This manual page only lists the command line arguments. For details of the directives necessary to configure user authentication in `<httpd>` see the httpd manual, which is part of the Apache distribution or can be found at <http://httpd.apache.org/>. Synopsis -------- ``` dbmmanage [ encoding ] filename add|adduser|check|delete|update username [ encpasswd [ group[,group...] [ comment ] ] ] ``` ``` dbmmanage filename view [ username ] ``` ``` dbmmanage filename import ``` Options ------- `filename` The filename of the DBM format file. Usually without the extension `.db`, `.pag`, or `.dir`. `username` The user for which the operations are performed. The username may not contain a colon (`:`). `encpasswd` This is the already encrypted password to use for the `update` and `add` commands. You may use a hyphen (`-`) if you want to get prompted for the password, but fill in the fields afterwards. Additionally when using the `update` command, a period (`.`) keeps the original password untouched. `group` A group, which the user is member of. A groupname may not contain a colon (`:`). You may use a hyphen (`-`) if you don't want to assign the user to a group, but fill in the comment field. Additionally when using the `update` command, a period (`.`) keeps the original groups untouched. `comment` This is the place for your opaque comments about the user, like realname, mailaddress or such things. The server will ignore this field. ### Encodings `-d` crypt encryption (default, except on Win32, Netware) `-m` MD5 encryption (default on Win32, Netware) `-s` SHA1 encryption `-p` plaintext (*not recommended*) ### Commands `add` Adds an entry for username to filename using the encrypted password encpasswd. ``` dbmmanage passwords.dat add rbowen foKntnEF3KSXA ``` `adduser` Asks for a password and then adds an entry for username to filename. ``` dbmmanage passwords.dat adduser krietz ``` `check` Asks for a password and then checks if username is in filename and if it's password matches the specified one. ``` dbmmanage passwords.dat check rbowen ``` `delete` Deletes the username entry from filename. ``` dbmmanage passwords.dat delete rbowen ``` `import` Reads `username:password` entries (one per line) from `STDIN` and adds them to filename. The passwords already have to be crypted. `update` Same as the `adduser` command, except that it makes sure username already exists in filename. ``` dbmmanage passwords.dat update rbowen ``` `view` Just displays the contents of the DBM file. If you specify a username, it displays the particular record only. ``` dbmmanage passwords.dat view ``` Bugs ---- One should be aware that there are a number of different DBM file formats in existence, and with all likelihood, libraries for more than one format may exist on your system. The three primary examples are SDBM, NDBM, the GNU project's GDBM, and Berkeley DB 2. Unfortunately, all these libraries use different file formats, and you must make sure that the file format used by filename is the same format that `dbmmanage` expects to see. `dbmmanage` currently has no way of determining what type of DBM file it is looking at. If used against the wrong format, will simply return nothing, or may create a different DBM file with a different name, or at worst, it may corrupt the DBM file if you were attempting to write to it. `dbmmanage` has a list of DBM format preferences, defined by the `@AnyDBM::ISA` array near the beginning of the program. Since we prefer the Berkeley DB 2 file format, the order in which `dbmmanage` will look for system libraries is Berkeley DB 2, then NDBM, then GDBM and then SDBM. The first library found will be the library `dbmmanage` will attempt to use for all DBM file transactions. This ordering is slightly different than the standard `@AnyDBM::ISA` ordering in Perl, as well as the ordering used by the simple `dbmopen()` call in Perl, so if you use any other utilities to manage your DBM files, they must also follow this preference ordering. Similar care must be taken if using programs in other languages, like C, to access these files. One can usually use the `file` program supplied with most Unix systems to see what format a DBM file is in. apache_http_server log_server_status - Log periodic status summaries log\_server\_status - Log periodic status summaries =================================================== This perl script is designed to be run at a frequent interval by something like cron. It connects to the server and downloads the status information. It reformats the information to a single line and logs it to a file. Adjust the variables at the top of the script to specify the location of the resulting logfile. `[mod\_status](../mod/mod_status)` will need to be loaded and configured in order for this script to do its job. Usage ----- The script contains the following section. ``` my $wherelog = "/usr/local/apache2/logs/"; # Logs will be like "/usr/local/apache2/logs/19960312" my $server = "localhost"; # Name of server, could be "www.foo.com" my $port = "80"; # Port on server my $request = "/server-status/?auto"; # Request to send ``` You'll need to ensure that these variables have the correct values, and you'll need to have the `/server-status` handler configured at the location specified, and the specified log location needs to be writable by the user which will run the script. Run the script periodically via cron to produce a daily log file, which can then be used for statistical analysis. apache_http_server rotatelogs - Piped logging program to rotate Apache logs rotatelogs - Piped logging program to rotate Apache logs ======================================================== `rotatelogs` is a simple program for use in conjunction with Apache's piped logfile feature. It supports rotation based on a time interval or maximum size of the log. Synopsis -------- ``` rotatelogs [ -l ] [ -L linkname ] [ -p program ] [ -f ] [ -D ] [ -t ] [ -v ] [ -e ] [ -c ] [ -n number-of-files ] logfile rotationtime|filesize(B|K|M|G) [ offset ] ``` Options ------- `-l` Causes the use of local time rather than GMT as the base for the interval or for `strftime(3)` formatting with size-based rotation. `-L` linkname Causes a hard link to be made from the current logfile to the specified link name. This can be used to watch the log continuously across rotations using a command like `tail -F linkname`. If the linkname is not an absolute path, it is relative to `rotatelogs`' working directory, which is the `[ServerRoot](../mod/core#serverroot)` when `rotatelogs` is run by the server. `-p` program If given, `rotatelogs` will execute the specified program every time a new log file is opened. The filename of the newly opened file is passed as the first argument to the program. If executing after a rotation, the old log file is passed as the second argument. `rotatelogs` does not wait for the specified program to terminate before continuing to operate, and will not log any error code returned on termination. The spawned program uses the same stdin, stdout, and stderr as rotatelogs itself, and also inherits the environment. `-f` Causes the logfile to be opened immediately, as soon as `rotatelogs` starts, instead of waiting for the first logfile entry to be read (for non-busy sites, there may be a substantial delay between when the server is started and when the first request is handled, meaning that the associated logfile does not "exist" until then, which causes problems from some automated logging tools) `-D` Creates the parent directories of the path that the log file will be placed in if they do not already exist. This allows `strftime(3)` formatting to be used in the path and not just the filename. `-t` Causes the logfile to be truncated instead of rotated. This is useful when a log is processed in real time by a command like tail, and there is no need for archived data. No suffix will be added to the filename, however format strings containing '%' characters will be respected. `-v` Produce verbose output on STDERR. The output contains the result of the configuration parsing, and all file open and close actions. `-e` Echo logs through to stdout. Useful when logs need to be further processed in real time by a further tool in the chain. `-c` Create log file for each interval, even if empty. `-n number-of-files` Use a circular list of filenames without timestamps. With -n 3, the series of log files opened would be "logfile", "logfile.1", "logfile.2", then overwriting "logfile". Available in 2.4.5 and later. `logfile` The path plus basename of the logfile. If logfile includes any '%' characters, it is treated as a format string for `strftime(3)`. Otherwise, the suffix .nnnnnnnnnn is automatically added and is the time in seconds (unless the -t option is used). Both formats compute the start time from the beginning of the current period. For example, if a rotation time of 86400 is specified, the hour, minute, and second fields created from the `strftime(3)` format will all be zero, referring to the beginning of the current 24-hour period (midnight). When using `strftime(3)` filename formatting, be sure the log file format has enough granularity to produce a different file name each time the logs are rotated. Otherwise rotation will overwrite the same file instead of starting a new one. For example, if logfile was `/var/log/errorlog.%Y-%m-%d` with log rotation at 5 megabytes, but 5 megabytes was reached twice in the same day, the same log file name would be produced and log rotation would keep writing to the same file. If the logfile is not an absolute path, it is relative to `rotatelogs`' working directory, which is the `[ServerRoot](../mod/core#serverroot)` when `rotatelogs` is run by the server. `rotationtime` The time between log file rotations in seconds. The rotation occurs at the beginning of this interval. For example, if the rotation time is 3600, the log file will be rotated at the beginning of every hour; if the rotation time is 86400, the log file will be rotated every night at midnight. (If no data is logged during an interval, no file will be created.) `filesize(B|K|M|G)` The maximum file size in followed by exactly one of the letters `B` (Bytes), `K` (KBytes), `M` (MBytes) or `G` (GBytes). When time and size are specified, the size must be given after the time. Rotation will occur whenever either time or size limits are reached. `offset` The number of minutes offset from UTC. If omitted, zero is assumed and UTC is used. For example, to use local time in the zone UTC -5 hours, specify a value of `-300` for this argument. In most cases, `-l` should be used instead of specifying an offset. Examples -------- ``` CustomLog "|bin/rotatelogs /var/log/logfile 86400" common ``` This creates the files /var/log/logfile.nnnn where nnnn is the system time at which the log nominally starts (this time will always be a multiple of the rotation time, so you can synchronize cron scripts with it). At the end of each rotation time (here after 24 hours) a new log is started. ``` CustomLog "|bin/rotatelogs -l /var/log/logfile.%Y.%m.%d 86400" common ``` This creates the files /var/log/logfile.yyyy.mm.dd where yyyy is the year, mm is the month, and dd is the day of the month. Logging will switch to a new file every day at midnight, local time. ``` CustomLog "|bin/rotatelogs /var/log/logfile 5M" common ``` This configuration will rotate the logfile whenever it reaches a size of 5 megabytes. ``` ErrorLog "|bin/rotatelogs /var/log/errorlog.%Y-%m-%d-%H_%M_%S 5M" ``` This configuration will rotate the error logfile whenever it reaches a size of 5 megabytes, and the suffix to the logfile name will be created of the form `errorlog.YYYY-mm-dd-HH_MM_SS`. ``` CustomLog "|bin/rotatelogs -t /var/log/logfile 86400" common ``` This creates the file /var/log/logfile, truncating the file at startup and then truncating the file once per day. It is expected in this scenario that a separate process (such as tail) would process the file in real time. Portability ----------- The following logfile format string substitutions should be supported by all `strftime(3)` implementations, see the `strftime(3)` man page for library-specific extensions. | | | | --- | --- | | `%A` | full weekday name (localized) | | `%a` | 3-character weekday name (localized) | | `%B` | full month name (localized) | | `%b` | 3-character month name (localized) | | `%c` | date and time (localized) | | `%d` | 2-digit day of month | | `%H` | 2-digit hour (24 hour clock) | | `%I` | 2-digit hour (12 hour clock) | | `%j` | 3-digit day of year | | `%M` | 2-digit minute | | `%m` | 2-digit month | | `%p` | am/pm of 12 hour clock (localized) | | `%S` | 2-digit second | | `%U` | 2-digit week of year (Sunday first day of week) | | `%W` | 2-digit week of year (Monday first day of week) | | `%w` | 1-digit weekday (Sunday first day of week) | | `%X` | time (localized) | | `%x` | date (localized) | | `%Y` | 4-digit year | | `%y` | 2-digit year | | `%Z` | time zone name | | `%%` | literal `%' |
programming_docs
apache_http_server apxs - APache eXtenSion tool apxs - APache eXtenSion tool ============================ `apxs` is a tool for building and installing extension modules for the Apache HyperText Transfer Protocol (HTTP) server. This is achieved by building a dynamic shared object (DSO) from one or more source or object files which then can be loaded into the Apache server under runtime via the `[LoadModule](../mod/mod_so#loadmodule)` directive from `[mod\_so](../mod/mod_so)`. So to use this extension mechanism your platform has to support the DSO feature and your Apache `<httpd>` binary has to be built with the `[mod\_so](../mod/mod_so)` module. The `apxs` tool automatically complains if this is not the case. You can check this yourself by manually running the command ``` $ httpd -l ``` The module `[mod\_so](../mod/mod_so)` should be part of the displayed list. If these requirements are fulfilled you can easily extend your Apache server's functionality by installing your own modules with the DSO mechanism by the help of this `apxs` tool: ``` $ apxs -i -a -c mod_foo.c gcc -fpic -DSHARED_MODULE -I/path/to/apache/include -c mod_foo.c ld -Bshareable -o mod_foo.so mod_foo.o cp mod_foo.so /path/to/apache/modules/mod_foo.so chmod 755 /path/to/apache/modules/mod_foo.so [activating module `foo' in /path/to/apache/etc/httpd.conf] $ apachectl restart /path/to/apache/sbin/apachectl restart: httpd not running, trying to start [Tue Mar 31 11:27:55 1998] [debug] mod_so.c(303): loaded module foo_module /path/to/apache/sbin/apachectl restart: httpd started $ _ ``` The arguments files can be any C source file (.c), a object file (.o) or even a library archive (.a). The `apxs` tool automatically recognizes these extensions and automatically used the C source files for compilation while just using the object and archive files for the linking phase. But when using such pre-compiled objects make sure they are compiled for position independent code (PIC) to be able to use them for a dynamically loaded shared object. For instance with GCC you always just have to use `-fpic`. For other C compilers consult its manual page or at watch for the flags `apxs` uses to compile the object files. For more details about DSO support in Apache read the documentation of `[mod\_so](../mod/mod_so)` or perhaps even read the `src/modules/standard/mod_so.c` source file. Synopsis -------- ``` apxs -g [ -S name=value ] -n modname ``` ``` apxs -q [ -v ] [ -S name=value ] query ... ``` ``` apxs -c [ -S name=value ] [ -o dsofile ] [ -I incdir ] [ -D name=value ] [ -L libdir ] [ -l libname ] [ -Wc,compiler-flags ] [ -Wl,linker-flags ] files ... ``` ``` apxs -i [ -S name=value ] [ -n modname ] [ -a ] [ -A ] dso-file ... ``` ``` apxs -e [ -S name=value ] [ -n modname ] [ -a ] [ -A ] dso-file ... ``` Options ------- ### Common Options `-n modname` This explicitly sets the module name for the `-i` (install) and `-g` (template generation) option. Use this to explicitly specify the module name. For option `-g` this is required, for option `-i` the `apxs` tool tries to determine the name from the source or (as a fallback) at least by guessing it from the filename. ### Query Options `-q` Performs a query for variables and environment settings used to build `httpd`. When invoked without query parameters, it prints all known variables and their values. The optional `-v` parameter formats the list output. Use this to manually determine settings used to build the `httpd` that will load your module. For instance use ``` INC=-I`apxs -q INCLUDEDIR` ``` inside your own Makefiles if you need manual access to Apache's C header files. ### Configuration Options `-S name=value` This option changes the apxs settings described above. ### Template Generation Options `-g` This generates a subdirectory name (see option `-n`) and there two files: A sample module source file named `mod_name.c` which can be used as a template for creating your own modules or as a quick start for playing with the apxs mechanism. And a corresponding `Makefile` for even easier build and installing of this module. ### DSO Compilation Options `-c` This indicates the compilation operation. It first compiles the C source files (.c) of files into corresponding object files (.o) and then builds a dynamically shared object in dsofile by linking these object files plus the remaining object files (.o and .a) of files. If no `-o` option is specified the output file is guessed from the first filename in files and thus usually defaults to `mod_name.so`. `-o dsofile` Explicitly specifies the filename of the created dynamically shared object. If not specified and the name cannot be guessed from the files list, the fallback name `mod_unknown.so` is used. `-D name=value` This option is directly passed through to the compilation command(s). Use this to add your own defines to the build process. `-I incdir` This option is directly passed through to the compilation command(s). Use this to add your own include directories to search to the build process. `-L libdir` This option is directly passed through to the linker command. Use this to add your own library directories to search to the build process. `-l libname` This option is directly passed through to the linker command. Use this to add your own libraries to search to the build process. `-Wc,compiler-flags` This option passes compiler-flags as additional flags to the `libtool --mode=compile` command. Use this to add local compiler-specific options. `-Wl,linker-flags` This option passes linker-flags as additional flags to the `libtool --mode=link` command. Use this to add local linker-specific options. `-p` This option causes apxs to link against the apr/apr-util libraries. This is useful when compiling helper programs that use the apr/apr-util libraries. ### DSO Installation and Configuration Options `-i` This indicates the installation operation and installs one or more dynamically shared objects into the server's modules directory. `-a` This activates the module by automatically adding a corresponding `[LoadModule](../mod/mod_so#loadmodule)` line to Apache's `httpd.conf` configuration file, or by enabling it if it already exists. `-A` Same as option `-a` but the created `[LoadModule](../mod/mod_so#loadmodule)` directive is prefixed with a hash sign (`#`), *i.e.*, the module is just prepared for later activation but initially disabled. `-e` This indicates the editing operation, which can be used with the `-a` and `-A` options similarly to the `-i` operation to edit Apache's `httpd.conf` configuration file without attempting to install the module. Examples -------- Assume you have an Apache module named `mod_foo.c` available which should extend Apache's server functionality. To accomplish this you first have to compile the C source into a shared object suitable for loading into the Apache server under runtime via the following command: ``` $ apxs -c mod_foo.c /path/to/libtool --mode=compile gcc ... -c mod_foo.c /path/to/libtool --mode=link gcc ... -o mod_foo.la mod_foo.slo $ _ ``` Then you have to update the Apache configuration by making sure a `[LoadModule](../mod/mod_so#loadmodule)` directive is present to load this shared object. To simplify this step `apxs` provides an automatic way to install the shared object in its "modules" directory and updating the `httpd.conf` file accordingly. This can be achieved by running: ``` $ apxs -i -a mod_foo.la /path/to/instdso.sh mod_foo.la /path/to/apache/modules /path/to/libtool --mode=install cp mod_foo.la /path/to/apache/modules ... chmod 755 /path/to/apache/modules/mod_foo.so [activating module `foo' in /path/to/apache/conf/httpd.conf] $ _ ``` This way a line named ``` LoadModule foo_module modules/mod_foo.so ``` is added to the configuration file if still not present. If you want to have this disabled per default use the `-A` option, *i.e.* ``` $ apxs -i -A mod_foo.c ``` For a quick test of the apxs mechanism you can create a sample Apache module template plus a corresponding Makefile via: ``` $ apxs -g -n foo Creating [DIR] foo Creating [FILE] foo/Makefile Creating [FILE] foo/modules.mk Creating [FILE] foo/mod_foo.c Creating [FILE] foo/.deps $ _ ``` Then you can immediately compile this sample module into a shared object and load it into the Apache server: ``` $ cd foo $ make all reload apxs -c mod_foo.c /path/to/libtool --mode=compile gcc ... -c mod_foo.c /path/to/libtool --mode=link gcc ... -o mod_foo.la mod_foo.slo apxs -i -a -n "foo" mod_foo.la /path/to/instdso.sh mod_foo.la /path/to/apache/modules /path/to/libtool --mode=install cp mod_foo.la /path/to/apache/modules ... chmod 755 /path/to/apache/modules/mod_foo.so [activating module `foo' in /path/to/apache/conf/httpd.conf] apachectl restart /path/to/apache/sbin/apachectl restart: httpd not running, trying to start [Tue Mar 31 11:27:55 1998] [debug] mod_so.c(303): loaded module foo_module /path/to/apache/sbin/apachectl restart: httpd started $ _ ``` apache_http_server htdbm - Manipulate DBM password databases htdbm - Manipulate DBM password databases ========================================= `htdbm` is used to manipulate the DBM format files used to store usernames and password for basic authentication of HTTP users via `[mod\_authn\_dbm](../mod/mod_authn_dbm)`. See the `<dbmmanage>` documentation for more information about these DBM files. Synopsis -------- ``` htdbm [ -TDBTYPE ] [ -i ] [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] filename username ``` ``` htdbm -b [ -TDBTYPE ] [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] filename username password ``` ``` htdbm -n [ -i ] [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] username ``` ``` htdbm -nb [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] username password ``` ``` htdbm -v [ -TDBTYPE ] [ -i ] [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] filename username ``` ``` htdbm -vb [ -TDBTYPE ] [ -c ] [ -m | -B | -d | -s | -p ] [ -C cost ] [ -t ] [ -v ] filename username password ``` ``` htdbm -x [ -TDBTYPE ] filename username ``` ``` htdbm -l [ -TDBTYPE ] ``` Options ------- `-b` Use batch mode; *i.e.*, get the password from the command line rather than prompting for it. This option should be used with extreme care, since **the password is clearly visible** on the command line. For script use see the `-i` option. `-i` Read the password from stdin without verification (for script usage). `-c` Create the passwdfile. If passwdfile already exists, it is rewritten and truncated. This option cannot be combined with the `-n` option. `-n` Display the results on standard output rather than updating a database. This option changes the syntax of the command line, since the passwdfile argument (usually the first one) is omitted. It cannot be combined with the `-c` option. `-m` Use MD5 encryption for passwords. On Windows and Netware, this is the default. `-B` Use bcrypt encryption for passwords. This is currently considered to be very secure. `-C` This flag is only allowed in combination with `-B` (bcrypt encryption). It sets the computing time used for the bcrypt algorithm (higher is more secure but slower, default: 5, valid: 4 to 31). `-d` Use `crypt()` encryption for passwords. The default on all platforms but Windows and Netware. Though possibly supported by `htdbm` on all platforms, it is not supported by the `<httpd>` server on Windows and Netware. This algorithm is **insecure** by today's standards. `-s` Use SHA encryption for passwords. Facilitates migration from/to Netscape servers using the LDAP Directory Interchange Format (ldif). This algorithm is **insecure** by today's standards. `-p` Use plaintext passwords. Though `htdbm` will support creation on all platforms, the `<httpd>` daemon will only accept plain text passwords on Windows and Netware. `-l` Print each of the usernames and comments from the database on stdout. `-v` Verify the username and password. The program will print a message indicating whether the supplied password is valid. If the password is invalid, the program exits with error code 3. `-x` Delete user. If the username exists in the specified DBM file, it will be deleted. `-t` Interpret the final parameter as a comment. When this option is specified, an additional string can be appended to the command line; this string will be stored in the "Comment" field of the database, associated with the specified username. `filename` The filename of the DBM format file. Usually without the extension `.db`, `.pag`, or `.dir`. If `-c` is given, the DBM file is created if it does not already exist, or updated if it does exist. `username` The username to create or update in passwdfile. If username does not exist in this file, an entry is added. If it does exist, the password is changed. `password` The plaintext password to be encrypted and stored in the DBM file. Used only with the `-b` flag. `-TDBTYPE` Type of DBM file (SDBM, GDBM, DB, or "default"). Bugs ---- One should be aware that there are a number of different DBM file formats in existence, and with all likelihood, libraries for more than one format may exist on your system. The three primary examples are SDBM, NDBM, GNU GDBM, and Berkeley/Sleepycat DB 2/3/4. Unfortunately, all these libraries use different file formats, and you must make sure that the file format used by filename is the same format that `htdbm` expects to see. `htdbm` currently has no way of determining what type of DBM file it is looking at. If used against the wrong format, will simply return nothing, or may create a different DBM file with a different name, or at worst, it may corrupt the DBM file if you were attempting to write to it. One can usually use the `file` program supplied with most Unix systems to see what format a DBM file is in. Exit Status ----------- `htdbm` returns a zero status ("true") if the username and password have been successfully added or updated in the DBM File. `htdbm` returns `1` if it encounters some problem accessing files, `2` if there was a syntax problem with the command line, `3` if the password was entered interactively and the verification entry didn't match, `4` if its operation was interrupted, `5` if a value is too long (username, filename, password, or final computed record), `6` if the username contains illegal characters (see the [Restrictions section](#restrictions)), and `7` if the file is not a valid DBM password file. Examples -------- ``` htdbm /usr/local/etc/apache/.htdbm-users jsmith ``` Adds or modifies the password for user `jsmith`. The user is prompted for the password. If executed on a Windows system, the password will be encrypted using the modified Apache MD5 algorithm; otherwise, the system's `crypt()` routine will be used. If the file does not exist, `htdbm` will do nothing except return an error. ``` htdbm -c /home/doe/public_html/.htdbm jane ``` Creates a new file and stores a record in it for user `jane`. The user is prompted for the password. If the file exists and cannot be read, or cannot be written, it is not altered and `htdbm` will display a message and return an error status. ``` htdbm -mb /usr/web/.htdbm-all jones Pwd4Steve ``` Encrypts the password from the command line (`Pwd4Steve`) using the MD5 algorithm, and stores it in the specified file. Security Considerations ----------------------- Web password files such as those managed by `htdbm` should *not* be within the Web server's URI space -- that is, they should not be fetchable with a browser. The use of the `-b` option is discouraged, since when it is used the unencrypted password appears on the command line. When using the `crypt()` algorithm, note that only the first 8 characters of the password are used to form the password. If the supplied password is longer, the extra characters will be silently discarded. The SHA encryption format does not use salting: for a given password, there is only one encrypted representation. The `crypt()` and MD5 formats permute the representation by prepending a random salt string, to make dictionary attacks against the passwords more difficult. The SHA and `crypt()` formats are insecure by today's standards. Restrictions ------------ On the Windows platform, passwords encrypted with `htdbm` are limited to no more than `255` characters in length. Longer passwords will be truncated to 255 characters. The MD5 algorithm used by `htdbm` is specific to the Apache software; passwords encrypted using it will not be usable with other Web servers. Usernames are limited to `255` bytes and may not include the character `:`. apache_http_server suexec - Switch user before executing external programs suexec - Switch user before executing external programs ======================================================= `suexec` is used by the Apache HTTP Server to switch to another user before executing CGI programs. In order to achieve this, it must run as `root`. Since the HTTP daemon normally doesn't run as `root`, the `suexec` executable needs the setuid bit set and must be owned by `root`. It should never be writable for any other person than `root`. For further information about the concepts and the security model of suexec please refer to the suexec documentation (<http://httpd.apache.org/docs/2.4/suexec.html>). Synopsis -------- ``` suexec -V ``` Options ------- `-V` If you are `root`, this option displays the compile options of `suexec`. For security reasons all configuration options are changeable only at compile time. apache_http_server htdigest - manage user files for digest authentication htdigest - manage user files for digest authentication ====================================================== `htdigest` is used to create and update the flat-files used to store usernames, realm and password for digest authentication of HTTP users. Resources available from the Apache HTTP server can be restricted to just the users listed in the files created by `htdigest`. This manual page only lists the command line arguments. For details of the directives necessary to configure digest authentication in `<httpd>` see the Apache manual, which is part of the Apache distribution or can be found at <http://httpd.apache.org/>. Synopsis -------- ``` htdigest [ -c ] passwdfile realm username ``` Options ------- `-c` Create the passwdfile. If passwdfile already exists, it is deleted first. `passwdfile` Name of the file to contain the username, realm and password. If `-c` is given, this file is created if it does not already exist, or deleted and recreated if it does exist. `realm` The realm name to which the user name belongs. See <http://tools.ietf.org/html/rfc2617#section-3.2.1> for more details. `username` The user name to create or update in passwdfile. If username does not exist is this file, an entry is added. If it does exist, the password is changed. Security Considerations ----------------------- This program is not safe as a setuid executable. Do *not* make it setuid. apache_http_server Apache Tutorial: Dynamic Content with CGI Apache Tutorial: Dynamic Content with CGI ========================================= Introduction ------------ | Related Modules | Related Directives | | --- | --- | | * `[mod\_alias](../mod/mod_alias)` * `[mod\_cgi](../mod/mod_cgi)` * `[mod\_cgid](../mod/mod_cgid)` | * `[AddHandler](../mod/mod_mime#addhandler)` * `[Options](../mod/core#options)` * `[ScriptAlias](../mod/mod_alias#scriptalias)` | The CGI (Common Gateway Interface) defines a way for a web server to interact with external content-generating programs, which are often referred to as CGI programs or CGI scripts. It is a simple way to put dynamic content on your web site, using whatever programming language you're most familiar with. This document will be an introduction to setting up CGI on your Apache web server, and getting started writing CGI programs. Configuring Apache to permit CGI -------------------------------- In order to get your CGI programs to work properly, you'll need to have Apache configured to permit CGI execution. There are several ways to do this. Note: If Apache has been built with shared module support you need to ensure that the module is loaded; in your `httpd.conf` you need to make sure the `[LoadModule](../mod/mod_so#loadmodule)` directive has not been commented out. A correctly configured directive may look like this: ``` LoadModule cgid_module modules/mod_cgid.so ``` On Windows, or using a non-threaded MPM like prefork, A correctly configured directive may look like this: ``` LoadModule cgi_module modules/mod_cgi.so ``` ### ScriptAlias The `[ScriptAlias](../mod/mod_alias#scriptalias)` directive tells Apache that a particular directory is set aside for CGI programs. Apache will assume that every file in this directory is a CGI program, and will attempt to execute it, when that particular resource is requested by a client. The `[ScriptAlias](../mod/mod_alias#scriptalias)` directive looks like: ``` ScriptAlias "/cgi-bin/" "/usr/local/apache2/cgi-bin/" ``` The example shown is from your default `httpd.conf` configuration file, if you installed Apache in the default location. The `[ScriptAlias](../mod/mod_alias#scriptalias)` directive is much like the `[Alias](../mod/mod_alias#alias)` directive, which defines a URL prefix that is to mapped to a particular directory. `Alias` and `ScriptAlias` are usually used for directories that are outside of the `[DocumentRoot](../mod/core#documentroot)` directory. The difference between `Alias` and `ScriptAlias` is that `ScriptAlias` has the added meaning that everything under that URL prefix will be considered a CGI program. So, the example above tells Apache that any request for a resource beginning with `/cgi-bin/` should be served from the directory `/usr/local/apache2/cgi-bin/`, and should be treated as a CGI program. For example, if the URL `http://www.example.com/cgi-bin/test.pl` is requested, Apache will attempt to execute the file `/usr/local/apache2/cgi-bin/test.pl` and return the output. Of course, the file will have to exist, and be executable, and return output in a particular way, or Apache will return an error message. ### CGI outside of ScriptAlias directories CGI programs are often restricted to `[ScriptAlias](../mod/mod_alias#scriptalias)`'ed directories for security reasons. In this way, administrators can tightly control who is allowed to use CGI programs. However, if the proper security precautions are taken, there is no reason why CGI programs cannot be run from arbitrary directories. For example, you may wish to let users have web content in their home directories with the `[UserDir](../mod/mod_userdir#userdir)` directive. If they want to have their own CGI programs, but don't have access to the main `cgi-bin` directory, they will need to be able to run CGI programs elsewhere. There are two steps to allowing CGI execution in an arbitrary directory. First, the `cgi-script` handler must be activated using the `[AddHandler](../mod/mod_mime#addhandler)` or `[SetHandler](../mod/core#sethandler)` directive. Second, `ExecCGI` must be specified in the `[Options](../mod/core#options)` directive. ### Explicitly using Options to permit CGI execution You could explicitly use the `[Options](../mod/core#options)` directive, inside your main server configuration file, to specify that CGI execution was permitted in a particular directory: ``` <Directory "/usr/local/apache2/htdocs/somedir"> Options +ExecCGI </Directory> ``` The above directive tells Apache to permit the execution of CGI files. You will also need to tell the server what files are CGI files. The following `[AddHandler](../mod/mod_mime#addhandler)` directive tells the server to treat all files with the `cgi` or `pl` extension as CGI programs: ``` AddHandler cgi-script .cgi .pl ``` ### .htaccess files The [`.htaccess` tutorial](htaccess) shows how to activate CGI programs if you do not have access to `httpd.conf`. ### User Directories To allow CGI program execution for any file ending in `.cgi` in users' directories, you can use the following configuration. ``` <Directory "/home/*/public_html"> Options +ExecCGI AddHandler cgi-script .cgi </Directory> ``` If you wish designate a `cgi-bin` subdirectory of a user's directory where everything will be treated as a CGI program, you can use the following. ``` <Directory "/home/*/public_html/cgi-bin"> Options ExecCGI SetHandler cgi-script </Directory> ``` Writing a CGI program --------------------- There are two main differences between ``regular'' programming, and CGI programming. First, all output from your CGI program must be preceded by a [MIME-type](https://httpd.apache.org/docs/2.4/en/glossary.html#mime-type "see glossary") header. This is HTTP header that tells the client what sort of content it is receiving. Most of the time, this will look like: ``` Content-type: text/html ``` Secondly, your output needs to be in HTML, or some other format that a browser will be able to display. Most of the time, this will be HTML, but occasionally you might write a CGI program that outputs a gif image, or other non-HTML content. Apart from those two things, writing a CGI program will look a lot like any other program that you might write. ### Your first CGI program The following is an example CGI program that prints one line to your browser. Type in the following, save it to a file called `first.pl`, and put it in your `cgi-bin` directory. ``` #!/usr/bin/perl print "Content-type: text/html\n\n"; print "Hello, World."; ``` Even if you are not familiar with Perl, you should be able to see what is happening here. The first line tells Apache (or whatever shell you happen to be running under) that this program can be executed by feeding the file to the interpreter found at the location `/usr/bin/perl`. The second line prints the content-type declaration we talked about, followed by two carriage-return newline pairs. This puts a blank line after the header, to indicate the end of the HTTP headers, and the beginning of the body. The third line prints the string "Hello, World.". And that's the end of it. If you open your favorite browser and tell it to get the address `http://www.example.com/cgi-bin/first.pl` or wherever you put your file, you will see the one line `Hello, World.` appear in your browser window. It's not very exciting, but once you get that working, you'll have a good chance of getting just about anything working. But it's still not working! --------------------------- There are four basic things that you may see in your browser when you try to access your CGI program from the web: The output of your CGI program Great! That means everything worked fine. If the output is correct, but the browser is not processing it correctly, make sure you have the correct `Content-Type` set in your CGI program. The source code of your CGI program or a "POST Method Not Allowed" message That means that you have not properly configured Apache to process your CGI program. Reread the section on [configuring Apache](#configuring) and try to find what you missed. A message starting with "Forbidden" That means that there is a permissions problem. Check the [Apache error log](#errorlogs) and the section below on [file permissions](#permissions). A message saying "Internal Server Error" If you check the [Apache error log](#errorlogs), you will probably find that it says "Premature end of script headers", possibly along with an error message generated by your CGI program. In this case, you will want to check each of the below sections to see what might be preventing your CGI program from emitting the proper HTTP headers. ### File permissions Remember that the server does not run as you. That is, when the server starts up, it is running with the permissions of an unprivileged user - usually `nobody`, or `www` - and so it will need extra permissions to execute files that are owned by you. Usually, the way to give a file sufficient permissions to be executed by `nobody` is to give everyone execute permission on the file: ``` chmod a+x first.pl ``` Also, if your program reads from, or writes to, any other files, those files will need to have the correct permissions to permit this. ### Path information and environment When you run a program from your command line, you have certain information that is passed to the shell without you thinking about it. For example, you have a `PATH`, which tells the shell where it can look for files that you reference. When a program runs through the web server as a CGI program, it may not have the same `PATH`. Any programs that you invoke in your CGI program (like `sendmail`, for example) will need to be specified by a full path, so that the shell can find them when it attempts to execute your CGI program. A common manifestation of this is the path to the script interpreter (often `perl`) indicated in the first line of your CGI program, which will look something like: ``` #!/usr/bin/perl ``` Make sure that this is in fact the path to the interpreter. When editing CGI scripts on Windows, end-of-line characters may be appended to the interpreter path. Ensure that files are then transferred to the server in ASCII mode. Failure to do so may result in "Command not found" warnings from the OS, due to the unrecognized end-of-line character being interpreted as a part of the interpreter filename. ### Missing environment variables If your CGI program depends on non-standard [environment variables](#env), you will need to assure that those variables are passed by Apache. When you miss HTTP headers from the environment, make sure they are formatted according to [RFC 2616](http://tools.ietf.org/html/rfc2616), section 4.2: Header names must start with a letter, followed only by letters, numbers or hyphen. Any header violating this rule will be dropped silently. ### Program errors Most of the time when a CGI program fails, it's because of a problem with the program itself. This is particularly true once you get the hang of this CGI stuff, and no longer make the above two mistakes. The first thing to do is to make sure that your program runs from the command line before testing it via the web server. For example, try: ``` cd /usr/local/apache2/cgi-bin ./first.pl ``` (Do not call the `perl` interpreter. The shell and Apache should find the interpreter using the [path information](#pathinformation) on the first line of the script.) The first thing you see written by your program should be a set of HTTP headers, including the `Content-Type`, followed by a blank line. If you see anything else, Apache will return the `Premature end of script headers` error if you try to run it through the server. See [Writing a CGI program](#writing) above for more details. ### Error logs The error logs are your friend. Anything that goes wrong generates message in the error log. You should always look there first. If the place where you are hosting your web site does not permit you access to the error log, you should probably host your site somewhere else. Learn to read the error logs, and you'll find that almost all of your problems are quickly identified, and quickly solved. ### Suexec The [suexec](../suexec) support program allows CGI programs to be run under different user permissions, depending on which virtual host or user home directory they are located in. Suexec has very strict permission checking, and any failure in that checking will result in your CGI programs failing with `Premature end of script headers`. To check if you are using suexec, run `apachectl -V` and check for the location of `SUEXEC_BIN`. If Apache finds an `[suexec](../programs/suexec)` binary there on startup, suexec will be activated. Unless you fully understand suexec, you should not be using it. To disable suexec, simply remove (or rename) the `[suexec](../programs/suexec)` binary pointed to by `SUEXEC_BIN` and then restart the server. If, after reading about [suexec](../suexec), you still wish to use it, then run `suexec -V` to find the location of the suexec log file, and use that log file to find what policy you are violating. What's going on behind the scenes? ---------------------------------- As you become more advanced in CGI programming, it will become useful to understand more about what's happening behind the scenes. Specifically, how the browser and server communicate with one another. Because although it's all very well to write a program that prints "Hello, World.", it's not particularly useful. ### Environment variables Environment variables are values that float around you as you use your computer. They are useful things like your path (where the computer searches for the actual file implementing a command when you type it), your username, your terminal type, and so on. For a full list of your normal, every day environment variables, type `env` at a command prompt. During the CGI transaction, the server and the browser also set environment variables, so that they can communicate with one another. These are things like the browser type (Netscape, IE, Lynx), the server type (Apache, IIS, WebSite), the name of the CGI program that is being run, and so on. These variables are available to the CGI programmer, and are half of the story of the client-server communication. The complete list of required variables is at [Common Gateway Interface RFC](http://www.ietf.org/rfc/rfc3875). This simple Perl CGI program will display all of the environment variables that are being passed around. Two similar programs are included in the `cgi-bin` directory of the Apache distribution. Note that some variables are required, while others are optional, so you may see some variables listed that were not in the official list. In addition, Apache provides many different ways for you to [add your own environment variables](../env) to the basic ones provided by default. ``` #!/usr/bin/perl use strict; use warnings; print "Content-type: text/html\n\n"; foreach my $key (keys %ENV) { print "$key --> $ENV{$key}<br>"; } ``` ### STDIN and STDOUT Other communication between the server and the client happens over standard input (`STDIN`) and standard output (`STDOUT`). In normal everyday context, `STDIN` means the keyboard, or a file that a program is given to act on, and `STDOUT` usually means the console or screen. When you `POST` a web form to a CGI program, the data in that form is bundled up into a special format and gets delivered to your CGI program over `STDIN`. The program then can process that data as though it was coming in from the keyboard, or from a file The "special format" is very simple. A field name and its value are joined together with an equals (=) sign, and pairs of values are joined together with an ampersand (&). Inconvenient characters like spaces, ampersands, and equals signs, are converted into their hex equivalent so that they don't gum up the works. The whole data string might look something like: `name=Rich%20Bowen&city=Lexington&state=KY&sidekick=Squirrel%20Monkey` You'll sometimes also see this type of string appended to a URL. When that is done, the server puts that string into the environment variable called `QUERY_STRING`. That's called a `GET` request. Your HTML form specifies whether a `GET` or a `POST` is used to deliver the data, by setting the `METHOD` attribute in the `FORM` tag. Your program is then responsible for splitting that string up into useful information. Fortunately, there are libraries and modules available to help you process this data, as well as handle other of the aspects of your CGI program. CGI modules/libraries --------------------- When you write CGI programs, you should consider using a code library, or module, to do most of the grunt work for you. This leads to fewer errors, and faster development. If you're writing CGI programs in Perl, modules are available on [CPAN](http://www.cpan.org/). The most popular module for this purpose is `CGI.pm`. You might also consider `CGI::Lite`, which implements a minimal set of functionality, which is all you need in most programs. If you're writing CGI programs in C, there are a variety of options. One of these is the `CGIC` library, from <https://web.mit.edu/wwwdev/www/cgic.html>. For more information -------------------- The current CGI specification is available in the [Common Gateway Interface RFC](http://www.ietf.org/rfc/rfc3875). When you post a question about a CGI problem that you're having, whether to a mailing list, or to a newsgroup, make sure you provide enough information about what happened, what you expected to happen, and how what actually happened was different, what server you're running, what language your CGI program was in, and, if possible, the offending code. This will make finding your problem much simpler. Note that questions about CGI problems should **never** be posted to the Apache bug database unless you are sure you have found a problem in the Apache source code.
programming_docs
apache_http_server Authentication and Authorization Authentication and Authorization ================================ Authentication is any process by which you verify that someone is who they claim they are. Authorization is any process by which someone is allowed to be where they want to go, or to have information that they want to have. For general access control, see the [Access Control How-To](access). Related Modules and Directives ------------------------------ There are three types of modules involved in the authentication and authorization process. You will usually need to choose at least one module from each group. * Authentication type (see the `[AuthType](../mod/mod_authn_core#authtype)` directive) + `[mod\_auth\_basic](../mod/mod_auth_basic)` + `[mod\_auth\_digest](../mod/mod_auth_digest)` * Authentication provider (see the `[AuthBasicProvider](../mod/mod_auth_basic#authbasicprovider)` and `[AuthDigestProvider](../mod/mod_auth_digest#authdigestprovider)` directives) + `[mod\_authn\_anon](../mod/mod_authn_anon)` + `[mod\_authn\_dbd](../mod/mod_authn_dbd)` + `[mod\_authn\_dbm](../mod/mod_authn_dbm)` + `[mod\_authn\_file](../mod/mod_authn_file)` + `[mod\_authnz\_ldap](../mod/mod_authnz_ldap)` + `[mod\_authn\_socache](../mod/mod_authn_socache)` * Authorization (see the `[Require](../mod/mod_authz_core#require)` directive) + `[mod\_authnz\_ldap](../mod/mod_authnz_ldap)` + `[mod\_authz\_dbd](../mod/mod_authz_dbd)` + `[mod\_authz\_dbm](../mod/mod_authz_dbm)` + `[mod\_authz\_groupfile](../mod/mod_authz_groupfile)` + `[mod\_authz\_host](../mod/mod_authz_host)` + `[mod\_authz\_owner](../mod/mod_authz_owner)` + `[mod\_authz\_user](../mod/mod_authz_user)` In addition to these modules, there are also `[mod\_authn\_core](../mod/mod_authn_core)` and `[mod\_authz\_core](../mod/mod_authz_core)`. These modules implement core directives that are core to all auth modules. The module `[mod\_authnz\_ldap](../mod/mod_authnz_ldap)` is both an authentication and authorization provider. The module `[mod\_authz\_host](../mod/mod_authz_host)` provides authorization and access control based on hostname, IP address or characteristics of the request, but is not part of the authentication provider system. For backwards compatibility with the mod\_access, there is a new module `[mod\_access\_compat](../mod/mod_access_compat)`. You probably also want to take a look at the [Access Control](access) howto, which discusses the various ways to control access to your server. Introduction ------------ If you have information on your web site that is sensitive or intended for only a small group of people, the techniques in this article will help you make sure that the people that see those pages are the people that you wanted to see them. This article covers the "standard" way of protecting parts of your web site that most of you are going to use. **Note:** If your data really needs to be secure, consider using `[mod\_ssl](../mod/mod_ssl)` in addition to any authentication. The Prerequisites ----------------- The directives discussed in this article will need to go either in your main server configuration file (typically in a `[<Directory>](../mod/core#directory)` section), or in per-directory configuration files (`.htaccess` files). If you plan to use `.htaccess` files, you will need to have a server configuration that permits putting authentication directives in these files. This is done with the `[AllowOverride](../mod/core#allowoverride)` directive, which specifies which directives, if any, may be put in per-directory configuration files. Since we're talking here about authentication, you will need an `[AllowOverride](../mod/core#allowoverride)` directive like the following: ``` AllowOverride AuthConfig ``` Or, if you are just going to put the directives directly in your main server configuration file, you will of course need to have write permission to that file. And you'll need to know a little bit about the directory structure of your server, in order to know where some files are kept. This should not be terribly difficult, and I'll try to make this clear when we come to that point. You will also need to make sure that the modules `[mod\_authn\_core](../mod/mod_authn_core)` and `[mod\_authz\_core](../mod/mod_authz_core)` have either been built into the httpd binary or loaded by the httpd.conf configuration file. Both of these modules provide core directives and functionality that are critical to the configuration and use of authentication and authorization in the web server. Getting it working ------------------ Here's the basics of password protecting a directory on your server. First, you need to create a password file. Exactly how you do this will vary depending on what authentication provider you have chosen. More on that later. To start with, we'll use a text password file. This file should be placed somewhere not accessible from the web. This is so that folks cannot download the password file. For example, if your documents are served out of `/usr/local/apache/htdocs`, you might want to put the password file(s) in `/usr/local/apache/passwd`. To create the file, use the `[htpasswd](../programs/htpasswd)` utility that came with Apache. This will be located in the `bin` directory of wherever you installed Apache. If you have installed Apache from a third-party package, it may be in your execution path. To create the file, type: ``` htpasswd -c /usr/local/apache/passwd/passwords rbowen ``` `[htpasswd](../programs/htpasswd)` will ask you for the password, and then ask you to type it again to confirm it: ``` # htpasswd -c /usr/local/apache/passwd/passwords rbowen New password: mypassword Re-type new password: mypassword Adding password for user rbowen ``` If `[htpasswd](../programs/htpasswd)` is not in your path, of course you'll have to type the full path to the file to get it to run. With a default installation, it's located at `/usr/local/apache2/bin/htpasswd` Next, you'll need to configure the server to request a password and tell the server which users are allowed access. You can do this either by editing the `httpd.conf` file or using an `.htaccess` file. For example, if you wish to protect the directory `/usr/local/apache/htdocs/secret`, you can use the following directives, either placed in the file `/usr/local/apache/htdocs/secret/.htaccess`, or placed in `httpd.conf` inside a <Directory "/usr/local/apache/htdocs/secret"> section. ``` AuthType Basic AuthName "Restricted Files" # (Following line optional) AuthBasicProvider file AuthUserFile "/usr/local/apache/passwd/passwords" Require user rbowen ``` Let's examine each of those directives individually. The `[AuthType](../mod/mod_authn_core#authtype)` directive selects the method that is used to authenticate the user. The most common method is `Basic`, and this is the method implemented by `[mod\_auth\_basic](../mod/mod_auth_basic)`. It is important to be aware, however, that Basic authentication sends the password from the client to the server unencrypted. This method should therefore not be used for highly sensitive data, unless accompanied by `[mod\_ssl](../mod/mod_ssl)`. Apache supports one other authentication method: `AuthType Digest`. This method is implemented by `[mod\_auth\_digest](../mod/mod_auth_digest)` and was intended to be more secure. This is no longer the case and the connection should be encrypted with `[mod\_ssl](../mod/mod_ssl)` instead. The `[AuthName](../mod/mod_authn_core#authname)` directive sets the Realm to be used in the authentication. The realm serves two major functions. First, the client often presents this information to the user as part of the password dialog box. Second, it is used by the client to determine what password to send for a given authenticated area. So, for example, once a client has authenticated in the `"Restricted Files"` area, it will automatically retry the same password for any area on the same server that is marked with the `"Restricted Files"` Realm. Therefore, you can prevent a user from being prompted more than once for a password by letting multiple restricted areas share the same realm. Of course, for security reasons, the client will always need to ask again for the password whenever the hostname of the server changes. The `[AuthBasicProvider](../mod/mod_auth_basic#authbasicprovider)` is, in this case, optional, since `file` is the default value for this directive. You'll need to use this directive if you are choosing a different source for authentication, such as `[mod\_authn\_dbm](../mod/mod_authn_dbm)` or `[mod\_authn\_dbd](../mod/mod_authn_dbd)`. The `[AuthUserFile](../mod/mod_authn_file#authuserfile)` directive sets the path to the password file that we just created with `[htpasswd](../programs/htpasswd)`. If you have a large number of users, it can be quite slow to search through a plain text file to authenticate the user on each request. Apache also has the ability to store user information in fast database files. The `[mod\_authn\_dbm](../mod/mod_authn_dbm)` module provides the `[AuthDBMUserFile](../mod/mod_authn_dbm#authdbmuserfile)` directive. These files can be created and manipulated with the `[dbmmanage](../programs/dbmmanage)` and `[htdbm](../programs/htdbm)` programs. Many other types of authentication options are available from third party modules. Finally, the `[Require](../mod/mod_authz_core#require)` directive provides the authorization part of the process by setting the user that is allowed to access this region of the server. In the next section, we discuss various ways to use the `[Require](../mod/mod_authz_core#require)` directive. Letting more than one person in ------------------------------- The directives above only let one person (specifically someone with a username of `rbowen`) into the directory. In most cases, you'll want to let more than one person in. This is where the `[AuthGroupFile](../mod/mod_authz_groupfile#authgroupfile)` comes in. If you want to let more than one person in, you'll need to create a group file that associates group names with a list of users in that group. The format of this file is pretty simple, and you can create it with your favorite editor. The contents of the file will look like this: ``` GroupName: rbowen dpitts sungo rshersey ``` That's just a list of the members of the group in a long line separated by spaces. To add a user to your already existing password file, type: ``` htpasswd /usr/local/apache/passwd/passwords dpitts ``` You'll get the same response as before, but it will be appended to the existing file, rather than creating a new file. (It's the `-c` that makes it create a new password file). Now, you need to modify your `.htaccess` file or `[<Directory>](../mod/core#directory)` block to look like the following: ``` AuthType Basic AuthName "By Invitation Only" # Optional line: AuthBasicProvider file AuthUserFile "/usr/local/apache/passwd/passwords" AuthGroupFile "/usr/local/apache/passwd/groups" Require group GroupName ``` Now, anyone that is listed in the group `GroupName`, and has an entry in the `password` file, will be let in, if they type the correct password. There's another way to let multiple users in that is less specific. Rather than creating a group file, you can just use the following directive: ``` Require valid-user ``` Using that rather than the `Require user rbowen` line will allow anyone in that is listed in the password file, and who correctly enters their password. Possible problems ----------------- Because of the way that Basic authentication is specified, your username and password must be verified every time you request a document from the server. This is even if you're reloading the same page, and for every image on the page (if they come from a protected directory). As you can imagine, this slows things down a little. The amount that it slows things down is proportional to the size of the password file, because it has to open up that file, and go down the list of users until it gets to your name. And it has to do this every time a page is loaded. A consequence of this is that there's a practical limit to how many users you can put in one password file. This limit will vary depending on the performance of your particular server machine, but you can expect to see slowdowns once you get above a few hundred entries, and may wish to consider a different authentication method at that time. Alternate password storage -------------------------- Because storing passwords in plain text files has the above problems, you may wish to store your passwords somewhere else, such as in a database. `[mod\_authn\_dbm](../mod/mod_authn_dbm)` and `[mod\_authn\_dbd](../mod/mod_authn_dbd)` are two modules which make this possible. Rather than selecting ``[AuthBasicProvider](../mod/mod_auth_basic#authbasicprovider)` file`, instead you can choose `dbm` or `dbd` as your storage format. To select a dbm file rather than a text file, for example: ``` <Directory "/www/docs/private"> AuthName "Private" AuthType Basic AuthBasicProvider dbm AuthDBMUserFile "/www/passwords/passwd.dbm" Require valid-user </Directory> ``` Other options are available. Consult the `[mod\_authn\_dbm](../mod/mod_authn_dbm)` documentation for more details. Using multiple providers ------------------------ With the introduction of the new provider based authentication and authorization architecture, you are no longer locked into a single authentication or authorization method. In fact any number of the providers can be mixed and matched to provide you with exactly the scheme that meets your needs. In the following example, both the file and LDAP based authentication providers are being used. ``` <Directory "/www/docs/private"> AuthName "Private" AuthType Basic AuthBasicProvider file ldap AuthUserFile "/usr/local/apache/passwd/passwords" AuthLDAPURL ldap://ldaphost/o=yourorg Require valid-user </Directory> ``` In this example the file provider will attempt to authenticate the user first. If it is unable to authenticate the user, the LDAP provider will be called. This allows the scope of authentication to be broadened if your organization implements more than one type of authentication store. Other authentication and authorization scenarios may include mixing one type of authentication with a different type of authorization. For example, authenticating against a password file yet authorizing against an LDAP directory. Just as multiple authentication providers can be implemented, multiple authorization methods can also be used. In this example both file group authorization as well as LDAP group authorization is being used. ``` <Directory "/www/docs/private"> AuthName "Private" AuthType Basic AuthBasicProvider file AuthUserFile "/usr/local/apache/passwd/passwords" AuthLDAPURL ldap://ldaphost/o=yourorg AuthGroupFile "/usr/local/apache/passwd/groups" Require group GroupName Require ldap-group cn=mygroup,o=yourorg </Directory> ``` To take authorization a little further, authorization container directives such as `[<RequireAll>](../mod/mod_authz_core#requireall)` and `[<RequireAny>](../mod/mod_authz_core#requireany)` allow logic to be applied so that the order in which authorization is handled can be completely controlled through the configuration. See [Authorization Containers](../mod/mod_authz_core#logic) for an example of how they may be applied. Beyond just authorization ------------------------- The way that authorization can be applied is now much more flexible than just a single check against a single data store. Ordering, logic and choosing how authorization will be done is now possible. ### Applying logic and ordering Controlling how and in what order authorization will be applied has been a bit of a mystery in the past. In Apache 2.2 a provider-based authentication mechanism was introduced to decouple the actual authentication process from authorization and supporting functionality. One of the side benefits was that authentication providers could be configured and called in a specific order which didn't depend on the load order of the auth module itself. This same provider based mechanism has been brought forward into authorization as well. What this means is that the `[Require](../mod/mod_authz_core#require)` directive not only specifies which authorization methods should be used, it also specifies the order in which they are called. Multiple authorization methods are called in the same order in which the `[Require](../mod/mod_authz_core#require)` directives appear in the configuration. With the introduction of authorization container directives such as `[<RequireAll>](../mod/mod_authz_core#requireall)` and `[<RequireAny>](../mod/mod_authz_core#requireany)`, the configuration also has control over when the authorization methods are called and what criteria determines when access is granted. See [Authorization Containers](../mod/mod_authz_core#logic) for an example of how they may be used to express complex authorization logic. By default all `[Require](../mod/mod_authz_core#require)` directives are handled as though contained within a `[<RequireAny>](../mod/mod_authz_core#requireany)` container directive. In other words, if any of the specified authorization methods succeed, then authorization is granted. ### Using authorization providers for access control Authentication by username and password is only part of the story. Frequently you want to let people in based on something other than who they are. Something such as where they are coming from. The authorization providers `all`, `env`, `host` and `ip` let you allow or deny access based on other host based criteria such as host name or ip address of the machine requesting a document. The usage of these providers is specified through the `[Require](../mod/mod_authz_core#require)` directive. This directive registers the authorization providers that will be called during the authorization stage of the request processing. For example: ``` Require ip address ``` where address is an IP address (or a partial IP address) or: ``` Require host domain\_name ``` where domain\_name is a fully qualified domain name (or a partial domain name); you may provide multiple addresses or domain names, if desired. For example, if you have someone spamming your message board, and you want to keep them out, you could do the following: ``` <RequireAll> Require all granted Require not ip 10.252.46.165 </RequireAll> ``` Visitors coming from that address will not be able to see the content covered by this directive. If, instead, you have a machine name, rather than an IP address, you can use that. ``` <RequireAll> Require all granted Require not host host.example.com </RequireAll> ``` And, if you'd like to block access from an entire domain, you can specify just part of an address or domain name: ``` <RequireAll> Require all granted Require not ip 192.168.205 Require not host phishers.example.com moreidiots.example Require not host ke </RequireAll> ``` Using `[<RequireAll>](../mod/mod_authz_core#requireall)` with multiple `[<Require>](../mod/mod_authz_core#require)` directives, each negated with `not`, will only allow access, if all of negated conditions are true. In other words, access will be blocked, if any of the negated conditions fails. ### Access Control backwards compatibility One of the side effects of adopting a provider based mechanism for authentication is that the previous access control directives `[Order](../mod/mod_access_compat#order)`, `[Allow](../mod/mod_access_compat#allow)`, `[Deny](../mod/mod_access_compat#deny)` and `[Satisfy](../mod/mod_access_compat#satisfy)` are no longer needed. However to provide backwards compatibility for older configurations, these directives have been moved to the `[mod\_access\_compat](../mod/mod_access_compat)` module. **Note** The directives provided by `[mod\_access\_compat](../mod/mod_access_compat)` have been deprecated by `[mod\_authz\_host](../mod/mod_authz_host)`. Mixing old directives like `[Order](../mod/mod_access_compat#order)`, `[Allow](../mod/mod_access_compat#allow)` or `[Deny](../mod/mod_access_compat#deny)` with new ones like `[Require](../mod/mod_authz_core#require)` is technically possible but discouraged. The `[mod\_access\_compat](../mod/mod_access_compat)` module was created to support configurations containing only old directives to facilitate the 2.4 upgrade. Please check the [upgrading](https://httpd.apache.org/docs/2.4/en/upgrading.html) guide for more information. Authentication Caching ---------------------- There may be times when authentication puts an unacceptable load on a provider or on your network. This is most likely to affect users of `[mod\_authn\_dbd](../mod/mod_authn_dbd)` (or third-party/custom providers). To deal with this, HTTPD 2.3/2.4 introduces a new caching provider `[mod\_authn\_socache](../mod/mod_authn_socache)` to cache credentials and reduce the load on the origin provider(s). This may offer a substantial performance boost to some users. More information ---------------- You should also read the documentation for `[mod\_auth\_basic](../mod/mod_auth_basic)` and `[mod\_authz\_host](../mod/mod_authz_host)` which contain some more information about how this all works. The directive `[<AuthnProviderAlias>](../mod/mod_authn_core#authnprovideralias)` can also help in simplifying certain authentication configurations. The various ciphers supported by Apache for authentication data are explained in [Password Encryptions](../misc/password_encryptions). And you may want to look at the [Access Control](access) howto, which discusses a number of related topics.
programming_docs
apache_http_server Reverse Proxy Guide Reverse Proxy Guide =================== In addition to being a "basic" web server, and providing static and dynamic content to end-users, Apache httpd (as well as most other web servers) can also act as a reverse proxy server, also-known-as a "gateway" server. In such scenarios, httpd itself does not generate or host the data, but rather the content is obtained by one or several backend servers, which normally have no direct connection to the external network. As httpd receives a request from a client, the request itself is *proxied* to one of these backend servers, which then handles the request, generates the content and then sends this content back to httpd, which then generates the actual HTTP response back to the client. There are numerous reasons for such an implementation, but generally the typical rationales are due to security, high-availability, load-balancing and centralized authentication/authorization. It is critical in these implementations that the layout, design and architecture of the backend infrastructure (those servers which actually handle the requests) are insulated and protected from the outside; as far as the client is concerned, the reverse proxy server *is* the sole source of all content. A typical implementation is below: Reverse Proxy ------------- | Related Modules | Related Directives | | --- | --- | | * `[mod\_proxy](../mod/mod_proxy)` * `[mod\_proxy\_balancer](../mod/mod_proxy_balancer)` * `[mod\_proxy\_hcheck](../mod/mod_proxy_hcheck)` | * `[ProxyPass](../mod/mod_proxy#proxypass)` * `[BalancerMember](../mod/mod_proxy#balancermember)` | Simple reverse proxying ----------------------- The `[ProxyPass](../mod/mod_proxy#proxypass)` directive specifies the mapping of incoming requests to the backend server (or a cluster of servers known as a `Balancer` group). The simplest example proxies all requests (`"/"`) to a single backend: ``` ProxyPass "/" "http://www.example.com/" ``` To ensure that and `Location:` headers generated from the backend are modified to point to the reverse proxy, instead of back to itself, the `[ProxyPassReverse](../mod/mod_proxy#proxypassreverse)` directive is most often required: ``` ProxyPass "/" "http://www.example.com/" ProxyPassReverse "/" "http://www.example.com/" ``` Only specific URIs can be proxied, as shown in this example: ``` ProxyPass "/images" "http://www.example.com/" ProxyPassReverse "/images" "http://www.example.com/" ``` In the above, any requests which start with the `/images` path with be proxied to the specified backend, otherwise it will be handled locally. Clusters and Balancers ---------------------- As useful as the above is, it still has the deficiencies that should the (single) backend node go down, or become heavily loaded, that proxying those requests provides no real advantage. What is needed is the ability to define a set or group of backend servers which can handle such requests and for the reverse proxy to load balance and failover among them. This group is sometimes called a *cluster* but Apache httpd's term is a *balancer*. One defines a balancer by leveraging the `[<Proxy>](../mod/mod_proxy#proxy)` and `[BalancerMember](../mod/mod_proxy#balancermember)` directives as shown: ``` <Proxy balancer://myset> BalancerMember http://www2.example.com:8080 BalancerMember http://www3.example.com:8080 ProxySet lbmethod=bytraffic </Proxy> ProxyPass "/images/" "balancer://myset/" ProxyPassReverse "/images/" "balancer://myset/" ``` The `balancer://` scheme is what tells httpd that we are creating a balancer set, with the name *myset*. It includes 2 backend servers, which httpd calls *BalancerMembers*. In this case, any requests for `/images` will be proxied to *one* of the 2 backends. The `[ProxySet](../mod/mod_proxy#proxyset)` directive specifies that the *myset* Balancer use a load balancing algorithm that balances based on I/O bytes. **Hint** *BalancerMembers* are also sometimes referred to as *workers*. Balancer and BalancerMember configuration ----------------------------------------- You can adjust numerous configuration details of the *balancers* and the *workers* via the various parameters defined in `[ProxyPass](../mod/mod_proxy#proxypass)`. For example, assuming we would want `http://www3.example.com:8080` to handle 3x the traffic with a timeout of 1 second, we would adjust the configuration as follows: ``` <Proxy balancer://myset> BalancerMember http://www2.example.com:8080 BalancerMember http://www3.example.com:8080 loadfactor=3 timeout=1 ProxySet lbmethod=bytraffic </Proxy> ProxyPass "/images" "balancer://myset/" ProxyPassReverse "/images" "balancer://myset/" ``` Failover -------- You can also fine-tune various failover scenarios, detailing which workers and even which balancers should be accessed in such cases. For example, the below setup implements three failover cases: 1. `http://spare1.example.com:8080` and `http://spare2.example.com:8080` are only sent traffic if one or both of `http://www2.example.com:8080` or `http://www3.example.com:8080` is unavailable. (One spare will be used to replace one unusable member of the same balancer set.) 2. `http://hstandby.example.com:8080` is only sent traffic if all other workers in balancer set `0` are not available. 3. If all load balancer set `0` workers, spares, and the standby are unavailable, only then will the `http://bkup1.example.com:8080` and `http://bkup2.example.com:8080` workers from balancer set `1` be brought into rotation. Thus, it is possible to have one or more hot spares and hot standbys for each load balancer set. ``` <Proxy balancer://myset> BalancerMember http://www2.example.com:8080 BalancerMember http://www3.example.com:8080 loadfactor=3 timeout=1 BalancerMember http://spare1.example.com:8080 status=+R BalancerMember http://spare2.example.com:8080 status=+R BalancerMember http://hstandby.example.com:8080 status=+H BalancerMember http://bkup1.example.com:8080 lbset=1 BalancerMember http://bkup2.example.com:8080 lbset=1 ProxySet lbmethod=byrequests </Proxy> ProxyPass "/images/" "balancer://myset/" ProxyPassReverse "/images/" "balancer://myset/" ``` For failover, hot spares are used as replacements for unusable workers in the same load balancer set. A worker is considered unusable if it is draining, stopped, or otherwise in an error/failed state. Hot standbys are used if all workers and spares in the load balancer set are unavailable. Load balancer sets (with their respective hot spares and standbys) are always tried in order from lowest to highest. Balancer Manager ---------------- One of the most unique and useful features of Apache httpd's reverse proxy is the embedded *balancer-manager* application. Similar to `[mod\_status](../mod/mod_status)`, *balancer-manager* displays the current working configuration and status of the enabled balancers and workers currently in use. However, not only does it display these parameters, it also allows for dynamic, runtime, on-the-fly reconfiguration of almost all of them, including adding new *BalancerMembers* (workers) to an existing balancer. To enable these capability, the following needs to be added to your configuration: ``` <Location "/balancer-manager"> SetHandler balancer-manager Require host localhost </Location> ``` **Warning** Do not enable the *balancer-manager* until you have [secured your server](../mod/mod_proxy#access). In particular, ensure that access to the URL is tightly restricted. When the reverse proxy server is accessed at that url (eg: `http://rproxy.example.com/balancer-manager/`, you will see a page similar to the below: This form allows the devops admin to adjust various parameters, take workers offline, change load balancing methods and add new works. For example, clicking on the balancer itself, you will get the following page: Whereas clicking on a worker, displays this page: To have these changes persist restarts of the reverse proxy, ensure that `[BalancerPersist](../mod/mod_proxy#balancerpersist)` is enabled. Dynamic Health Checks --------------------- Before httpd proxies a request to a worker, it can *"test"* if that worker is available via setting the `ping` parameter for that worker using `[ProxyPass](../mod/mod_proxy#proxypass)`. Oftentimes it is more useful to check the health of the workers *out of band*, in a dynamic fashion. This is achieved in Apache httpd by the `[mod\_proxy\_hcheck](../mod/mod_proxy_hcheck)` module. BalancerMember status flags --------------------------- In the *balancer-manager* the current state, or *status*, of a worker is displayed and can be set/reset. The meanings of these statuses are as follows: | Flag | String | Description | | --- | --- | --- | | | *Ok* | Worker is available | | | *Init* | Worker has been initialized | | `D` | *Dis* | Worker is disabled and will not accept any requests; will be automatically retried. | | `S` | *Stop* | Worker is administratively stopped; will not accept requests and will not be automatically retried | | `I` | *Ign* | Worker is in ignore-errors mode and will always be considered available. | | `R` | *Spar* | Worker is a hot spare. For each worker in a given lbset that is unusable (draining, stopped, in error, etc.), a usable hot spare with the same lbset will be used in its place. Hot spares can help ensure that a specific number of workers are always available for use by a balancer. | | `H` | *Stby* | Worker is in hot-standby mode and will only be used if no other viable workers or spares are available in the balancer set. | | `E` | *Err* | Worker is in an error state, usually due to failing pre-request check; requests will not be proxied to this worker, but it will be retried depending on the `retry` setting of the worker. | | `N` | *Drn* | Worker is in drain mode and will only accept existing sticky sessions destined for itself and ignore all other requests. | | `C` | *HcFl* | Worker has failed dynamic health check and will not be used until it passes subsequent health checks. | apache_http_server Access Control Access Control ============== Access control refers to any means of controlling access to any resource. This is separate from [authentication and authorization](auth). Related Modules and Directives ------------------------------ Access control can be done by several different modules. The most important of these are `[mod\_authz\_core](../mod/mod_authz_core)` and `[mod\_authz\_host](../mod/mod_authz_host)`. Also discussed in this document is access control using `[mod\_rewrite](../mod/mod_rewrite)`. Access control by host ---------------------- If you wish to restrict access to portions of your site based on the host address of your visitors, this is most easily done using `[mod\_authz\_host](../mod/mod_authz_host)`. The `[Require](../mod/mod_authz_core#require)` provides a variety of different ways to allow or deny access to resources. In conjunction with the `[RequireAll](../mod/mod_authz_core#requireall)`, `[RequireAny](../mod/mod_authz_core#requireany)`, and `[RequireNone](../mod/mod_authz_core#requirenone)` directives, these requirements may be combined in arbitrarily complex ways, to enforce whatever your access policy happens to be. The `[Allow](../mod/mod_access_compat#allow)`, `[Deny](../mod/mod_access_compat#deny)`, and `[Order](../mod/mod_access_compat#order)` directives, provided by `[mod\_access\_compat](../mod/mod_access_compat)`, are deprecated and will go away in a future version. You should avoid using them, and avoid outdated tutorials recommending their use. The usage of these directives is: ``` Require host address Require ip ip.address ``` In the first form, address is a fully qualified domain name (or a partial domain name); you may provide multiple addresses or domain names, if desired. In the second form, ip.address is an IP address, a partial IP address, a network/netmask pair, or a network/nnn CIDR specification. Either IPv4 or IPv6 addresses may be used. See [the mod\_authz\_host documentation](../mod/mod_authz_host#requiredirectives) for further examples of this syntax. You can insert `not` to negate a particular requirement. Note, that since a `not` is a negation of a value, it cannot be used by itself to allow or deny a request, as *not true* does not constitute *false*. Thus, to deny a visit using a negation, the block must have one element that evaluates as true or false. For example, if you have someone spamming your message board, and you want to keep them out, you could do the following: ``` <RequireAll> Require all granted Require not ip 10.252.46.165 </RequireAll> ``` Visitors coming from that address (`10.252.46.165`) will not be able to see the content covered by this directive. If, instead, you have a machine name, rather than an IP address, you can use that. ``` Require not host host.example.com ``` And, if you'd like to block access from an entire domain, you can specify just part of an address or domain name: ``` Require not ip 192.168.205 Require not host phishers.example.com moreidiots.example Require not host gov ``` Use of the `[RequireAll](../mod/mod_authz_core#requireall)`, `[RequireAny](../mod/mod_authz_core#requireany)`, and `[RequireNone](../mod/mod_authz_core#requirenone)` directives may be used to enforce more complex sets of requirements. Access control by arbitrary variables ------------------------------------- Using the `[<If>](../mod/core#if)`, you can allow or deny access based on arbitrary environment variables or request header values. For example, to deny access based on user-agent (the browser type) you might do the following: ``` <If "%{HTTP_USER_AGENT} == 'BadBot'"> Require all denied </If> ``` Using the `[Require](../mod/mod_authz_core#require)` `expr` syntax, this could also be written as: ``` Require expr %{HTTP_USER_AGENT} != 'BadBot' ``` **Warning:** Access control by `User-Agent` is an unreliable technique, since the `User-Agent` header can be set to anything at all, at the whim of the end user. See [the expressions document](../expr) for a further discussion of what expression syntaxes and variables are available to you. Access control with mod\_rewrite -------------------------------- The `[F]` `[RewriteRule](../mod/mod_rewrite#rewriterule)` flag causes a 403 Forbidden response to be sent. Using this, you can deny access to a resource based on arbitrary criteria. For example, if you wish to block access to a resource between 8pm and 7am, you can do this using `[mod\_rewrite](../mod/mod_rewrite)`. ``` RewriteEngine On RewriteCond "%{TIME_HOUR}" ">=20" [OR] RewriteCond "%{TIME_HOUR}" "<07" RewriteRule "^/fridge" "-" [F] ``` This will return a 403 Forbidden response for any request after 8pm or before 7am. This technique can be used for any criteria that you wish to check. You can also redirect, or otherwise rewrite these requests, if that approach is preferred. The `[<If>](../mod/core#if)` directive, added in 2.4, replaces many things that `[mod\_rewrite](../mod/mod_rewrite)` has traditionally been used to do, and you should probably look there first before resorting to mod\_rewrite. More information ---------------- The [expression engine](../expr) gives you a great deal of power to do a variety of things based on arbitrary server variables, and you should consult that document for more detail. Also, you should read the `[mod\_authz\_core](../mod/mod_authz_core)` documentation for examples of combining multiple access requirements and specifying how they interact. See also the [Authentication and Authorization](auth) howto. apache_http_server Per-user web directories Per-user web directories ======================== On systems with multiple users, each user can be permitted to have a web site in their home directory using the `[UserDir](../mod/mod_userdir#userdir)` directive. Visitors to a URL `http://example.com/~username/` will get content out of the home directory of the user "`username`", out of the subdirectory specified by the `[UserDir](../mod/mod_userdir#userdir)` directive. Note that, by default, access to these directories is **not** enabled. You can enable access when using `[UserDir](../mod/mod_userdir#userdir)` by uncommenting the line: ``` #Include conf/extra/httpd-userdir.conf ``` in the default config file `conf/httpd.conf`, and adapting the `httpd-userdir.conf` file as necessary, or by including the appropriate directives in a `[<Directory>](../mod/core#directory)` block within the main config file. Per-user web directories ------------------------ | Related Modules | Related Directives | | --- | --- | | * `[mod\_userdir](../mod/mod_userdir)` | * `[UserDir](../mod/mod_userdir#userdir)` * `[DirectoryMatch](../mod/core#directorymatch)` * `[AllowOverride](../mod/core#allowoverride)` | Setting the file path with UserDir ---------------------------------- The `[UserDir](../mod/mod_userdir#userdir)` directive specifies a directory out of which per-user content is loaded. This directive may take several different forms. If a path is given which does not start with a leading slash, it is assumed to be a directory path relative to the home directory of the specified user. Given this configuration: ``` UserDir public_html ``` the URL `http://example.com/~rbowen/file.html` will be translated to the file path `/home/rbowen/public_html/file.html` If a path is given starting with a slash, a directory path will be constructed using that path, plus the username specified. Given this configuration: ``` UserDir /var/html ``` the URL `http://example.com/~rbowen/file.html` will be translated to the file path `/var/html/rbowen/file.html` If a path is provided which contains an asterisk (\*), a path is used in which the asterisk is replaced with the username. Given this configuration: ``` UserDir /var/www/*/docs ``` the URL `http://example.com/~rbowen/file.html` will be translated to the file path `/var/www/rbowen/docs/file.html` Multiple directories or directory paths can also be set. ``` UserDir public_html /var/html ``` For the URL `http://example.com/~rbowen/file.html`, Apache will search for `~rbowen`. If it isn't found, Apache will search for `rbowen` in `/var/html`. If found, the above URL will then be translated to the file path `/var/html/rbowen/file.html` Redirecting to external URLs ---------------------------- The `[UserDir](../mod/mod_userdir#userdir)` directive can be used to redirect user directory requests to external URLs. ``` UserDir http://example.org/users/*/ ``` The above example will redirect a request for `http://example.com/~bob/abc.html` to `http://example.org/users/bob/abc.html`. Restricting what users are permitted to use this feature -------------------------------------------------------- Using the syntax shown in the UserDir documentation, you can restrict what users are permitted to use this functionality: ``` UserDir disabled root jro fish ``` The configuration above will enable the feature for all users except for those listed in the `disabled` statement. You can, likewise, disable the feature for all but a few users by using a configuration like the following: ``` UserDir disabled UserDir enabled rbowen krietz ``` See `[UserDir](../mod/mod_userdir#userdir)` documentation for additional examples. Enabling a cgi directory for each user -------------------------------------- In order to give each user their own cgi-bin directory, you can use a `[<Directory>](../mod/core#directory)` directive to make a particular subdirectory of a user's home directory cgi-enabled. ``` <Directory "/home/*/public_html/cgi-bin/"> Options ExecCGI SetHandler cgi-script </Directory> ``` Then, presuming that `UserDir` is set to `public_html`, a cgi program `example.cgi` could be loaded from that directory as: `http://example.com/~rbowen/cgi-bin/example.cgi` Allowing users to alter configuration ------------------------------------- If you want to allows users to modify the server configuration in their web space, they will need to use `.htaccess` files to make these changes. Ensure that you have set `[AllowOverride](../mod/core#allowoverride)` to a value sufficient for the directives that you want to permit the users to modify. See the [.htaccess tutorial](htaccess) for additional details on how this works.
programming_docs
apache_http_server HTTP/2 guide HTTP/2 guide ============ This is the howto guide for the HTTP/2 implementation in Apache httpd. This feature is *production-ready* and you may expect interfaces and directives to remain consistent releases. The HTTP/2 protocol ------------------- HTTP/2 is the evolution of the world's most successful application layer protocol, HTTP. It focuses on making more efficient use of network resources. It does not change the fundamentals of HTTP, the semantics. There are still request and responses and headers and all that. So, if you already know HTTP/1, you know 95% about HTTP/2 as well. There has been a lot written about HTTP/2 and how it works. The most normative is, of course, its [RFC 7540](https://tools.ietf.org/html/rfc7540) ([also available in more readable formatting, YMMV](http://httpwg.org/specs/rfc7540.html)). So, there you'll find the nuts and bolts. But, as RFC do, it's not really a good thing to read first. It's better to first understand *what* a thing wants to do and then read the RFC about *how* it is done. A much better document to start with is [http2 explained](https://daniel.haxx.se/http2/) by Daniel Stenberg, the author of [curl](https://curl.haxx.se). It is available in an ever growing list of languages, too! Too Long, Didn't read: there are some new terms and gotchas that need to be kept in mind while reading this document: * HTTP/2 is a **binary protocol**, as opposed to HTTP 1.1 that is plain text. The latter is meant to be human readable (for example sniffing network traffic) meanwhile the former is not. More info in the official FAQ [question](https://http2.github.io/faq/#why-is-http2-binary). * **h2** is HTTP/2 over TLS (protocol negotiation via ALPN). * **h2c** is HTTP/2 over TCP. * A **frame** is the smallest unit of communication within an HTTP/2 connection, consisting of a header and a variable-length sequence of octets structured according to the frame type. More info in the official documentation [section](http://httpwg.org/specs/rfc7540.html#FramingLayer). * A **stream** is a bidirectional flow of frames within the HTTP/2 connection. The correspondent concept in HTTP 1.1 is a request/response message exchange. More info in the official documentation [section](http://httpwg.org/specs/rfc7540.html#StreamsLayer). * HTTP/2 is able to run **multiple streams** of data over the same TCP connection, avoiding the classic HTTP 1.1 head of blocking slow request and avoiding to re-instantiate TCP connections for each request/response (KeepAlive patched the problem in HTTP 1.1 but did not fully solve it). HTTP/2 in Apache httpd ---------------------- The HTTP/2 protocol is implemented by its own httpd module, aptly named `[mod\_http2](../mod/mod_http2)`. It implements the complete set of features described by RFC 7540 and supports HTTP/2 over cleartext (http:), as well as secure (https:) connections. The cleartext variant is named '`h2c`', the secure one '`h2`'. For `h2c` it allows the *direct* mode and the `Upgrade:` via an initial HTTP/1 request. One feature of HTTP/2 that offers new capabilities for web developers is [Server Push](#push). See that section on how your web application can make use of it. Build httpd with HTTP/2 support ------------------------------- `[mod\_http2](../mod/mod_http2)` uses the library of [nghttp2](https://nghttp2.org) as its implementation base. In order to build `[mod\_http2](../mod/mod_http2)` you need at least version 1.2.1 of `libnghttp2` installed on your system. When you `./configure` you Apache httpd source tree, you need to give it '`--enable-http2`' as additional argument to trigger the build of the module. Should your `libnghttp2` reside in an unusual place (whatever that is on your operating system), you may announce its location with '`--with-nghttp2=<path>`' to `configure`. While that should do the trick for most, they are people who might prefer a statically linked `nghttp2` in this module. For those, the option `--enable-nghttp2-staticlib-deps` exists. It works quite similar to how one statically links openssl to `[mod\_ssl](../mod/mod_ssl)`. Speaking of SSL, you need to be aware that most browsers will speak HTTP/2 only on `https:` URLs, so you need a server with SSL support. But not only that, you will need a SSL library that supports the `ALPN` extension. If OpenSSL is the library you use, you need at least version 1.0.2. Basic Configuration ------------------- When you have a `httpd` built with `[mod\_http2](../mod/mod_http2)` you need some basic configuration for it becoming active. The first thing, as with every Apache module, is that you need to load it: ``` LoadModule http2_module modules/mod_http2.so ``` The second directive you need to add to your server configuration is ``` Protocols h2 http/1.1 ``` This allows h2, the secure variant, to be the preferred protocol on your server connections. When you want to enable all HTTP/2 variants, you simply write: ``` Protocols h2 h2c http/1.1 ``` Depending on where you put this directive, it affects all connections or just the ones to a certain virtual host. You can nest it, as in: ``` Protocols http/1.1 <VirtualHost ...> ServerName test.example.org Protocols h2 http/1.1 </VirtualHost> ``` This allows only HTTP/1 on connections, except SSL connections to `test.example.org` which offer HTTP/2. **Choose a strong SSLCipherSuite** The `[SSLCipherSuite](../mod/mod_ssl#sslciphersuite)` needs to be configured with a strong TLS cipher suite. The current version of `[mod\_http2](../mod/mod_http2)` does not enforce any cipher but most clients do so. Pointing a browser to a `h2` enabled server with a inappropriate cipher suite will force it to simply refuse and fall back to HTTP 1.1. This is a common mistake that is done while configuring httpd for HTTP/2 the first time, so please keep it in mind to avoid long debugging sessions! If you want to be sure about the cipher suite to choose please avoid the ones listed in the [HTTP/2 TLS reject list](http://httpwg.org/specs/rfc7540.html#BadCipherSuites). The order of protocols mentioned is also relevant. By default, the first one is the most preferred protocol. When a client offers multiple choices, the one most to the left is selected. In ``` Protocols http/1.1 h2 ``` the most preferred protocol is HTTP/1 and it will always be selected unless a client *only* supports h2. Since we want to talk HTTP/2 to clients that support it, the better order is ``` Protocols h2 h2c http/1.1 ``` There is one more thing to ordering: the client has its own preferences, too. If you want, you can configure your server to select the protocol most preferred by the client: ``` ProtocolsHonorOrder Off ``` makes the order *you* wrote the Protocols irrelevant and only the client's ordering will decide. A last thing: the protocols you configure are not checked for correctness or spelling. You can mention protocols that do not exist, so there is no need to guard `[Protocols](../mod/core#protocols)` with any `[<IfModule>](../mod/core#ifmodule)` checks. For more advanced tips on configuration, see the [modules section about dimensioning](../mod/mod_http2#dimensioning) and [how to manage multiple hosts with the same certificate](../mod/mod_http2#misdirected). MPM Configuration ----------------- HTTP/2 is supported in all multi-processing modules that come with httpd. However, if you use the `[prefork](../mod/prefork)` mpm, there will be severe restrictions. In `[prefork](../mod/prefork)`, `[mod\_http2](../mod/mod_http2)` will only process one request at at time per connection. But clients, such as browsers, will send many requests at the same time. If one of these takes long to process (or is a long polling one), the other requests will stall. `[mod\_http2](../mod/mod_http2)` will not work around this limit by default. The reason is that `[prefork](../mod/prefork)` is today only chosen, if you run processing engines that are not prepared for multi-threading, e.g. will crash with more than one request. If your setup can handle it, configuring `[event](../mod/event)` mpm is nowadays the best one (if supported on your platform). If you are really stuck with `[prefork](../mod/prefork)` and want multiple requests, you can tweak the `[H2MinWorkers](../mod/mod_http2#h2minworkers)` to make that possible. If it breaks, however, you own both parts. Clients ------- Almost all modern browsers support HTTP/2, but only over SSL connections: Firefox (v43), Chrome (v45), Safari (since v9), iOS Safari (v9), Opera (v35), Chrome for Android (v49) and Internet Explorer (v11 on Windows10) ([source](http://caniuse.com/#search=http2)). Other clients, as well as servers, are listed [on the Implementations wiki](https://github.com/http2/http2-spec/wiki/Implementations), among them implementations for c, c++, common lisp, dart, erlang, haskell, java, nodejs, php, python, perl, ruby, rust, scala and swift. Several of the non-browser client implementations support HTTP/2 over cleartext, h2c. The most versatile being [curl](https://curl.haxx.se). Useful tools to debug HTTP/2 ---------------------------- The first tool to mention is of course [curl](https://curl.haxx.se). Please make sure that your version supports HTTP/2 checking its `Features`: ``` $ curl -V curl 7.45.0 (x86_64-apple-darwin15.0.0) libcurl/7.45.0 OpenSSL/1.0.2d zlib/1.2.8 nghttp2/1.3.4 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 [...] Features: IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP **HTTP2** ``` **Mac OS homebrew notes** brew install curl --with-openssl --with-nghttp2 And for really deep inspection [wireshark](https://wiki.wireshark.org/HTTP2). The [nghttp2](https://nghttp2.org) package also includes clients, such as: * [nghttp](https://nghttp2.org/documentation/nghttp.1.html) - useful to visualize the HTTP/2 frames and get a better idea of the protocol. * [h2load](https://nghttp2.org/documentation/h2load-howto.html) - useful to stress-test your server. Chrome offers detailed HTTP/2 logs on its connections via the [special net-internals page](chrome://net-internals/#http2). There is also an interesting extension for [Chrome](https://chrome.google.com/webstore/detail/http2-and-spdy-indicator/mpbpobfflnpcgagjijhmgnchggcjblin?hl=en) and [Firefox](https://addons.mozilla.org/en-us/firefox/addon/spdy-indicator/) to visualize when your browser is using HTTP/2. Server Push ----------- The HTTP/2 protocol allows the server to PUSH responses to a client it never asked for. The tone of the conversation is: "here is a request that you never sent and the response to it will arrive soon..." But there are restrictions: the client can disable this feature and the server may only ever PUSH on a request that came from the client. The intention is to allow the server to send resources to the client that it will most likely need: a css or javascript resource that belongs to a html page the client requested. A set of images that is referenced by a css, etc. The advantage for the client is that it saves the time to send the request which may range from a few milliseconds to half a second, depending on where on the globe both are located. The disadvantage is that the client may get sent things it already has in its cache. Sure, HTTP/2 allows for the early cancellation of such requests, but still there are resources wasted. To summarize: there is no one good strategy on how to make best use of this feature of HTTP/2 and everyone is still experimenting. So, how do you experiment with it in Apache httpd? `[mod\_http2](../mod/mod_http2)` inspect response header for `Link` headers in a certain format: ``` Link </xxx.css>;rel=preload, </xxx.js>; rel=preload ``` If the connection supports PUSH, these two resources will be sent to the client. As a web developer, you may set these headers either directly in your application response or you configure the server via ``` <Location /xxx.html> Header add Link "</xxx.css>;rel=preload" Header add Link "</xxx.js>;rel=preload" </Location> ``` If you want to use `preload` links without triggering a PUSH, you can use the `nopush` parameter, as in ``` Link </xxx.css>;rel=preload;nopush ``` or you may disable PUSHes for your server entirely with the directive ``` H2Push Off ``` And there is more: The module will keep a diary of what has been PUSHed for each connection (hashes of URLs, basically) and will not PUSH the same resource twice. When the connection closes, this information is discarded. There are people thinking about how a client can tell a server what it already has, so PUSHes for those things can be avoided, but this is all highly experimental right now. Another experimental draft that has been implemented in `[mod\_http2](../mod/mod_http2)` is the [Accept-Push-Policy Header Field](https://tools.ietf.org/html/draft-ruellan-http-accept-push-policy-00) where a client can, for each request, define what kind of PUSHes it accepts. PUSH might not always trigger the request/response/performance that one expects or hopes for. There are various studies on this topic to be found on the web that explain benefits and weaknesses and how different features of client and network influence the outcome. For example: just because the server PUSHes a resource does not mean a browser will actually use the data. The major thing that influences the response being PUSHed is the request that was simulated. The request URL for a PUSH is given by the application, but where do the request headers come from? For example, will the PUSH request a `accept-language` header and if yes with what value? Apache will look at the original request (the one that triggered the PUSH) and copy the following headers over to PUSH requests: `user-agent`, `accept`, `accept-encoding`, `accept-language`, `cache-control`. All other headers are ignored. Cookies will also not be copied over. PUSHing resources that require a cookie to be present will not work. This can be a matter of debate. But unless this is more clearly discussed with browser, let's err on the side of caution and not expose cookie where they might ordinarily not be visible. Early Hints ----------- An alternative to PUSHing resources is to send `Link` headers to the client before the response is even ready. This uses the HTTP feature called "Early Hints" and is described in [RFC 8297](https://tools.ietf.org/html/rfc8297). In order to use this, you need to explicitly enable it on the server via ``` H2EarlyHints on ``` (It is not enabled by default since some older browser tripped on such responses.) If this feature is on, you can use the directive `[H2PushResource](../mod/mod_http2#h2pushresource)` to trigger early hints and resource PUSHes: ``` <Location /xxx.html> H2PushResource /xxx.css H2PushResource /xxx.js </Location> ``` This will send out a `"103 Early Hints"` response to a client as soon as the server *starts* processing the request. This may be much early than the time the first response headers have been determined, depending on your web application. If `[H2Push](../mod/mod_http2#h2push)` is enabled, this will also start the PUSH right after the 103 response. If `[H2Push](../mod/mod_http2#h2push)` is disabled however, the 103 response will be send nevertheless to the client. apache_http_server Apache HTTP Server Tutorial: .htaccess files Apache HTTP Server Tutorial: .htaccess files ============================================ `.htaccess` files provide a way to make configuration changes on a per-directory basis. .htaccess files --------------- | Related Modules | Related Directives | | --- | --- | | * `[core](../mod/core)` * `[mod\_authn\_file](../mod/mod_authn_file)` * `[mod\_authz\_groupfile](../mod/mod_authz_groupfile)` * `[mod\_cgi](../mod/mod_cgi)` * `[mod\_include](../mod/mod_include)` * `[mod\_mime](../mod/mod_mime)` | * `[AccessFileName](../mod/core#accessfilename)` * `[AllowOverride](../mod/core#allowoverride)` * `[Options](../mod/core#options)` * `[AddHandler](../mod/mod_mime#addhandler)` * `[SetHandler](../mod/core#sethandler)` * `[AuthType](../mod/mod_authn_core#authtype)` * `[AuthName](../mod/mod_authn_core#authname)` * `[AuthUserFile](../mod/mod_authn_file#authuserfile)` * `[AuthGroupFile](../mod/mod_authz_groupfile#authgroupfile)` * `[Require](../mod/mod_authz_core#require)` | You should avoid using `.htaccess` files completely if you have access to httpd main server config file. Using `.htaccess` files slows down your Apache http server. Any directive that you can include in a `.htaccess` file is better set in a `[Directory](../mod/core#directory)` block, as it will have the same effect with better performance. What they are/How to use them ----------------------------- `.htaccess` files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof. **Note:** If you want to call your `.htaccess` file something else, you can change the name of the file using the `[AccessFileName](../mod/core#accessfilename)` directive. For example, if you would rather call the file `.config` then you can put the following in your server configuration file: ``` AccessFileName ".config" ``` In general, `.htaccess` files use the same syntax as the [main configuration files](../configuring#syntax). What you can put in these files is determined by the `[AllowOverride](../mod/core#allowoverride)` directive. This directive specifies, in categories, what directives will be honored if they are found in a `.htaccess` file. If a directive is permitted in a `.htaccess` file, the documentation for that directive will contain an Override section, specifying what value must be in `[AllowOverride](../mod/core#allowoverride)` in order for that directive to be permitted. For example, if you look at the documentation for the `[AddDefaultCharset](../mod/core#adddefaultcharset)` directive, you will find that it is permitted in `.htaccess` files. (See the Context line in the directive summary.) The Override line reads `FileInfo`. Thus, you must have at least `AllowOverride FileInfo` in order for this directive to be honored in `.htaccess` files. ### Example: | | | | --- | --- | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | If you are unsure whether a particular directive is permitted in a `.htaccess` file, look at the documentation for that directive, and check the Context line for ".htaccess". When (not) to use .htaccess files --------------------------------- In general, you should only use `.htaccess` files when you don't have access to the main server configuration file. There is, for example, a common misconception that user authentication should always be done in `.htaccess` files, and, in more recent years, another misconception that `[mod\_rewrite](../mod/mod_rewrite)` directives must go in `.htaccess` files. This is simply not the case. You can put user authentication configurations in the main server configuration, and this is, in fact, the preferred way to do things. Likewise, `mod_rewrite` directives work better, in many respects, in the main server configuration. `.htaccess` files should be used in a case where the content providers need to make configuration changes to the server on a per-directory basis, but do not have root access on the server system. In the event that the server administrator is not willing to make frequent configuration changes, it might be desirable to permit individual users to make these changes in `.htaccess` files for themselves. This is particularly true, for example, in cases where ISPs are hosting multiple user sites on a single machine, and want their users to be able to alter their configuration. However, in general, use of `.htaccess` files should be avoided when possible. Any configuration that you would consider putting in a `.htaccess` file, can just as effectively be made in a `[<Directory>](../mod/core#directory)` section in your main server configuration file. There are two main reasons to avoid the use of `.htaccess` files. The first of these is performance. When `[AllowOverride](../mod/core#allowoverride)` is set to allow the use of `.htaccess` files, httpd will look in every directory for `.htaccess` files. Thus, permitting `.htaccess` files causes a performance hit, whether or not you actually even use them! Also, the `.htaccess` file is loaded every time a document is requested. Further note that httpd must look for `.htaccess` files in all higher-level directories, in order to have a full complement of directives that it must apply. (See section on [how directives are applied](#how).) Thus, if a file is requested out of a directory `/www/htdocs/example`, httpd must look for the following files: ``` /.htaccess /www/.htaccess /www/htdocs/.htaccess /www/htdocs/example/.htaccess ``` And so, for each file access out of that directory, there are 4 additional file-system accesses, even if none of those files are present. (Note that this would only be the case if `.htaccess` files were enabled for `/`, which is not usually the case.) In the case of `[RewriteRule](../mod/mod_rewrite#rewriterule)` directives, in `.htaccess` context these regular expressions must be re-compiled with every request to the directory, whereas in main server configuration context they are compiled once and cached. Additionally, the rules themselves are more complicated, as one must work around the restrictions that come with per-directory context and `mod_rewrite`. Consult the [Rewrite Guide](../rewrite/intro#htaccess) for more detail on this subject. The second consideration is one of security. You are permitting users to modify server configuration, which may result in changes over which you have no control. Carefully consider whether you want to give your users this privilege. Note also that giving users less privileges than they need will lead to additional technical support requests. Make sure you clearly tell your users what level of privileges you have given them. Specifying exactly what you have set `[AllowOverride](../mod/core#allowoverride)` to, and pointing them to the relevant documentation, will save yourself a lot of confusion later. Note that it is completely equivalent to put a `.htaccess` file in a directory `/www/htdocs/example` containing a directive, and to put that same directive in a Directory section `<Directory "/www/htdocs/example">` in your main server configuration: `.htaccess` file in `/www/htdocs/example`: ### Contents of .htaccess file in `/www/htdocs/example` ``` AddType text/example ".exm" ``` ### Section from your `httpd.conf` file ``` <Directory "/www/htdocs/example"> AddType text/example ".exm" </Directory> ``` However, putting this configuration in your server configuration file will result in less of a performance hit, as the configuration is loaded once when httpd starts, rather than every time a file is requested. The use of `.htaccess` files can be disabled completely by setting the `[AllowOverride](../mod/core#allowoverride)` directive to `none`: ``` AllowOverride None ``` How directives are applied -------------------------- The configuration directives found in a `.htaccess` file are applied to the directory in which the `.htaccess` file is found, and to all subdirectories thereof. However, it is important to also remember that there may have been `.htaccess` files in directories higher up. Directives are applied in the order that they are found. Therefore, a `.htaccess` file in a particular directory may override directives found in `.htaccess` files found higher up in the directory tree. And those, in turn, may have overridden directives found yet higher up, or in the main server configuration file itself. Example: In the directory `/www/htdocs/example1` we have a `.htaccess` file containing the following: ``` Options +ExecCGI ``` (Note: you must have "`AllowOverride Options`" in effect to permit the use of the "`[Options](../mod/core#options)`" directive in `.htaccess` files.) In the directory `/www/htdocs/example1/example2` we have a `.htaccess` file containing: ``` Options Includes ``` Because of this second `.htaccess` file, in the directory `/www/htdocs/example1/example2`, CGI execution is not permitted, as only `Options Includes` is in effect, which completely overrides any earlier setting that may have been in place. ### Merging of .htaccess with the main configuration files As discussed in the documentation on [Configuration Sections](../sections), `.htaccess` files can override the `[<Directory>](../mod/core#directory)` sections for the corresponding directory, but will be overridden by other types of configuration sections from the main configuration files. This fact can be used to enforce certain configurations, even in the presence of a liberal `[AllowOverride](../mod/core#allowoverride)` setting. For example, to prevent script execution while allowing anything else to be set in `.htaccess` you can use: ``` <Directory "/www/htdocs"> AllowOverride All </Directory> <Location "/"> Options +IncludesNoExec -ExecCGI </Location> ``` This example assumes that your `[DocumentRoot](../mod/core#documentroot)` is `/www/htdocs`. Authentication example ---------------------- If you jumped directly to this part of the document to find out how to do authentication, it is important to note one thing. There is a common misconception that you are required to use `.htaccess` files in order to implement password authentication. This is not the case. Putting authentication directives in a `[<Directory>](../mod/core#directory)` section, in your main server configuration file, is the preferred way to implement this, and `.htaccess` files should be used only if you don't have access to the main server configuration file. See [above](#when) for a discussion of when you should and should not use `.htaccess` files. Having said that, if you still think you need to use a `.htaccess` file, you may find that a configuration such as what follows may work for you. `.htaccess` file contents: ``` AuthType Basic AuthName "Password Required" AuthUserFile "/www/passwords/password.file" AuthGroupFile "/www/passwords/group.file" Require group admins ``` Note that `AllowOverride AuthConfig` must be in effect for these directives to have any effect. Please see the [authentication tutorial](auth) for a more complete discussion of authentication and authorization. Server Side Includes example ---------------------------- Another common use of `.htaccess` files is to enable Server Side Includes for a particular directory. This may be done with the following configuration directives, placed in a `.htaccess` file in the desired directory: ``` Options +Includes AddType text/html shtml AddHandler server-parsed shtml ``` Note that `AllowOverride Options` and `AllowOverride FileInfo` must both be in effect for these directives to have any effect. Please see the [SSI tutorial](ssi) for a more complete discussion of server-side includes. Rewrite Rules in .htaccess files -------------------------------- When using `[RewriteRule](../mod/mod_rewrite#rewriterule)` in `.htaccess` files, be aware that the per-directory context changes things a bit. In particular, rules are taken to be relative to the current directory, rather than being the original requested URI. Consider the following examples: ``` # In httpd.conf RewriteRule "^/images/(.+)\.jpg" "/images/$1.png" # In .htaccess in root dir RewriteRule "^images/(.+)\.jpg" "images/$1.png" # In .htaccess in images/ RewriteRule "^(.+)\.jpg" "$1.png" ``` In a `.htaccess` in your document directory, the leading slash is removed from the value supplied to `[RewriteRule](../mod/mod_rewrite#rewriterule)`, and in the `images` subdirectory, `/images/` is removed from it. Thus, your regular expression needs to omit that portion as well. Consult the [mod\_rewrite documentation](../rewrite/index) for further details on using `mod_rewrite`. CGI example ----------- Finally, you may wish to use a `.htaccess` file to permit the execution of CGI programs in a particular directory. This may be implemented with the following configuration: ``` Options +ExecCGI AddHandler cgi-script cgi pl ``` Alternately, if you wish to have all files in the given directory be considered to be CGI programs, this may be done with the following configuration: ``` Options +ExecCGI SetHandler cgi-script ``` Note that `AllowOverride Options` and `AllowOverride FileInfo` must both be in effect for these directives to have any effect. Please see the [CGI tutorial](cgi) for a more complete discussion of CGI programming and configuration. Troubleshooting --------------- When you put configuration directives in a `.htaccess` file, and you don't get the desired effect, there are a number of things that may be going wrong. Most commonly, the problem is that `[AllowOverride](../mod/core#allowoverride)` is not set such that your configuration directives are being honored. Make sure that you don't have a `AllowOverride None` in effect for the file scope in question. A good test for this is to put garbage in your `.htaccess` file and reload the page. If a server error is not generated, then you almost certainly have `AllowOverride None` in effect. If, on the other hand, you are getting server errors when trying to access documents, check your httpd error log. It will likely tell you that the directive used in your `.htaccess` file is not permitted. ``` [Fri Sep 17 18:43:16 2010] [alert] [client 192.168.200.51] /var/www/html/.htaccess: DirectoryIndex not allowed here ``` This will indicate either that you've used a directive that is never permitted in `.htaccess` files, or that you simply don't have `[AllowOverride](../mod/core#allowoverride)` set to a level sufficient for the directive you've used. Consult the documentation for that particular directive to determine which is the case. Alternately, it may tell you that you had a syntax error in your usage of the directive itself. ``` [Sat Aug 09 16:22:34 2008] [alert] [client 192.168.200.51] /var/www/html/.htaccess: RewriteCond: bad flag delimiters ``` In this case, the error message should be specific to the particular syntax error that you have committed.
programming_docs
apache_http_server Apache httpd Tutorial: Introduction to Server Side Includes Apache httpd Tutorial: Introduction to Server Side Includes =========================================================== Server-side includes provide a means to add dynamic content to existing HTML documents. Introduction ------------ | Related Modules | Related Directives | | --- | --- | | * `[mod\_include](../mod/mod_include)` * `[mod\_cgi](../mod/mod_cgi)` * `[mod\_expires](../mod/mod_expires)` | * `[Options](../mod/core#options)` * `[XBitHack](../mod/mod_include#xbithack)` * `[AddType](../mod/mod_mime#addtype)` * `[SetOutputFilter](../mod/core#setoutputfilter)` * `[BrowserMatchNoCase](../mod/mod_setenvif#browsermatchnocase)` | This article deals with Server Side Includes, usually called simply SSI. In this article, I'll talk about configuring your server to permit SSI, and introduce some basic SSI techniques for adding dynamic content to your existing HTML pages. In the latter part of the article, we'll talk about some of the somewhat more advanced things that can be done with SSI, such as conditional statements in your SSI directives. What are SSI? ------------- SSI (Server Side Includes) are directives that are placed in HTML pages, and evaluated on the server while the pages are being served. They let you add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program, or other dynamic technology. For example, you might place a directive into an existing HTML page, such as: ``` <!--#echo var="DATE_LOCAL" --> ``` And, when the page is served, this fragment will be evaluated and replaced with its value: ``` Tuesday, 15-Jan-2013 19:28:54 EST ``` The decision of when to use SSI, and when to have your page entirely generated by some program, is usually a matter of how much of the page is static, and how much needs to be recalculated every time the page is served. SSI is a great way to add small pieces of information, such as the current time - shown above. But if a majority of your page is being generated at the time that it is served, you need to look for some other solution. Configuring your server to permit SSI ------------------------------------- To permit SSI on your server, you must have the following directive either in your `httpd.conf` file, or in a `.htaccess` file: ``` Options +Includes ``` This tells Apache that you want to permit files to be parsed for SSI directives. Note that most configurations contain multiple `[Options](../mod/core#options)` directives that can override each other. You will probably need to apply the `Options` to the specific directory where you want SSI enabled in order to assure that it gets evaluated last. Not just any file is parsed for SSI directives. You have to tell Apache which files should be parsed. There are two ways to do this. You can tell Apache to parse any file with a particular file extension, such as `.shtml`, with the following directives: ``` AddType text/html .shtml AddOutputFilter INCLUDES .shtml ``` One disadvantage to this approach is that if you wanted to add SSI directives to an existing page, you would have to change the name of that page, and all links to that page, in order to give it a `.shtml` extension, so that those directives would be executed. The other method is to use the `[XBitHack](../mod/mod_include#xbithack)` directive: ``` XBitHack on ``` `[XBitHack](../mod/mod_include#xbithack)` tells Apache to parse files for SSI directives if they have the execute bit set. So, to add SSI directives to an existing page, rather than having to change the file name, you would just need to make the file executable using `chmod`. ``` chmod +x pagename.html ``` A brief comment about what not to do. You'll occasionally see people recommending that you just tell Apache to parse all `.html` files for SSI, so that you don't have to mess with `.shtml` file names. These folks have perhaps not heard about `[XBitHack](../mod/mod_include#xbithack)`. The thing to keep in mind is that, by doing this, you're requiring that Apache read through every single file that it sends out to clients, even if they don't contain any SSI directives. This can slow things down quite a bit, and is not a good idea. Of course, on Windows, there is no such thing as an execute bit to set, so that limits your options a little. In its default configuration, Apache does not send the last modified date or content length HTTP headers on SSI pages, because these values are difficult to calculate for dynamic content. This can prevent your document from being cached, and result in slower perceived client performance. There are two ways to solve this: 1. Use the `XBitHack Full` configuration. This tells Apache to determine the last modified date by looking only at the date of the originally requested file, ignoring the modification date of any included files. 2. Use the directives provided by `[mod\_expires](../mod/mod_expires)` to set an explicit expiration time on your files, thereby letting browsers and proxies know that it is acceptable to cache them. Basic SSI directives -------------------- SSI directives have the following syntax: ``` <!--#function attribute=value attribute=value ... --> ``` It is formatted like an HTML comment, so if you don't have SSI correctly enabled, the browser will ignore it, but it will still be visible in the HTML source. If you have SSI correctly configured, the directive will be replaced with its results. The function can be one of a number of things, and we'll talk some more about most of these in the next installment of this series. For now, here are some examples of what you can do with SSI ### Today's date ``` <!--#echo var="DATE_LOCAL" --> ``` The `echo` function just spits out the value of a variable. There are a number of standard variables, which include the whole set of environment variables that are available to CGI programs. Also, you can define your own variables with the `set` function. If you don't like the format in which the date gets printed, you can use the `config` function, with a `timefmt` attribute, to modify that formatting. ``` <!--#config timefmt="%A %B %d, %Y" --> Today is <!--#echo var="DATE_LOCAL" --> ``` ### Modification date of the file ``` This document last modified <!--#flastmod file="index.html" --> ``` This function is also subject to `timefmt` format configurations. ### Including the results of a CGI program This is one of the more common uses of SSI - to output the results of a CGI program, such as everybody's favorite, a ``hit counter.'' ``` <!--#include virtual="/cgi-bin/counter.pl" --> ``` Additional examples ------------------- Following are some specific examples of things you can do in your HTML documents with SSI. ### When was this document modified? Earlier, we mentioned that you could use SSI to inform the user when the document was most recently modified. However, the actual method for doing that was left somewhat in question. The following code, placed in your HTML document, will put such a time stamp on your page. Of course, you will have to have SSI correctly enabled, as discussed above. ``` <!--#config timefmt="%A %B %d, %Y" --> This file last modified <!--#flastmod file="ssi.shtml" --> ``` Of course, you will need to replace the `ssi.shtml` with the actual name of the file that you're referring to. This can be inconvenient if you're just looking for a generic piece of code that you can paste into any file, so you probably want to use the `LAST_MODIFIED` variable instead: ``` <!--#config timefmt="%D" --> This file last modified <!--#echo var="LAST_MODIFIED" --> ``` For more details on the `timefmt` format, go to your favorite search site and look for `strftime`. The syntax is the same. ### Including a standard footer If you are managing any site that is more than a few pages, you may find that making changes to all those pages can be a real pain, particularly if you are trying to maintain some kind of standard look across all those pages. Using an include file for a header and/or a footer can reduce the burden of these updates. You just have to make one footer file, and then include it into each page with the `include` SSI command. The `include` function can determine what file to include with either the `file` attribute, or the `virtual` attribute. The `file` attribute is a file path, *relative to the current directory*. That means that it cannot be an absolute file path (starting with /), nor can it contain ../ as part of that path. The `virtual` attribute is probably more useful, and should specify a URL relative to the document being served. It can start with a /, but must be on the same server as the file being served. ``` <!--#include virtual="/footer.html" --> ``` I'll frequently combine the last two things, putting a `LAST_MODIFIED` directive inside a footer file to be included. SSI directives can be contained in the included file, and includes can be nested - that is, the included file can include another file, and so on. What else can I config? ----------------------- In addition to being able to `config` the time format, you can also `config` two other things. Usually, when something goes wrong with your SSI directive, you get the message ``` [an error occurred while processing this directive] ``` If you want to change that message to something else, you can do so with the `errmsg` attribute to the `config` function: ``` <!--#config errmsg="[It appears that you don't know how to use SSI]" --> ``` Hopefully, end users will never see this message, because you will have resolved all the problems with your SSI directives before your site goes live. (Right?) And you can `config` the format in which file sizes are returned with the `sizefmt` attribute. You can specify `bytes` for a full count in bytes, or `abbrev` for an abbreviated number in Kb or Mb, as appropriate. Executing commands ------------------ Here's something else that you can do with the `exec` function. You can actually have SSI execute a command using the shell (`/bin/sh`, to be precise - or the DOS shell, if you're on Win32). The following, for example, will give you a directory listing. ``` <pre> <!--#exec cmd="ls" --> </pre> ``` or, on Windows ``` <pre> <!--#exec cmd="dir" --> </pre> ``` You might notice some strange formatting with this directive on Windows, because the output from `dir` contains the string ``<`dir`>'' in it, which confuses browsers. Note that this feature is exceedingly dangerous, as it will execute whatever code happens to be embedded in the `exec` tag. If you have any situation where users can edit content on your web pages, such as with a ``guestbook'', for example, make sure that you have this feature disabled. You can allow SSI, but not the `exec` feature, with the `IncludesNOEXEC` argument to the `Options` directive. Advanced SSI techniques ----------------------- In addition to spitting out content, Apache SSI gives you the option of setting variables, and using those variables in comparisons and conditionals. ### Setting variables Using the `set` directive, you can set variables for later use. We'll need this later in the discussion, so we'll talk about it here. The syntax of this is as follows: ``` <!--#set var="name" value="Rich" --> ``` In addition to merely setting values literally like that, you can use any other variable, including [environment variables](../env) or the variables discussed above (like `LAST_MODIFIED`, for example) to give values to your variables. You will specify that something is a variable, rather than a literal string, by using the dollar sign ($) before the name of the variable. ``` <!--#set var="modified" value="$LAST_MODIFIED" --> ``` To put a literal dollar sign into the value of your variable, you need to escape the dollar sign with a backslash. ``` <!--#set var="cost" value="\$100" --> ``` Finally, if you want to put a variable in the midst of a longer string, and there's a chance that the name of the variable will run up against some other characters, and thus be confused with those characters, you can place the name of the variable in braces, to remove this confusion. (It's hard to come up with a really good example of this, but hopefully you'll get the point.) ``` <!--#set var="date" value="${DATE_LOCAL}_${DATE_GMT}" --> ``` ### Conditional expressions Now that we have variables, and are able to set and compare their values, we can use them to express conditionals. This lets SSI be a tiny programming language of sorts. `[mod\_include](../mod/mod_include)` provides an `if`, `elif`, `else`, `endif` structure for building conditional statements. This allows you to effectively generate multiple logical pages out of one actual page. The structure of this conditional construct is: ``` <!--#if expr="test_condition" --> <!--#elif expr="test_condition" --> <!--#else --> <!--#endif --> ``` A *test\_condition* can be any sort of logical comparison - either comparing values to one another, or testing the ``truth'' of a particular value. (A given string is true if it is nonempty.) For a full list of the comparison operators available to you, see the `[mod\_include](../mod/mod_include)` documentation. For example, if you wish to customize the text on your web page based on the time of day, you could use the following recipe, placed in the HTML page: ``` Good <!--#if expr="%{TIME_HOUR} <12" --> morning! <!--#else --> afternoon! <!--#endif --> ``` Any other variable (either ones that you define, or normal environment variables) can be used in conditional statements. See [Expressions in Apache HTTP Server](../expr) for more information on the expression evaluation engine. With Apache's ability to set environment variables with the `SetEnvIf` directives, and other related directives, this functionality can let you do a wide variety of dynamic content on the server side without resorting a full web application. Conclusion ---------- SSI is certainly not a replacement for CGI, or other technologies used for generating dynamic web pages. But it is a great way to add small amounts of dynamic content to pages, without doing a lot of extra work. apache_http_server Apache Module mod_buffer Apache Module mod\_buffer ========================= | | | | --- | --- | | Description: | Support for request buffering | | Status: | Extension | | Module Identifier: | buffer\_module | | Source File: | mod\_buffer.c | | Compatibility: | Available in Apache 2.3 and later | ### Summary This module provides the ability to buffer the input and output filter stacks. Under certain circumstances, content generators might create content in small chunks. In order to promote memory reuse, in memory chunks are always 8k in size, regardless of the size of the chunk itself. When many small chunks are generated by a request, this can create a large memory footprint while the request is being processed, and an unnecessarily large amount of data on the wire. The addition of a buffer collapses the response into the fewest chunks possible. When httpd is used in front of an expensive content generator, buffering the response may allow the backend to complete processing and release resources sooner, depending on how the backend is designed. The buffer filter may be added to either the input or the output filter stacks, as appropriate, using the `[SetInputFilter](core#setinputfilter)`, `[SetOutputFilter](core#setoutputfilter)`, `[AddOutputFilter](mod_mime#addoutputfilter)` or `[AddOutputFilterByType](mod_filter#addoutputfilterbytype)` directives. ### Using buffer with mod\_include ``` AddOutputFilterByType INCLUDES;BUFFER text/html ``` The buffer filters read the request/response into RAM and then repack the request/response into the fewest memory buckets possible, at the cost of CPU time. When the request/response is already efficiently packed, buffering the request/response could cause the request/response to be slower than not using a buffer at all. These filters should be used with care, and only where necessary. BufferSize Directive -------------------- | | | | --- | --- | | Description: | Maximum size in bytes to buffer by the buffer filter | | Syntax: | ``` BufferSize integer ``` | | Default: | ``` BufferSize 131072 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_buffer | The `[BufferSize](#buffersize)` directive specifies the amount of data in bytes that will be buffered before being read from or written to each request. The default is 128 kilobytes. apache_http_server Apache Module mod_session_cookie Apache Module mod\_session\_cookie ================================== | | | | --- | --- | | Description: | Cookie based session support | | Status: | Extension | | Module Identifier: | session\_cookie\_module | | Source File: | mod\_session\_cookie.c | | Compatibility: | Available in Apache 2.3 and later | ### Summary **Warning** The session modules make use of HTTP cookies, and as such can fall victim to Cross Site Scripting attacks, or expose potentially private information to clients. Please ensure that the relevant risks have been taken into account before enabling the session functionality on your server. This submodule of `<mod_session>` provides support for the storage of user sessions on the remote browser within HTTP cookies. Using cookies to store a session removes the need for the server or a group of servers to store the session locally, or collaborate to share a session, and can be useful for high traffic environments where a server based session might be too resource intensive. If session privacy is required, the `<mod_session_crypto>` module can be used to encrypt the contents of the session before writing the session to the client. For more details on the session interface, see the documentation for the `<mod_session>` module. Basic Examples -------------- To create a simple session and store it in a cookie called session, configure the session as follows: ### Browser based session ``` Session On SessionCookieName session path=/ ``` For more examples on how the session can be configured to be read from and written to by a CGI application, see the `<mod_session>` examples section. For documentation on how the session can be used to store username and password details, see the `<mod_auth_form>` module. SessionCookieName Directive --------------------------- | | | | --- | --- | | Description: | Name and attributes for the RFC2109 cookie storing the session | | Syntax: | ``` SessionCookieName name attributes ``` | | Default: | `none` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session\_cookie | The `SessionCookieName` directive specifies the name and optional attributes of an RFC2109 compliant cookie inside which the session will be stored. RFC2109 cookies are set using the `Set-Cookie` HTTP header. An optional list of cookie attributes can be specified, as per the example below. These attributes are inserted into the cookie as is, and are not interpreted by Apache. Ensure that your attributes are defined correctly as per the cookie specification. ### Cookie with attributes ``` Session On SessionCookieName session path=/private;domain=example.com;httponly;secure;version=1; ``` SessionCookieName2 Directive ---------------------------- | | | | --- | --- | | Description: | Name and attributes for the RFC2965 cookie storing the session | | Syntax: | ``` SessionCookieName2 name attributes ``` | | Default: | `none` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session\_cookie | The `SessionCookieName2` directive specifies the name and optional attributes of an RFC2965 compliant cookie inside which the session will be stored. RFC2965 cookies are set using the `Set-Cookie2` HTTP header. An optional list of cookie attributes can be specified, as per the example below. These attributes are inserted into the cookie as is, and are not interpreted by Apache. Ensure that your attributes are defined correctly as per the cookie specification. ### Cookie2 with attributes ``` Session On SessionCookieName2 session path=/private;domain=example.com;httponly;secure;version=1; ``` SessionCookieRemove Directive ----------------------------- | | | | --- | --- | | Description: | Control for whether session cookies should be removed from incoming HTTP headers | | Syntax: | ``` SessionCookieRemove On|Off ``` | | Default: | ``` SessionCookieRemove Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session\_cookie | The `SessionCookieRemove` flag controls whether the cookies containing the session will be removed from the headers during request processing. In a reverse proxy situation where the Apache server acts as a server frontend for a backend origin server, revealing the contents of the session cookie to the backend could be a potential privacy violation. When set to on, the session cookie will be removed from the incoming HTTP headers.
programming_docs
apache_http_server Apache Module mod_userdir Apache Module mod\_userdir ========================== | | | | --- | --- | | Description: | User-specific directories | | Status: | Base | | Module Identifier: | userdir\_module | | Source File: | mod\_userdir.c | ### Summary By using this module you are allowing multiple users to host content within the same origin. The same origin policy is a key principle of Javascript and web security. By hosting web pages in the same origin these pages can read and control each other and security issues in one page may affect another. This is particularly dangerous in combination with web pages involving dynamic content and authentication and when your users don't necessarily trust each other. This module allows user-specific directories to be accessed using the `http://example.com/~user/` syntax. UserDir Directive ----------------- | | | | --- | --- | | Description: | Location of the user-specific directories | | Syntax: | ``` UserDir directory-filename [directory-filename] ... ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_userdir | The `UserDir` directive sets the real directory in a user's home directory to use when a request for a document for a user is received. *Directory-filename* is one of the following: * The name of a directory or a pattern such as those shown below. * The keyword `disabled`. This turns off *all* username-to-directory translations except those explicitly named with the `enabled` keyword (see below). * The keyword `disabled` followed by a space-delimited list of usernames. Usernames that appear in such a list will *never* have directory translation performed, even if they appear in an `enabled` clause. * The keyword `enabled` followed by a space-delimited list of usernames. These usernames will have directory translation performed even if a global disable is in effect, but not if they also appear in a `disabled` clause. If neither the `enabled` nor the `disabled` keywords appear in the `Userdir` directive, the argument is treated as a filename pattern, and is used to turn the name into a directory specification. A request for `http://www.example.com/~bob/one/two.html` will be translated to: | UserDir directive used | Translated path | | --- | --- | | UserDir public\_html | ~bob/public\_html/one/two.html | | UserDir /usr/web | /usr/web/bob/one/two.html | | UserDir /home/\*/www | /home/bob/www/one/two.html | The following directives will send redirects to the client: | UserDir directive used | Translated path | | --- | --- | | UserDir http://www.example.com/users | http://www.example.com/users/bob/one/two.html | | UserDir http://www.example.com/\*/usr | http://www.example.com/bob/usr/one/two.html | | UserDir http://www.example.com/~\*/ | http://www.example.com/~bob/one/two.html | **Be careful when using this directive; for instance, `"UserDir ./"` would map `"/~root"` to `"/"` - which is probably undesirable. It is strongly recommended that your configuration include a "`UserDir disabled root`" declaration. See also the `[Directory](core#directory)` directive and the [Security Tips](../misc/security_tips) page for more information.** Additional examples: To allow a few users to have `UserDir` directories, but not anyone else, use the following: ``` UserDir disabled UserDir enabled user1 user2 user3 ``` To allow most users to have `UserDir` directories, but deny this to a few, use the following: ``` UserDir disabled user4 user5 user6 ``` It is also possible to specify alternative user directories. If you use a command like: ``` UserDir "public_html" "/usr/web" "http://www.example.com/" ``` With a request for `http://www.example.com/~bob/one/two.html`, will try to find the page at `~bob/public_html/one/two.html` first, then `/usr/web/bob/one/two.html`, and finally it will send a redirect to `http://www.example.com/bob/one/two.html`. If you add a redirect, it must be the last alternative in the list. Apache httpd cannot determine if the redirect succeeded or not, so if you have the redirect earlier in the list, that will always be the alternative that is used. User directory substitution is not active by default in versions 2.1.4 and later. In earlier versions, `UserDir public_html` was assumed if no `UserDir` directive was present. **Merging details** Lists of specific enabled and disabled users are replaced, not merged, from global to virtual host scope ### See also * [Per-user web directories tutorial](../howto/public_html) apache_http_server Apache Module mod_headers Apache Module mod\_headers ========================== | | | | --- | --- | | Description: | Customization of HTTP request and response headers | | Status: | Extension | | Module Identifier: | headers\_module | | Source File: | mod\_headers.c | ### Summary This module provides directives to control and modify HTTP request and response headers. Headers can be merged, replaced or removed. Order of Processing ------------------- The directives provided by `<mod_headers>` can occur almost anywhere within the server configuration, and can be limited in scope by enclosing them in [configuration sections](../sections). Order of processing is important and is affected both by the order in the configuration file and by placement in [configuration sections](../sections#mergin). These two directives have a different effect if reversed: ``` RequestHeader append MirrorID "mirror 12" RequestHeader unset MirrorID ``` This way round, the `MirrorID` header is not set. If reversed, the MirrorID header is set to "mirror 12". Early and Late Processing ------------------------- `<mod_headers>` can be applied either early or late in the request. The normal mode is late, when *Request* Headers are set immediately before running the content generator and *Response* Headers just as the response is sent down the wire. Always use Late mode in an operational server. Early mode is designed as a test/debugging aid for developers. Directives defined using the `early` keyword are set right at the beginning of processing the request. This means they can be used to simulate different requests and set up test cases, but it also means that headers may be changed at any time by other modules before generating a Response. Because early directives are processed before the request path's configuration is traversed, early headers can only be set in a main server or virtual host context. Early directives cannot depend on a request path, so they will fail in contexts such as `[<Directory>](core#directory)` or `[<Location>](core#location)`. Examples -------- 1. Copy all request headers that begin with "TS" to the response headers: ``` Header echo ^TS ``` 2. Add a header, `MyHeader`, to the response including a timestamp for when the request was received and how long it took to begin serving the request. This header can be used by the client to intuit load on the server or in isolating bottlenecks between the client and the server. ``` Header set MyHeader "%D %t" ``` results in this header being added to the response: ``` MyHeader: D=3775428 t=991424704447256 ``` 3. Say hello to Joe ``` Header set MyHeader "Hello Joe. It took %D microseconds for Apache to serve this request." ``` results in this header being added to the response: ``` MyHeader: Hello Joe. It took D=3775428 microseconds for Apache to serve this request. ``` 4. Conditionally send `MyHeader` on the response if and only if header `MyRequestHeader` is present on the request. This is useful for constructing headers in response to some client stimulus. Note that this example requires the services of the `<mod_setenvif>` module. ``` SetEnvIf MyRequestHeader myvalue HAVE_MyRequestHeader Header set MyHeader "%D %t mytext" env=HAVE_MyRequestHeader ``` If the header `MyRequestHeader: myvalue` is present on the HTTP request, the response will contain the following header: ``` MyHeader: D=3775428 t=991424704447256 mytext ``` 5. Enable DAV to work with Apache running HTTP through SSL hardware ([problem description](http://svn.haxx.se/users/archive-2006-03/0549.shtml)) by replacing https: with http: in the Destination header: ``` RequestHeader edit Destination ^https: http: early ``` 6. Set the same header value under multiple nonexclusive conditions, but do not duplicate the value in the final header. If all of the following conditions applied to a request (i.e., if the `CGI`, `NO_CACHE` and `NO_STORE` environment variables all existed for the request): ``` Header merge Cache-Control no-cache env=CGI Header merge Cache-Control no-cache env=NO_CACHE Header merge Cache-Control no-store env=NO_STORE ``` then the response would contain the following header: ``` Cache-Control: no-cache, no-store ``` If `append` was used instead of `merge`, then the response would contain the following header: ``` Cache-Control: no-cache, no-cache, no-store ``` 7. Set a test cookie if and only if the client didn't send us a cookie ``` Header set Set-Cookie testcookie "expr=-z %{req:Cookie}" ``` 8. Append a Caching header for responses with a HTTP status code of 200 ``` Header append Cache-Control s-maxage=600 "expr=%{REQUEST_STATUS} == 200" ``` Header Directive ---------------- | | | | --- | --- | | Description: | Configure HTTP response headers | | Syntax: | ``` Header [condition] add|append|echo|edit|edit*|merge|set|setifempty|unset|note header [[expr=]value [replacement] [early|env=[!]varname|expr=expression]] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_headers | | Compatibility: | SetIfEmpty available in 2.4.7 and later, expr=value available in 2.4.10 and later | This directive can replace, merge or remove HTTP response headers. The header is modified just after the content handler and output filters are run, allowing outgoing headers to be modified. The optional condition argument determines which internal table of responses headers this directive will operate against: `onsuccess` (default, can be omitted) or `always`. The difference between the two lists is that the headers contained in the latter are added to the response even on error, and persisted across internal redirects (for example, ErrorDocument handlers). Note also that repeating this directive with both conditions makes sense in some scenarios because `always` is not a superset of `onsuccess` with respect to existing headers: * You're adding a header to a locally generated non-success (non-2xx) response, such as a redirect, in which case only the table corresponding to `always` is used in the ultimate response. * You're modifying or removing a header generated by a CGI script or by `<mod_proxy_fcgi>`, in which case the CGI scripts' headers are in the table corresponding to `always` and not in the default table. * You're modifying or removing a header generated by some piece of the server but that header is not being found by the default `onsuccess` condition. This difference between `onsuccess` and `always` is a feature that resulted as a consequence of how httpd internally stores headers for a HTTP response, since it does not offer any "normalized" single list of headers. The main problem that can arise if the following concept is not kept in mind while writing the configuration is that some HTTP responses might end up with the same header duplicated (confusing users or sometimes even HTTP clients). For example, suppose that you have a simple PHP proxy setup with `<mod_proxy_fcgi>` and your backend PHP scripts adds the `X-Foo: bar` header to each HTTP response. As described above, `<mod_proxy_fcgi>` uses the `always` table to store headers, so a configuration like the following ends up in the wrong result, namely having the header duplicated with both values: ``` # X-Foo's value is set in the 'onsuccess' headers table Header set X-Foo: baz ``` To circumvent this limitation, there are some known configuration patterns that can help, like the following: ``` # 'onsuccess' can be omitted since it is the default Header onsuccess unset X-Foo Header always set X-Foo "baz" ``` Separately from the condition parameter described above, you can limit an action based on HTTP status codes for e.g. proxied or CGI requests. See the example that uses %{REQUEST\_STATUS} in the section above. The action it performs is determined by the first argument (second argument if a condition is specified). This can be one of the following values: **Warning** Please read the difference between `always` and `onsuccess` headers list described above before start reading the actions list, since that important concept still applies. Each action, in fact, works as described but only on the target headers list. `add` The response header is added to the existing set of headers, even if this header already exists. This can result in two (or more) headers having the same name. This can lead to unforeseen consequences, and in general `set`, `append` or `merge` should be used instead. `append` The response header is appended to any existing header of the same name. When a new value is merged onto an existing header it is separated from the existing header with a comma. This is the HTTP standard way of giving a header multiple values. `echo` Request headers with this name are echoed back in the response headers. header may be a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"). value must be omitted. `edit` `edit*` If this response header exists, its value is transformed according to a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") search-and-replace. The value argument is a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"), and the replacement is a replacement string, which may contain backreferences or format specifiers. The `edit` form will match and replace exactly once in a header value, whereas the `edit*` form will replace *every* instance of the search pattern if it appears more than once. `merge` The response header is appended to any existing header of the same name, unless the value to be appended already appears in the header's comma-delimited list of values. When a new value is merged onto an existing header it is separated from the existing header with a comma. This is the HTTP standard way of giving a header multiple values. Values are compared in a case sensitive manner, and after all format specifiers have been processed. Values in double quotes are considered different from otherwise identical unquoted values. `set` The response header is set, replacing any previous header with this name. The value may be a format string. `setifempty` The request header is set, but only if there is no previous header with this name. The Content-Type header is a special use case since there might be the chance that its value have been determined but the header is not part of the response when `setifempty` is evaluated. It is safer to use `set` for this use case like in the following example: ``` Header set Content-Type "text/plain" "expr=-z %{CONTENT_TYPE}" ``` `unset` The response header of this name is removed, if it exists. If there are multiple headers of the same name, all will be removed. value must be omitted. `note` The value of the named response header is copied into an internal note whose name is given by value. This is useful if a header sent by a CGI or proxied resource is configured to be unset but should also be logged. Available in 2.4.7 and later. This argument is followed by a header name, which can include the final colon, but it is not required. Case is ignored for `set`, `append`, `merge`, `add`, `unset` and `edit`. The header name for `echo` is case sensitive and may be a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"). For `set`, `append`, `merge` and `add` a value is specified as the next argument. If value contains spaces, it should be surrounded by double quotes. value may be a character string, a string containing `<mod_headers>` specific format specifiers (and character literals), or an [ap\_expr](../expr) expression prefixed with *expr=* The following format specifiers are supported in value: | Format | Description | | --- | --- | | `%%` | The percent sign | | `%t` | The time the request was received in Universal Coordinated Time since the epoch (Jan. 1, 1970) measured in microseconds. The value is preceded by `t=`. | | `%D` | The time from when the request was received to the time the headers are sent on the wire. This is a measure of the duration of the request. The value is preceded by `D=`. The value is measured in microseconds. | | `%l` | The current load averages of the actual server itself. It is designed to expose the values obtained by `getloadavg()` and this represents the current load average, the 5 minute average, and the 15 minute average. The value is preceded by `l=` with each average separated by `/`. Available in 2.4.4 and later. | | `%i` | The current idle percentage of httpd (0 to 100) based on available processes and threads. The value is preceded by `i=`. Available in 2.4.4 and later. | | `%b` | The current busy percentage of httpd (0 to 100) based on available processes and threads. The value is preceded by `b=`. Available in 2.4.4 and later. | | `%{VARNAME}e` | The contents of the [environment variable](../env) `VARNAME`. | | `%{VARNAME}s` | The contents of the [SSL environment variable](mod_ssl#envvars) `VARNAME`, if `<mod_ssl>` is enabled. | **Note** The `%s` format specifier is only available in Apache 2.1 and later; it can be used instead of `%e` to avoid the overhead of enabling `SSLOptions +StdEnvVars`. If `SSLOptions +StdEnvVars` must be enabled anyway for some other reason, `%e` will be more efficient than `%s`. **Note on expression values** When the value parameter uses the [ap\_expr](../expr) parser, some expression syntax will differ from examples that evaluate *boolean* expressions such as <If>: * The starting point of the grammar is 'string' rather than 'expr'. * Function calls use the %{funcname:arg} syntax rather than funcname(arg). * Multi-argument functions are not currently accessible from this starting point * Quote the entire parameter, such as ``` Header set foo-checksum "expr=%{md5:foo}" ``` For `edit` there is both a value argument which is a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"), and an additional replacement string. As of version 2.4.7 the replacement string may also contain format specifiers. The `Header` directive may be followed by an additional argument, which may be any of: `early` Specifies [early processing](#early). `env=[!]varname` The directive is applied if and only if the [environment variable](../env) `varname` exists. A `!` in front of `varname` reverses the test, so the directive applies only if `varname` is unset. `expr=expression` The directive is applied if and only if expression evaluates to true. Details of expression syntax and evaluation are documented in the [ap\_expr](../expr) documentation. ``` # This delays the evaluation of the condition clause compared to <If> Header always set CustomHeader my-value "expr=%{REQUEST_URI} =~ m#^/special_path.php$#" ``` Except in [early](#early) mode, the `Header` directives are processed just before the response is sent to the network. This means that it is possible to set and/or override most headers, except for some headers added by the HTTP header filter. Prior to 2.2.12, it was not possible to change the Content-Type header with this directive. RequestHeader Directive ----------------------- | | | | --- | --- | | Description: | Configure HTTP request headers | | Syntax: | ``` RequestHeader add|append|edit|edit*|merge|set|setifempty|unset header [[expr=]value [replacement] [early|env=[!]varname|expr=expression]] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_headers | | Compatibility: | SetIfEmpty available in 2.4.7 and later, expr=value available in 2.4.10 and later | This directive can replace, merge, change or remove HTTP request headers. The header is modified just before the content handler is run, allowing incoming headers to be modified. The action it performs is determined by the first argument. This can be one of the following values: `add` The request header is added to the existing set of headers, even if this header already exists. This can result in two (or more) headers having the same name. This can lead to unforeseen consequences, and in general `set`, `append` or `merge` should be used instead. `append` The request header is appended to any existing header of the same name. When a new value is merged onto an existing header it is separated from the existing header with a comma. This is the HTTP standard way of giving a header multiple values. `edit` `edit*` If this request header exists, its value is transformed according to a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") search-and-replace. The value argument is a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"), and the replacement is a replacement string, which may contain backreferences or format specifiers. The `edit` form will match and replace exactly once in a header value, whereas the `edit*` form will replace *every* instance of the search pattern if it appears more than once. `merge` The request header is appended to any existing header of the same name, unless the value to be appended already appears in the existing header's comma-delimited list of values. When a new value is merged onto an existing header it is separated from the existing header with a comma. This is the HTTP standard way of giving a header multiple values. Values are compared in a case sensitive manner, and after all format specifiers have been processed. Values in double quotes are considered different from otherwise identical unquoted values. `set` The request header is set, replacing any previous header with this name `setifempty` The request header is set, but only if there is no previous header with this name. Available in 2.4.7 and later. `unset` The request header of this name is removed, if it exists. If there are multiple headers of the same name, all will be removed. value must be omitted. This argument is followed by a header name, which can include the final colon, but it is not required. Case is ignored. For `set`, `append`, `merge` and `add` a value is given as the third argument. If a value contains spaces, it should be surrounded by double quotes. For `unset`, no value should be given. value may be a character string, a string containing format specifiers or a combination of both. The supported format specifiers are the same as for the `[Header](#header)`, please have a look there for details. For `edit` both a value and a replacement are required, and are a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") and a replacement string respectively. The `RequestHeader` directive may be followed by an additional argument, which may be any of: `early` Specifies [early processing](#early). `env=[!]varname` The directive is applied if and only if the [environment variable](../env) `varname` exists. A `!` in front of `varname` reverses the test, so the directive applies only if `varname` is unset. `expr=expression` The directive is applied if and only if expression evaluates to true. Details of expression syntax and evaluation are documented in the [ap\_expr](../expr) documentation. Except in [early](#early) mode, the `RequestHeader` directive is processed just before the request is run by its handler in the fixup phase. This should allow headers generated by the browser, or by Apache input filters to be overridden or modified.
programming_docs
apache_http_server Apache Module mod_imagemap Apache Module mod\_imagemap =========================== | | | | --- | --- | | Description: | Server-side imagemap processing | | Status: | Base | | Module Identifier: | imagemap\_module | | Source File: | mod\_imagemap.c | ### Summary This module processes `.map` files, thereby replacing the functionality of the `imagemap` CGI program. Any directory or document type configured to use the handler `imap-file` (using either `[AddHandler](mod_mime#addhandler)` or `[SetHandler](core#sethandler)`) will be processed by this module. The following directive will activate files ending with `.map` as imagemap files: ``` AddHandler imap-file map ``` Note that the following is still supported: ``` AddType application/x-httpd-imap map ``` However, we are trying to phase out "magic MIME types" so we are deprecating this method. New Features ------------ The imagemap module adds some new features that were not possible with previously distributed imagemap programs. * URL references relative to the Referer: information. * Default `<base>` assignment through a new map directive `base`. * No need for `imagemap.conf` file. * Point references. * Configurable generation of imagemap menus. Imagemap File ------------- The lines in the imagemap files can have one of several formats: ``` directive value [x,y ...] directive value "Menu text" [x,y ...] directive value x,y ... "Menu text" ``` The directive is one of `base`, `default`, `poly`, `circle`, `rect`, or `point`. The value is an absolute or relative URL, or one of the special values listed below. The coordinates are `x,y` pairs separated by whitespace. The quoted text is used as the text of the link if a imagemap menu is generated. Lines beginning with '#' are comments. ### Imagemap File Directives There are six directives allowed in the imagemap file. The directives can come in any order, but are processed in the order they are found in the imagemap file. `base` Directive Has the effect of `<base href="value">`. The non-absolute URLs of the map-file are taken relative to this value. The `base` directive overrides `[ImapBase](#imapbase)` as set in a `.htaccess` file or in the server configuration files. In the absence of an `ImapBase` configuration directive, `base` defaults to `http://server_name/`. `base_uri` is synonymous with `base`. Note that a trailing slash on the URL is significant. `default` Directive The action taken if the coordinates given do not fit any of the `poly`, `circle` or `rect` directives, and there are no `point` directives. Defaults to `nocontent` in the absence of an `[ImapDefault](#imapdefault)` configuration setting, causing a status code of `204 No Content` to be returned. The client should keep the same page displayed. `poly` Directive Takes three to one-hundred points, and is obeyed if the user selected coordinates fall within the polygon defined by these points. `circle` Takes the center coordinates of a circle and a point on the circle. Is obeyed if the user selected point is with the circle. `rect` Directive Takes the coordinates of two opposing corners of a rectangle. Obeyed if the point selected is within this rectangle. `point` Directive Takes a single point. The point directive closest to the user selected point is obeyed if no other directives are satisfied. Note that `default` will not be followed if a `point` directive is present and valid coordinates are given. ### Values The values for each of the directives can be any of the following: a URL The URL can be relative or absolute URL. Relative URLs can contain '..' syntax and will be resolved relative to the `base` value. `base` itself will not be resolved according to the current value. A statement `base mailto:` will work properly, though. `map` Equivalent to the URL of the imagemap file itself. No coordinates are sent with this, so a menu will be generated unless `[ImapMenu](#imapmenu)` is set to `none`. `menu` Synonymous with `map`. `referer` Equivalent to the URL of the referring document. Defaults to `http://servername/` if no `Referer:` header was present. `nocontent` Sends a status code of `204 No Content`, telling the client to keep the same page displayed. Valid for all but `base`. `error` Fails with a `500 Server Error`. Valid for all but `base`, but sort of silly for anything but `default`. ### Coordinates `0,0 200,200` A coordinate consists of an x and a y value separated by a comma. The coordinates are separated from each other by whitespace. To accommodate the way Lynx handles imagemaps, should a user select the coordinate `0,0`, it is as if no coordinate had been selected. ### Quoted Text `"Menu Text"` After the value or after the coordinates, the line optionally may contain text within double quotes. This string is used as the text for the link if a menu is generated: ``` <a href="http://example.com/">Menu text</a> ``` If no quoted text is present, the name of the link will be used as the text: ``` <a href="http://example.com/">http://example.com</a> ``` If you want to use double quotes within this text, you have to write them as `&quot;`. Example Mapfile --------------- ``` #Comments are printed in a 'formatted' or 'semiformatted' menu. #And can contain html tags. <hr> base referer poly map "Could I have a menu, please?" 0,0 0,10 10,10 10,0 rect .. 0,0 77,27 "the directory of the referer" circle http://www.inetnebr.example.com/lincoln/feedback/ 195,0 305,27 rect another_file "in same directory as referer" 306,0 419,27 point http://www.zyzzyva.example.com/ 100,100 point http://www.tripod.example.com/ 200,200 rect mailto:[email protected] 100,150 200,0 "Bugs?" ``` Referencing your mapfile ------------------------ ### HTML example ``` <a href="/maps/imagemap1.map"> <img ismap src="/images/imagemap1.gif"> </a> ``` ### XHTML example ``` <a href="/maps/imagemap1.map"> <img ismap="ismap" src="/images/imagemap1.gif" /> </a> ``` ImapBase Directive ------------------ | | | | --- | --- | | Description: | Default `base` for imagemap files | | Syntax: | ``` ImapBase map|referer|URL ``` | | Default: | ``` ImapBase http://servername/ ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_imagemap | The `ImapBase` directive sets the default `base` used in the imagemap files. Its value is overridden by a `base` directive within the imagemap file. If not present, the `base` defaults to `http://servername/`. ### See also * `[UseCanonicalName](core#usecanonicalname)` ImapDefault Directive --------------------- | | | | --- | --- | | Description: | Default action when an imagemap is called with coordinates that are not explicitly mapped | | Syntax: | ``` ImapDefault error|nocontent|map|referer|URL ``` | | Default: | ``` ImapDefault nocontent ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_imagemap | The `ImapDefault` directive sets the default `default` used in the imagemap files. Its value is overridden by a `default` directive within the imagemap file. If not present, the `default` action is `nocontent`, which means that a `204 No Content` is sent to the client. In this case, the client should continue to display the original page. ImapMenu Directive ------------------ | | | | --- | --- | | Description: | Action if no coordinates are given when calling an imagemap | | Syntax: | ``` ImapMenu none|formatted|semiformatted|unformatted ``` | | Default: | ``` ImapMenu formatted ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_imagemap | The `ImapMenu` directive determines the action taken if an imagemap file is called without valid coordinates. `none` If ImapMenu is `none`, no menu is generated, and the `default` action is performed. `formatted` A `formatted` menu is the simplest menu. Comments in the imagemap file are ignored. A level one header is printed, then an hrule, then the links each on a separate line. The menu has a consistent, plain look close to that of a directory listing. `semiformatted` In the `semiformatted` menu, comments are printed where they occur in the imagemap file. Blank lines are turned into HTML breaks. No header or hrule is printed, but otherwise the menu is the same as a `formatted` menu. `unformatted` Comments are printed, blank lines are ignored. Nothing is printed that does not appear in the imagemap file. All breaks and headers must be included as comments in the imagemap file. This gives you the most flexibility over the appearance of your menus, but requires you to treat your map files as HTML instead of plaintext. apache_http_server Apache Module mod_cern_meta Apache Module mod\_cern\_meta ============================= | | | | --- | --- | | Description: | CERN httpd metafile semantics | | Status: | Extension | | Module Identifier: | cern\_meta\_module | | Source File: | mod\_cern\_meta.c | ### Summary Emulate the CERN HTTPD Meta file semantics. Meta files are HTTP headers that can be output in addition to the normal range of headers for each file accessed. They appear rather like the Apache .asis files, and are able to provide a crude way of influencing the Expires: header, as well as providing other curiosities. There are many ways to manage meta information, this one was chosen because there is already a large number of CERN users who can exploit this module. More information on the [CERN metafile semantics](http://www.w3.org/pub/WWW/Daemon/User/Config/General.html#MetaDir) is available. MetaDir Directive ----------------- | | | | --- | --- | | Description: | Name of the directory to find CERN-style meta information files | | Syntax: | ``` MetaDir directory ``` | | Default: | ``` MetaDir .web ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Extension | | Module: | mod\_cern\_meta | Specifies the name of the directory in which Apache can find meta information files. The directory is usually a 'hidden' subdirectory of the directory that contains the file being accessed. Set to "`.`" to look in the same directory as the file: ``` MetaDir . ``` Or, to set it to a subdirectory of the directory containing the files: ``` MetaDir .meta ``` MetaFiles Directive ------------------- | | | | --- | --- | | Description: | Activates CERN meta-file processing | | Syntax: | ``` MetaFiles on|off ``` | | Default: | ``` MetaFiles off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Extension | | Module: | mod\_cern\_meta | Turns on/off Meta file processing on a per-directory basis. MetaSuffix Directive -------------------- | | | | --- | --- | | Description: | File name suffix for the file containing CERN-style meta information | | Syntax: | ``` MetaSuffix suffix ``` | | Default: | ``` MetaSuffix .meta ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Extension | | Module: | mod\_cern\_meta | Specifies the file name suffix for the file containing the meta information. For example, the default values for the two directives will cause a request to `DOCUMENT_ROOT/somedir/index.html` to look in `DOCUMENT_ROOT/somedir/.web/index.html.meta` and will use its contents to generate additional MIME header information. ### Example: ``` MetaSuffix .meta ``` apache_http_server Apache Module mod_log_debug Apache Module mod\_log\_debug ============================= | | | | --- | --- | | Description: | Additional configurable debug logging | | Status: | Experimental | | Module Identifier: | log\_debug\_module | | Source File: | mod\_log\_debug.c | | Compatibility: | Available in Apache 2.3.14 and later | Examples -------- 1. Log message after request to /foo/\* is processed: ``` <Location "/foo/">   LogMessage "/foo/ has been requested" </Location> ``` 2. Log message if request to /foo/\* is processed in a sub-request: ``` <Location "/foo/">   LogMessage "subrequest to /foo/" hook=type_checker "expr=-T %{IS_SUBREQ}" </Location> ``` The default log\_transaction hook is not executed for sub-requests, therefore we have to use a different hook. 3. Log message if an IPv6 client causes a request timeout: ``` LogMessage "IPv6 timeout from %{REMOTE_ADDR}" "expr=-T %{IPV6} && %{REQUEST_STATUS} = 408" ``` Note the placing of the double quotes for the `expr=` argument. 4. Log the value of the "X-Foo" request environment variable in each stage of the request: ``` <Location "/">   LogMessage "%{reqenv:X-Foo}" hook=all </Location> ``` Together with microsecond time stamps in the error log, `hook=all` also lets you determine the times spent in the different parts of the request processing. LogMessage Directive -------------------- | | | | --- | --- | | Description: | Log user-defined message to error log | | Syntax: | ``` LogMessage message [hook=hook] [expr=expression] ``` | | Default: | `Unset` | | Context: | directory | | Status: | Experimental | | Module: | mod\_log\_debug | This directive causes a user defined message to be logged to the error log. The message can use variables and functions from the [ap\_expr syntax](../expr). References to HTTP headers will not cause header names to be added to the Vary header. The messages are logged at loglevel info. The hook specifies before which phase of request processing the message will be logged. The following hooks are supported: | Name | | --- | | `pre_translate_name` | | `translate_name` | | `type_checker` | | `quick_handler` | | `map_to_storage` | | `check_access` | | `check_access_ex` | | `insert_filter` | | `check_authn` | | `check_authz` | | `fixups` | | `handler` | | `log_transaction` | The default is `log_transaction`. The special value `all` is also supported, causing a message to be logged at each phase. Not all hooks are executed for every request. The optional expression allows to restrict the message if a condition is met. The details of the expression syntax are described in the [ap\_expr documentation](../expr). References to HTTP headers will not cause the header names to be added to the Vary header. apache_http_server Apache Module mod_authn_dbd Apache Module mod\_authn\_dbd ============================= | | | | --- | --- | | Description: | User authentication using an SQL database | | Status: | Extension | | Module Identifier: | authn\_dbd\_module | | Source File: | mod\_authn\_dbd.c | | Compatibility: | Available in Apache 2.1 and later | ### Summary This module provides authentication front-ends such as `<mod_auth_digest>` and `<mod_auth_basic>` to authenticate users by looking up users in SQL tables. Similar functionality is provided by, for example, `<mod_authn_file>`. This module relies on `<mod_dbd>` to specify the backend database driver and connection parameters, and manage the database connections. When using `<mod_auth_basic>` or `<mod_auth_digest>`, this module is invoked via the `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` or `[AuthDigestProvider](mod_auth_digest#authdigestprovider)` with the `dbd` value. Performance and Caching ----------------------- Some users of DBD authentication in HTTPD 2.2/2.4 have reported that it imposes a problematic load on the database. This is most likely where an HTML page contains hundreds of objects (e.g. images, scripts, etc) each of which requires authentication. Users affected (or concerned) by this kind of problem should use `<mod_authn_socache>` to cache credentials and take most of the load off the database. Configuration Example --------------------- This simple example shows use of this module in the context of the Authentication and DBD frameworks. ``` # mod_dbd configuration # UPDATED to include authentication caching DBDriver pgsql DBDParams "dbname=apacheauth user=apache password=xxxxxx" DBDMin 4 DBDKeep 8 DBDMax 20 DBDExptime 300 <Directory "/usr/www/myhost/private"> # mod_authn_core and mod_auth_basic configuration # for mod_authn_dbd AuthType Basic AuthName "My Server" # To cache credentials, put socache ahead of dbd here AuthBasicProvider socache dbd # Also required for caching: tell the cache to cache dbd lookups! AuthnCacheProvideFor dbd AuthnCacheContext my-server # mod_authz_core configuration Require valid-user # mod_authn_dbd SQL query to authenticate a user AuthDBDUserPWQuery "SELECT password FROM authn WHERE user = %s" </Directory> ``` Exposing Login Information -------------------------- If httpd was built against [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary") version 1.3.0 or higher, then whenever a query is made to the database server, all column values in the first row returned by the query are placed in the environment, using environment variables with the prefix "AUTHENTICATE\_". If a database query for example returned the username, full name and telephone number of a user, a CGI program will have access to this information without the need to make a second independent database query to gather this additional information. This has the potential to dramatically simplify the coding and configuration required in some web applications. AuthDBDUserPWQuery Directive ---------------------------- | | | | --- | --- | | Description: | SQL query to look up a password for a user | | Syntax: | ``` AuthDBDUserPWQuery query ``` | | Context: | directory | | Status: | Extension | | Module: | mod\_authn\_dbd | The `AuthDBDUserPWQuery` specifies an SQL query to look up a password for a specified user. The user's ID will be passed as a single string parameter when the SQL query is executed. It may be referenced within the query statement using a `%s` format specifier. ``` AuthDBDUserPWQuery "SELECT password FROM authn WHERE user = %s" ``` The first column value of the first row returned by the query statement should be a string containing the encrypted password. Subsequent rows will be ignored. If no rows are returned, the user will not be authenticated through `<mod_authn_dbd>`. If httpd was built against [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary") version 1.3.0 or higher, any additional column values in the first row returned by the query statement will be stored as environment variables with names of the form `AUTHENTICATE_COLUMN`. The encrypted password format depends on which authentication frontend (e.g. `<mod_auth_basic>` or `<mod_auth_digest>`) is being used. See [Password Formats](../misc/password_encryptions) for more information. AuthDBDUserRealmQuery Directive ------------------------------- | | | | --- | --- | | Description: | SQL query to look up a password hash for a user and realm. | | Syntax: | ``` AuthDBDUserRealmQuery query ``` | | Context: | directory | | Status: | Extension | | Module: | mod\_authn\_dbd | The `AuthDBDUserRealmQuery` specifies an SQL query to look up a password for a specified user and realm in a digest authentication process. The user's ID and the realm, in that order, will be passed as string parameters when the SQL query is executed. They may be referenced within the query statement using `%s` format specifiers. ``` AuthDBDUserRealmQuery "SELECT password FROM authn WHERE user = %s AND realm = %s" ``` The first column value of the first row returned by the query statement should be a string containing the encrypted password. Subsequent rows will be ignored. If no rows are returned, the user will not be authenticated through `<mod_authn_dbd>`. If httpd was built against [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary") version 1.3.0 or higher, any additional column values in the first row returned by the query statement will be stored as environment variables with names of the form `AUTHENTICATE_COLUMN`. The encrypted password format depends on which authentication frontend (e.g. `<mod_auth_basic>` or `<mod_auth_digest>`) is being used. See [Password Formats](../misc/password_encryptions) for more information.
programming_docs
apache_http_server Apache Module mod_md Apache Module mod\_md ===================== | | | | --- | --- | | Description: | Managing domains across virtual hosts, certificate provisioning via the ACME protocol | | Status: | Experimental | | Module Identifier: | md\_module | | Source File: | mod\_md.c | | Compatibility: | Available in version 2.4.30 and later | ### Summary This module manages common properties of domains for one or more virtual hosts. Its serves two main purposes: for one, supervise/renew TLS certificates via the ACME protocol ([RFC 8555](https://tools.ietf.org/html/rfc8555)). Certificates will be renewed by the module ahead of their expiration to account for disruption in internet services. There are ways to monitor the status of all certififcates managed this way and configurations that will run your own notification commands on renewal, expiration and errors. Second, mod\_md offers an alternate OCSP Stapling implementation. This works with managed certificates as well as with certificates you configure yourself. OCSP Stapling is a necessary component for any https: site, influencing page load times and, depending on other setups, page availability. More in the stapling section below. The default ACME Authority for managing certificates is [Let's Encrypt](https://letsencrypt.org/), but it is possible to configure another CA that supports the protocol. Simple configuration example: **TLS in a VirtualHost context** ``` MDomain example.org <VirtualHost *:443> ServerName example.org DocumentRoot htdocs/a SSLEngine on # no certificates specification </VirtualHost> ``` This setup will, on server start, contact [Let's Encrypt](https://letsencrypt.org/) to request a certificate for the domain. If Let's Encrypt can verify the ownership of the domain, the module will retrieve the certificate and its chain, store it in the local file system (see `[MDStoreDir](#mdstoredir)`) and provide it, on next restart, to `<mod_ssl>`. This happens while the server is already running. All other hosts will continue to work as before. While a certificate is not available, requests for the managed domain will be answered with a '503 Service Unavailable'. **Prerequisites** This module requires `<mod_watchdog>` to be loaded as well. Certificate sign-up and renewal with Let's Encrypt requires your server to be reachable on port 80 (http:) and/or port 443 (https:) from the public internet. (Unless your server is configured to use DNS for challenges - more on that under 'wildcard certificates') The module will select from the methods offered by Let's Encrypt. Usually LE offers challenges on both ports and DNS and Apache chooses a method available. To determine which one is available, the module looks at the ports Apache httpd listens on. If those include port 80, it assumes that the http: challenge (named http-01) is available. If the server listens on port 443, the https: challenge (named tls-alpn-01) is also added to the list. (And if `[MDChallengeDns01](#mdchallengedns01)` is configured, the challenge dns-01 is added as well.) If your setup is not so straight forward, there are two methods available to influence this. First, look at `[MDPortMap](#mdportmap)` if the server is behind a portmapper, such as a firewall. Second, you may override the module's guesswork completely by configuring `[MDCAChallenges](#mdcachallenges)` directly. **https: Challenges** For domain verification via the TLS protocol `tls-alpn-01` is the name of the challenge type. It requires the Apache server to listen on port 443 (see `[MDPortMap](#mdportmap)` if you map that port to something else). Let's Encrypt will open a TLS connection to Apache using the special indicator `acme-tls/1` (this indication part of TLS is called ALPN, therefore the name of the challenge. ALPN is also used by browsers to request a HTTP/2 connection). As with the HTTP/2 protocol, to allow this, you configure: ``` Protocols h2 http/1.1 acme-tls/1 ``` And the `tls-alpn-01` challenge type is available. **Wildcard Certificates** Wildcard certificates are possible, but not straight-forward to use out of the box. Let's Encrypt requires the `dns-01` challenge verification for those. No other is considered good enough. The difficulty here is that Apache cannot do that on its own. As the name implies, `dns-01` requires you to show some specific DNS records for your domain that contain some challenge data. So you need to \_write\_ your domain's DNS records. If you know how to do that, you can integrated this with mod\_md. Let's say you have a script for that in `/usr/bin/acme-setup-dns` you configure Apache with: ``` MDChallengeDns01 /usr/bin/acme-setup-dns ``` and Apache will call this script when it needs to setup/teardown a DNS challenge record for a domain. Assuming you want a certificate for `\*.mydomain.com`, mod\_md will call: ``` /usr/bin/acme-setup-dns setup mydomain.com challenge-data # this needs to remove all existing DNS TXT records for # _acme-challenge.mydomain.com and create a new one with # content "challenge-data" ``` and afterwards it will call ``` /usr/bin/acme-setup-dns teardown mydomain.com # this needs to remove all existing DNS TXT records for # _acme-challenge.mydomain.com ``` **Monitoring** Apache has a standard module for monitoring: `<mod_status>`. mod\_md contributes a section and makes monitoring your domains easy. You see all your MDs listed alphabetically, the domain names they contain, an overall status, expiration times and specific settings. The settings show your selection of renewal times (or the default), the CA that is used, etc. The 'Renewal' column will show activity and error descriptions for certificate renewals. This should make life easier for people to find out if everything is all right or what went wrong. If there is an error with an MD it will be shown here as well. This let's you assess problems without digging through your server logs. There is also a new 'md-status' handler available to give you the MD information from 'server-status' in JSON format. You configure it as ``` <Location "/md-status"> SetHandler md-status </Location> ``` on your server. As with 'server-status' you will want to add authorization for this. If you just want to check the JSON status of a specific domain, simply append that to your status url: ``` > curl https://<yourhost>/md-status/another-domain.org { "name": "another-domain.org", "domains": [ "another-domain.org", "www.another-domain.org" ], ... ``` This JSON status also shows a log of activities when domains are renewed: ``` { "when": "Wed, 19 Jun 2019 14:45:58 GMT", "type": "progress", "detail": "The certificate for the managed domain has been renewed successfully and can be used. A graceful server restart now is recommended." },{ "when": "Wed, 19 Jun 2019 14:45:58 GMT", "type": "progress", "detail": "Retrieving certificate chain for test-901-003-1560955549.org" },{ "when": "Wed, 19 Jun 2019 14:45:58 GMT", "type": "progress", "detail": "Waiting for finalized order to become valid" },{ "when": "Wed, 19 Jun 2019 14:45:50 GMT", "type": "progress", "detail": "Submitting CSR to CA for test-901-003-1560955549.org" }, ... ``` You will also find this information in the file `job.json` in your staging and, when activated, domains directory. This allows you to inspect these at any later point in time as well. In addition, there is `[MDCertificateStatus](#mdcertificatestatus)` which gives access to relevant certificate information in JSON format. **Stapling** If you want to try the stapling in one Managed Domain alone at first, configure: ``` <MDomain mydomain.net> MDStapling on </MDomain> ``` and use the 'server-status' and/or `[MDMessageCmd](#mdmessagecmd)` to see how it operates. You will see if Stapling information is there, how long it is valid, from where it came and when it will be refreshed. If this all works to your satisfaction, you can switch it on for all your certificates or just your managed ones. The existing stapling implementation by mod\_ssl is used by many sites for years. There are two main differences between the mod\_ssl and mod\_md one: 1. On demand vs. scheduled: mod\_ssl retrieves the stapling information when it is requested, e.g. on a new connection. mod\_md retrieves it right at server start and after 2/3rds of its lifetime. 2. In memory vs. persisted: mod\_ssl *can* persist this information, but most example configurations use a memory cache. mod\_md always stores in the file system. If you are unlucky and restart your server during an outage of your CA's OCSP service, your users may no longer reach your sites. Without persistence your server cannot provide the client with the data and the client browser cannot get it as well, since the OCSP service is not responding. The implementation in mod\_md will have persisted it, load it again after restart and have it available for incoming connections. A day or two before this information expires, it will renew it, making it able to cope with a long OCSP service downtime. Due to backward compatibility, the existing implementation in mod\_ssl could not be changed drastically. For example, mod\_ssl is unable to add a dependency to mod\_watchdog without braking many existing installations (that do not load it). MDActivationDelay Directive --------------------------- | | | | --- | --- | | Description: | | | Syntax: | ``` MDActivationDelay duration ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | | Compatibility: | Available in version 2.4.42 and later | MDBaseServer Directive ---------------------- | | | | --- | --- | | Description: | Control if base server may be managed or only virtual hosts. | | Syntax: | ``` MDBaseServer on|off ``` | | Default: | ``` MDBaseServer off ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | Controls if the base server, the one outside all VirtualHosts should be managed by mod\_md or not. By default, it will not. For the very reason that it may have confusing side-effects. It is recommended that you have virtual hosts for all managed domains and do not rely on the global, fallback server configuration. MDCAChallenges Directive ------------------------ | | | | --- | --- | | Description: | Type of ACME challenge used to prove domain ownership. | | Syntax: | ``` MDCAChallenges name [ name ... ] ``` | | Default: | ``` MDCAChallenges tls-alpn-01 http-01 dns-01 ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | Sets challenge types (in order of preference) when proving domain ownership. Supported by the module are the challenge methods 'tls-alpn-01', 'dns-01' and 'http-01'. The module will look at the overall configuration of the server to find out which methods can be used. If the server listens on port 80, for example, the 'http-01' method is available. The prerequisite for 'dns-01' is a configured `[MDChallengeDns01](#mdchallengedns01)` command. 'tls-alpn-01' is described above in 'https: Challenges'. This auto selection works for most setups. But since Apache is a very powerful server with many configuration options, the situation is not clear for all possible cases. For example: it may listen on multiple IP addresses where some are reachable on `https:` and some not. If you configure `MDCAChallenges` directly, this auto selection is disabled. Instead, the module will use the configured challenge list when talking to the ACME server (a challenge type must be offered by the server as well). This challenges are examined in the order specified. MDCertificateAgreement Directive -------------------------------- | | | | --- | --- | | Description: | You confirm that you accepted the Terms of Service of the Certificate Authority. | | Syntax: | ``` MDCertificateAgreement accepted ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | When you use mod\_md to obtain a certificate, you become a customer of the CA (e.g. Let's Encrypt). That means you need to read and agree to their Terms of Service, so that you understand what they offer and what they might exclude or require from you. mod\_md cannot, by itself, agree to such a thing. MDCertificateAuthority Directive -------------------------------- | | | | --- | --- | | Description: | The URL of the ACME Certificate Authority service. | | Syntax: | ``` MDCertificateAuthority url ``` | | Default: | ``` MDCertificateAuthority https://acme-v02.api.letsencrypt.org/directory ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | The URL where the CA offers its service. Let's Encrypt offers, right now, four such URLs. Two for the own legacy version of the ACME protocol, commonly named ACMEv1. And two for the RFC 8555 version, named ACMEv2. Each version has 2 endpoints, as their is a production endpoint and a "staging" endpoint for testing. The testing endpoint works the same, but will not give you certificates recognized by browsers. However, it also has very relaxed rate limits. This allows testing of the service repeatedly without you blocking yourself. ### LE Staging Setup ``` MDCertificateAuthority https://acme-staging-v02.api.letsencrypt.org/directory ``` MDCertificateCheck Directive ---------------------------- | | | | --- | --- | | Description: | | | Syntax: | ``` MDCertificateCheck name url ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | | Compatibility: | Available in version 2.4.42 and later | MDCertificateFile Directive --------------------------- | | | | --- | --- | | Description: | Specify a static certificate file for the MD. | | Syntax: | ``` MDCertificateFile path-to-pem-file ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | This is used inside a `[MDomainSet](#mdomainset)` and specifies the file holding the certificate chain for the Managed Domain. The matching key is specified via `[MDCertificateKeyFile](#mdcertificatekeyfile)`. ### Example ``` <MDomain mydomain.com> MDCertificateFile /etc/ssl/my.cert MDCertificateKeyFile /etc/ssl/my.key </MDomain> ``` This is that equivalent of the mod\_ssl `[SSLCertificateFile](mod_ssl#sslcertificatefile)` directive. It has several uses. If you want to migrate an existing domain, using static files, to automated Let's Encrypt certificates, for one. You define the `[MDomainSet](#mdomainset)`, add the files here and remove the `[SSLCertificateFile](mod_ssl#sslcertificatefile)` from your VirtualHosts. This will give you the same as before, with maybe less repeating lines in your configuration. Then you can add `[MDRenewMode](#mdrenewmode)` 'always' to it and the module will get a new certificate before the one from the file expires. When it has done so, you remove the `MDCertificateFile` and reload the server. Another use case is that you renew your Let's Encrypt certificates with another ACME clients, for example the excellent [certbot](https://certbot.eff.org). Then let your MDs point to the files from certbot and have both working together. MDCertificateKeyFile Directive ------------------------------ | | | | --- | --- | | Description: | Specify a static private key for for the static cerrtificate. | | Syntax: | ``` MDCertificateKeyFile path-to-file ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | This is used inside a `[MDomainSet](#mdomainset)` and specifies the file holding the private key for the Managed Domain. The matching certificate is specified via `[MDCertificateFile](#mdcertificatefile)`. This is that equivalent of the mod\_ssl `[SSLCertificateKeyFile](mod_ssl#sslcertificatekeyfile)` directive. MDCertificateMonitor Directive ------------------------------ | | | | --- | --- | | Description: | The URL of a certificate log monitor. | | Syntax: | ``` MDCertificateMonitor name url ``` | | Default: | ``` MDCertificateMonitor crt.sh https://crt.sh?q= ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | This is part of the 'server-status' HTML user interface and has nothing to do with the core functioning itself. It defines the link offered on that page for easy checking of a certificate monitor. The SHA256 fingerprint of the certificate is appended to the configured url. Certificate Monitors offer supervision of Certificate Transparency (CT) Logs to track the use of certificates for domains. The least you may see is that Let's Encrypt (or whichever CA you have configured) has entered your certificates into the CTLogs. Caveat: certificate logs update and monitor's intakes of those updates suffer some delay. This varies between logs and monitors. A brand new certificate will not be known immediately. MDCertificateProtocol Directive ------------------------------- | | | | --- | --- | | Description: | The protocol to use with the Certificate Authority. | | Syntax: | ``` MDCertificateProtocol protocol ``` | | Default: | ``` MDCertificateProtocol ACME ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | Specifies the protocol to use. Currently, only `ACME` is supported. MDCertificateStatus Directive ----------------------------- | | | | --- | --- | | Description: | Exposes public certificate information in JSON. | | Syntax: | ``` MDCertificateStatus on|off ``` | | Default: | ``` MDCertificateStatus on ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | When enabled, a resources is available in Managed Domains at 'https://domain/.httpd/certificate-status' that returns a JSON document list key properties of the current and of a renewed certificate - when available. ### Example ``` { "valid-until": "Thu, 29 Aug 2019 16:06:35 GMT", "valid-from": "Fri, 31 May 2019 16:06:35 GMT", "serial": "03039C464D454EDE79FCD2CAE859F668F269", "sha256-fingerprint": "1ff3bfd2c7c199489ed04df6e29a9b4ea6c015fe8a1b0ce3deb88afc751e352d" "renewal" : { ...renewed cert information... } } ``` MDChallengeDns01 Directive -------------------------- | | | | --- | --- | | Description: | | | Syntax: | ``` MDChallengeDns01 path-to-command ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | Define a program to be called when the `dns-01` challenge needs to be setup/torn down. The program is given the argument `setup` or `teardown` followed by the domain name. For `setup` the challenge content is additionally given. You do not need to specify this, as long as a 'http:' or 'https:' challenge method is possible. However, Let's Encrypt makes 'dns-01' the only challenge available for wildcard certificates. If you require one of those, you need to configure this. See the section about wildcard certificates above for more details. MDContactEmail Directive ------------------------ | | | | --- | --- | | Description: | | | Syntax: | ``` MDContactEmail address ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | The ACME protocol requires you to give a contact url when you sign up. Currently, Let's Encrypt wants an email address (and it will use it to inform you about renewals or changed terms of service). `<mod_md>` uses the `MDContactEmail` directive email in your Apache configuration, so please specify the correct address there. If `MDContactEmail` is not present, `<mod_md>` will use the `[ServerAdmin](core#serveradmin)` directive. MDDriveMode Directive --------------------- | | | | --- | --- | | Description: | former name of MDRenewMode. | | Syntax: | ``` MDDriveMode always|auto|manual ``` | | Default: | ``` MDDriveMode auto ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | This directive exists for backward compatibility as the old name for `[MDRenewMode](#mdrenewmode)`. MDExternalAccountBinding Directive ---------------------------------- | | | | --- | --- | | Description: | | | Syntax: | ``` MDExternalAccountBinding key-id hmac-64 | none | file ``` | | Default: | ``` MDExternalAccountBinding none ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | | Compatibility: | Available in version 2.4.52 and later | Configure values for ACME "External Account Binding", a feature of the ACME standard that allows clients to bind registrations to an existing customer account on ACME servers. Let's Encrypt does not require those, but other ACME CAs do. Check with your ACME CA if you need those and how to obtain the values. They are two strings, a key identifier and a base64 encoded 'hmac' value. You can configure those globally or for a specific MDomain. Since these values allow anyone to register under the same account, it is adivsable to give the configuration file restricted permissions, e.g. root only. The value can also be taken from a JSON file, to keep more open permissions on the server configuration and restrict the ones on that file. The JSON itself is: ### EAB JSON Example file ``` {"kid": "kid-1", "hmac": "zWND..."} ``` If you change EAB values, the new ones will be used when the next certificate renewal is due. MDHttpProxy Directive --------------------- | | | | --- | --- | | Description: | Define a proxy for outgoing connections. | | Syntax: | ``` MDHttpProxy url ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | Use a http proxy to connect to the `[MDCertificateAuthority](#mdcertificateauthority)`. Define this if your webserver can only reach the internet with a forward proxy. MDMember Directive ------------------ | | | | --- | --- | | Description: | Additional hostname for the managed domain. | | Syntax: | ``` MDMember hostname ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | Instead of listing all dns names on the same line, you may use `MDMember` to add such names to a managed domain. ### Example ``` <MDomain example.org> MDMember www.example.org MDMember mail.example.org </MDomain> ``` If you use it in the global context, outside a specific MD, you can only specify one value, 'auto' or 'manual' as the default for all other MDs. See `[MDomain](#mdomain)` for a description of these special values. MDMembers Directive ------------------- | | | | --- | --- | | Description: | Control if the alias domain names are automatically added. | | Syntax: | ``` MDMembers auto|manual ``` | | Default: | ``` MDMembers auto ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | Defines if the `[ServerName](core#servername)` and `[ServerAlias](core#serveralias)` values of a VirtualHost are automatically added to the members of a Managed Domain or not. MDMessageCmd Directive ---------------------- | | | | --- | --- | | Description: | Handle events for Manage Domains | | Syntax: | ``` MDMessageCmd path-to-cmd optional-args ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | This command gets called when one of the following events happen for a Managed Domain: "renewed", "installed", "expiring", "errored". The command may be invoked for more than these in the future and ignore events it is not prepared to handle. This is the more flexible companion to `[MDNotifyCmd](#mdnotifycmd)`. ### Example ``` MDMessageCmd /etc/apache/md-message ``` ``` # will be invoked when a new certificate for mydomain.org is available as: /etc/apache/md-message renewed mydomain.com ``` The program should not block, as the module will wait for it to finish. A return code other than 0 is regarded as an error. 'errored' is no immediate cause for concern since renewal is attempted early enough to allow the internet to come back. This is reported at most once per hour. 'expiring' should be taken serious. It is issued when the `[MDWarnWindow](#mdwarnwindow)` is reached. By default this is 10% of the certificate lifetime, so for Let's Encrypt this currently means 9 days before it expires. The warning is repeated at most once a day. 'renewed' means that a new certificate has been obtained and is stored in the 'staging' area in the MD store. It will be activated on the next server restart/reload. 'installed' is triggered when a new certificate has been transferred from staging into the domains location in MD store. This happens at server startup/reload. Different to all other invocations, `MDMessageCmd` is run with root permissions (on \*nix systems) and has access to the certificate files (and keys). Certificates needed for other applications or in different formats can be processed on this event. 'renewing' event is triggered before starting renew process for the managed domain. Should the command return != 0 for this reason, renew will be aborted and repeated on next cycle. Some cluster setups use this to allow renewals to run only on a single node. 'challenge-setup:type:domain' event is triggered when the challenge data for a domain has been created. This is invoked before the ACME server is told to check for it. The type is one of the ACME challenge types. This is invoked for every DNS name in a MDomain. Cluster setups may use this event to distribute challenge files to all nodes in a cluster. ocsp-errored happens when MDStapling is enabled for a domain, this indicates that an error was encountered retrieving the OCSP response from the Certificate Authority. mod\_md will continue trying. MDMustStaple Directive ---------------------- | | | | --- | --- | | Description: | Control if new certificates carry the OCSP Must Staple flag. | | Syntax: | ``` MDMustStaple on|off ``` | | Default: | ``` MDMustStaple off ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | Defines if newly requested certificate should have the OCSP Must Staple flag set or not. If a certificate has this flag, the server is required to send a OCSP stapling response to every client. This only works if you configure `<mod_ssl>` to generate this (see `[SSLUseStapling](mod_ssl#sslusestapling)` and friends). MDNotifyCmd Directive --------------------- | | | | --- | --- | | Description: | Run a program when a Managed Domain is ready. | | Syntax: | ``` MDNotifyCmd path [ args ] ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | The configured executable is run when a Managed Domain has signed up or renewed its certificate. It is given the name of the processed MD as additional arguments (after the parameters specified here). It should return status code 0 to indicate that it has run successfully. MDomain Directive ----------------- | | | | --- | --- | | Description: | Define list of domain names that belong to one group. | | Syntax: | ``` MDomain dns-name [ other-dns-name... ] [auto|manual] ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | All the names in the list are managed as one Managed Domain (MD). mod\_md will request one single certificate that is valid for all these names. This directive uses the global settings (see other MD directives below). If you need specific settings for one MD, use the `[<MDomainSet>](#mdomainset)`. There are 2 additional settings that are necessary for a Managed Domain: a contact Email address (via `[MDContactEmail](#mdcontactemail)` or `[ServerAdmin](core#serveradmin)`) and `[MDCertificateAgreement](#mdcertificateagreement)`. The mail address of `[ServerAdmin](core#serveradmin)` is used to register at the CA (Let's Encrypt by default). The CA may use it to notify you about changes in its service or status of your certificates. The second setting, `[MDCertificateAgreement](#mdcertificateagreement)`, should have the value "accepted". By specifying this, you confirm that your accept the Terms of Service of the CA. ### Example ``` MDContactEmail [email protected] MDCertificateAgreement accepted MDomain example.org www.example.org <VirtualHost *:443> ServerName example.org DocumentRoot htdocs/root SSLEngine on </VirtualHost> <VirtualHost *:443> ServerName www.example.org DocumentRoot htdocs/www SSLEngine on </VirtualHost> ``` There are two special names that you may use in this directive: 'manual' and 'auto'. This determines if a Managed Domain shall have exactly the name list as is configured ('manual') or offer more convenience. With 'auto' all names of a virtual host are added to a MD. Conveniently, 'auto' is also the default. ### Example ``` MDomain example.org <VirtualHost *:443> ServerName example.org ServerAlias www.example.org DocumentRoot htdocs/root SSLEngine on </VirtualHost> MDomain example2.org auto <VirtualHost *:443> ServerName example2.org ServerAlias www.example2.org ... </VirtualHost> ``` In this example, the domain 'www.example.org' is automatically added to the MD 'example.org'. Similarly for 'example2.org' where 'auto' is configured explicitly. Whenever you add more ServerAlias names to this virtual host, they will be added as well to the Managed Domain. If you prefer to explicitly declare all the domain names, use 'manual' mode. An error will be logged if the names do not match with the expected ones. <MDomainSet> Directive ---------------------- | | | | --- | --- | | Description: | Container for directives applied to the same managed domains. | | Syntax: | ``` <MDomainSet dns-name [ other-dns-name... ]>...</MDomainSet> ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | This is the directive `[MDomain](#mdomain)` with the added possibility to add setting just for this MD. In fact, you may also use "<MDomain ..>" as a shortcut. This allows you to configure an MD that uses another Certificate Authority, have other renewal requirements, etc. ### Example ``` <MDomain sandbox.example.org> MDCertificateAuthority https://someotherca.com/ACME </MDomain> ``` A common use case is to configure https: requirements separately for your domains. ### Example ``` <MDomain example.org> MDRequireHttps temporary </MDomain> ``` MDPortMap Directive ------------------- | | | | --- | --- | | Description: | Map external to internal ports for domain ownership verification. | | Syntax: | ``` MDPortMap map1 [ map2 ] ``` | | Default: | ``` MDPortMap http:80 https:443 ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | The ACME protocol provides two methods to verify domain ownership via HTTP: one that uses 'http:' urls (port 80) and one for 'https:' urls (port 443). If your server is not reachable by at least one of the two, ACME may only work by configuring your DNS server, see `[MDChallengeDns01](#mdchallengedns01)`. On most public facing servers, 'http:' arrives on port 80 and 'https:' on port 443. The module checks the ports your Apache server is listening on and assumes those are available. This means that when your server does not listen on port 80, it assumes that 'http:' requests from the internet will not work. This is a good guess, but it may be wrong. For example, your Apache might listen to port 80, but your firewall might block it. 'http:' is only available in your intranet. So, the module will falsely assume that Let's Encrypt can use 'http:' challenges with your server. This will then fail, because your firewall will drop those. ### Example ``` MDPortMap http:- https:8433 ``` The above example shows how you can specify that 'http:' requests from the internet will never arrive. In addition it says that 'https:' requests will arrive on local port 8433. This is necessary if you have port forwarding in place, your server may be reachable from the Internet on port 443, but the local port that httpd uses is another one. Your server might only listen on ports 8443 and 8000, but be reached on ports 443 and 80 (from the internet). MDPrivateKeys Directive ----------------------- | | | | --- | --- | | Description: | Set type and size of the private keys generated. | | Syntax: | ``` MDPrivateKeys type [ params... ] ``` | | Default: | ``` MDPrivateKeys RSA 2048 ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | Defines what kind of private keys are generated for a managed domain and with what parameters. You can have more than one private key type configured and the module will obtain a certificate for each key. For example, you may configure an RSA and an Elliptic Curve (EC) key, so that 2 certicates are created for a domain. On a client connection, the first one supported by the client will then be used. Since EC keys and certificates are smaller, you might want to offer them first for all compatible (modern) clients. This can enable faster handshakes. Add an RSA key type to support older clients. ### Example ``` MDPrivateKeys secp256r1 rsa3072 ``` The EC types supported depend on the CA you use. For Let's encrypt the supported curves include 'secp256r1' and 'secp384r1'. Each key and certificate type is stored in its own file in the MD store. The key type is part of the file name with some backward compatible naming for RSA certificates. So you may continue sharing these files with other applications. Please note that this setting only has an effect on new keys. Any existing private key you have remains unaffected. Also, this only affects private keys generated for certificates. ACME account keys are unaffected by this. MDRenewMode Directive --------------------- | | | | --- | --- | | Description: | Controls if certificates shall be renewed. | | Syntax: | ``` MDRenewMode always|auto|manual ``` | | Default: | ``` MDRenewMode auto ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | In the default 'auto' mode, the module will do what makes most sense of each Managed Domain. For a domain without any certificates, it will obtain them from the Certificate Authority. However, if you have defined an MD that is not used by any of Apache's VirtualHosts, it will not bother. And for MDs with static certificate files (see `[MDCertificateFile](#mdcertificatefile)`), it assumes that you have your own source, and will not renew them either. You can override this default in either way. If you specify 'always', the module will renew certificates for an MD, regardless if the domains are in use or if there are static files. For the opposite effect, configure 'manual' and no renewal will be attempted. MDRenewWindow Directive ----------------------- | | | | --- | --- | | Description: | Control when a certificate will be renewed. | | Syntax: | ``` MDRenewWindow duration ``` | | Default: | ``` MDRenewWindow 33% ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | If the validity of the certificate falls below duration, mod\_md will get a new signed certificate. Normally, certificates are valid for around 90 days and mod\_md will renew them the earliest 33% of their complete lifetime before they expire (so for 90 days validity, 30 days before it expires). If you think this is not what you need, you can specify either the exact time, as in: ### Example ``` # 21 days before expiry MDRenewWindow 21d # 30 seconds (might be close) MDRenewWindow 30s # 10% of the cert lifetime MDRenewWindow 10% ``` When in auto drive mode, the module will check every 12 hours at least what the status of the managed domains is and if it needs to do something. On errors, for example when the CA is unreachable, it will initially retry after some seconds. Should that continue to fail, it will back off to a maximum interval of hourly checks. MDRequireHttps Directive ------------------------ | | | | --- | --- | | Description: | Redirects http: traffic to https: for Managed Domains. | | Syntax: | ``` MDRequireHttps off|temporary|permanent ``` | | Default: | ``` MDRequireHttps off ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | This is a convenience directive to ease http: to https: migration of your Managed Domains. With: ### Example ``` MDRequireHttps temporary ``` you announce that you want all traffic via http: URLs to be redirected to the https: ones, for now. This is safe and you can remove this again at any time. **The following has consequences:** if you want client to **no longer** use the http: URLs, configure: ### Permanent (for at least half a year!) ``` MDRequireHttps permanent ``` This does two things: 1. All request to the `http:` resources are redirected to the same url with the `https:` scheme using the `301` status code. This tells clients that this is intended to be forever and the should update any links they have accordingly. 2. All answers to `https:` requests will carry the header `Strict-Transport-Security` with a life time of half a year. This tells the browser that it **never** (for half a year) shall use `http:` when talking to this domain name. Browsers will, after having seen this, refuse to contact your unencrypted site. This prevents malicious middleware to downgrade connections and listen/manipulate the traffic. Which is good. But you cannot simply take it back again. You can achieve the same with `<mod_alias>` and some `[Redirect](mod_alias#redirect)` configuration, basically. If you do it yourself, please make sure to exclude the paths /.well-known/\* from your redirection, otherwise mod\_md might have trouble signing on new certificates. If you set this globally, it applies to all managed domains. If you want it for a specific domain only, use: ### Example ``` <MDomain xxx.yyy> MDRequireHttps temporary </MDomain> ``` MDServerStatus Directive ------------------------ | | | | --- | --- | | Description: | Control if Managed Domain information is added to server-status. | | Syntax: | ``` MDServerStatus on|off ``` | | Default: | ``` MDServerStatus on ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | Apaches 'server-status' handler allows you configure a resource to monitor what is going on. This includes now a section listing all Managed Domains with the DNS names, renewal status, lifetimes and main properties. You can switch that off using this directive. MDStapleOthers Directive ------------------------ | | | | --- | --- | | Description: | Enable stapling for certificates not managed by mod\_md. | | Syntax: | ``` MDStapleOthers on|off ``` | | Default: | ``` MDStapleOthers on ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | | Compatibility: | Available in version 2.4.42 and later | This setting only takes effect when `[MDStapling](#mdstapling)` is enabled. It controls if `<mod_md>` should also provide stapling information for certificates that are not directly controlled by it, e.g. renewed via an ACME CA. MDStapling Directive -------------------- | | | | --- | --- | | Description: | Enable stapling for all or a particular MDomain. | | Syntax: | ``` MDStapling on|off ``` | | Default: | ``` MDStapling off ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | | Compatibility: | Available in version 2.4.42 and later | `<mod_md>` offers an implementation for providing OCSP stapling information. This is an alternative to the one provided by `<mod_ssl>`. For backward compatibility, this is disabled by default. The stapling can be switched on for all certificates on the server or for an individual `[MDomain](#mdomain)`. This will replace any stapling configuration in `<mod_ssl>` for these hosts. When disabled, the `<mod_ssl>` stapling will do the work (if it is itself enabled, of course). This allows for a gradual shift over from one implementation to the other. The stapling of `<mod_md>` will also work for domains where the certificates are not managed by this module (see `[MDStapleOthers](#mdstapleothers)` for how to control this). This allows use of the new stapling without using any ACME certificate management. MDStaplingKeepResponse Directive -------------------------------- | | | | --- | --- | | Description: | Controls when old responses should be removed. | | Syntax: | ``` MDStaplingKeepResponse duration ``` | | Default: | ``` MDStaplingKeepResponse 7d ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | | Compatibility: | Available in version 2.4.42 and later | This time window specifies when OCSP response data used in stapling shall be removed from the store again. Response information older than 7 days (default) is deleted on server restart/reload. This keeps the store from growing when certificates are renewed/reconfigured frequently. MDStaplingRenewWindow Directive ------------------------------- | | | | --- | --- | | Description: | Control when the stapling responses will be renewed. | | Syntax: | ``` MDStaplingRenewWindow duration ``` | | Default: | ``` MDStaplingRenewWindow 33% ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | | Compatibility: | Available in version 2.4.42 and later | If the validity of the OCSP response used in stapling falls below duration, `<mod_md>` will obtain a new OCSP response. The CA issuing a certificate commonly also operates the OCSP responder service and determines how long its signed response about the validity of a certificate are itself valid. The longer a response is valid, the longer it can be cached which mean better overall performance for everyone. The shorter the life time, the more rapidly certificate revocations spread to clients. Also, service reliability is a consideration. By adjusting the stapling renew window you can control parts of this yourself. If you make the renew time short (e.g. a short time before the current information expires), you gain maximum cache time. But a service outage (down for maintenance, for example) will affect you. If you renew a long time before expiry, updates will be made more frequent, cause more load on the CA server infrastructure and also more coordination between the child processes of your server. The default is chosen as 33%, which means renewal is started when only a third of the response lifetime is left. For a CA that issues OCSP responses with lifetime of 3 days, this means 2 days of caching and 1 day for renewal attempts. A service outage would have to last full 24 hours to affect your domains. Setting an absolute renew window, like `2d` (2 days), is also possible. MDStoreDir Directive -------------------- | | | | --- | --- | | Description: | Path on the local file system to store the Managed Domains data. | | Syntax: | ``` MDStoreDir path ``` | | Default: | ``` MDStoreDir md ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | Defines where on the local file system the Managed Domain data is stored. This is an absolute path or interpreted relative to the server root. The default will create a directory 'md' in your server root. If you move this and have already data, be sure to move/copy the data first to the new location, reconfigure and then restart the server. If you reconfigure and restart first, the server will try to get new certificates that it thinks are missing. MDWarnWindow Directive ---------------------- | | | | --- | --- | | Description: | Define the time window when you want to be warned about an expiring certificate. | | Syntax: | ``` MDWarnWindow duration ``` | | Default: | ``` MDWarnWindow 10% ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_md | See `[MDRenewWindow](#mdrenewwindow)` for a description on how you can specify the time. The modules checks the remaining lifetime of certificates and invokes `[MDMessageCmd](#mdmessagecmd)` when there is less than the warn window left. With the default, this mean 9 days for certificates from Let's Encrypt. It also applies to Managed Domains with static certificate files ( see `[MDCertificateFile](#mdcertificatefile)`).
programming_docs
apache_http_server Apache Module mod_proxy_uwsgi Apache Module mod\_proxy\_uwsgi =============================== | | | | --- | --- | | Description: | UWSGI gateway module for `<mod_proxy>` | | Status: | Extension | | Module Identifier: | proxy\_uwsgi\_module | | Source File: | mod\_proxy\_uwsgi.c | | Compatibility: | Available in version 2.4.30 and later | ### Summary This module *requires* the service of `<mod_proxy>`. It provides support for the [UWSGI protocol](http://uwsgi-docs.readthedocs.io/en/latest/index.html). Thus, in order to get the ability of handling the UWSGI protocol, `<mod_proxy>` and `<mod_proxy_uwsgi>` have to be present in the server. **Warning** Do not enable proxying until you have [secured your server](mod_proxy#access). Open proxy servers are dangerous both to your network and to the Internet at large. Examples -------- Remember, in order to make the following examples work, you have to enable `<mod_proxy>` and `<mod_proxy_uwsgi>`. ### Simple gateway ``` ProxyPass "/uwsgi-bin/" "uwsgi://localhost:4000/" ``` The balanced gateway needs `<mod_proxy_balancer>` and at least one load balancer algorithm module, such as `<mod_lbmethod_byrequests>`, in addition to the proxy modules listed above. `<mod_lbmethod_byrequests>` is the default, and will be used for this example configuration. ### Balanced gateway ``` ProxyPass "/uwsgi-bin/" "balancer://somecluster/" <Proxy balancer://somecluster> BalancerMember uwsgi://localhost:4000 BalancerMember uwsgi://localhost:4001 </Proxy> ``` apache_http_server Apache Module mod_xml2enc Apache Module mod\_xml2enc ========================== | | | | --- | --- | | Description: | Enhanced charset/internationalisation support for libxml2-based filter modules | | Status: | Base | | Module Identifier: | xml2enc\_module | | Source File: | mod\_xml2enc.c | | Compatibility: | Version 2.4 and later. Available as a third-party module for 2.2.x versions | ### Summary This module provides enhanced internationalisation support for markup-aware filter modules such as `<mod_proxy_html>`. It can automatically detect the encoding of input data and ensure they are correctly processed by the [libxml2](http://xmlsoft.org/) parser, including converting to Unicode (UTF-8) where necessary. It can also convert data to an encoding of choice after markup processing, and will ensure the correct charset value is set in the HTTP Content-Type header. Usage ----- There are two usage scenarios: with modules programmed to work with mod\_xml2enc, and with those that are not aware of it: Filter modules enabled for mod\_xml2enc Modules such as `<mod_proxy_html>` version 3.1 and up use the `xml2enc_charset` optional function to retrieve the charset argument to pass to the libxml2 parser, and may use the `xml2enc_filter` optional function to postprocess to another encoding. Using mod\_xml2enc with an enabled module, no configuration is necessary: the other module will configure mod\_xml2enc for you (though you may still want to customise it using the configuration directives below). Non-enabled modules To use it with a libxml2-based module that isn't explicitly enabled for mod\_xml2enc, you will have to configure the filter chain yourself. So to use it with a filter **foo** provided by a module **mod\_foo** to improve the latter's i18n support with HTML and XML, you could use ``` FilterProvider iconv xml2enc Content-Type $text/html FilterProvider iconv xml2enc Content-Type $xml FilterProvider markup foo Content-Type $text/html FilterProvider markup foo Content-Type $xml FilterChain iconv markup ``` **mod\_foo** will now support any character set supported by either (or both) of libxml2 or apr\_xlate/iconv. Programming API --------------- Programmers writing libxml2-based filter modules are encouraged to enable them for mod\_xml2enc, to provide strong i18n support for your users without reinventing the wheel. The programming API is exposed in mod\_xml2enc.h, and a usage example is `<mod_proxy_html>`. Detecting an Encoding --------------------- Unlike `<mod_charset_lite>`, mod\_xml2enc is designed to work with data whose encoding cannot be known in advance and thus configured. It therefore uses 'sniffing' techniques to detect the encoding of HTTP data as follows: 1. If the HTTP Content-Type header includes a charset parameter, that is used. 2. If the data start with an XML Byte Order Mark (BOM) or an XML encoding declaration, that is used. 3. If an encoding is declared in an HTML `<META>` element, that is used. 4. If none of the above match, the default value set by `xml2EncDefault` is used. The rules are applied in order. As soon as a match is found, it is used and detection is stopped. Output Encoding --------------- [libxml2](http://xmlsoft.org/) always uses UTF-8 (Unicode) internally, and libxml2-based filter modules will output that by default. mod\_xml2enc can change the output encoding through the API, but there is currently no way to configure that directly. Changing the output encoding should (in theory, at least) never be necessary, and is not recommended due to the extra processing load on the server of an unnecessary conversion. Unsupported Encodings --------------------- If you are working with encodings that are not supported by any of the conversion methods available on your platform, you can still alias them to a supported encoding using `xml2EncAlias`. xml2EncAlias Directive ---------------------- | | | | --- | --- | | Description: | Recognise Aliases for encoding values | | Syntax: | ``` xml2EncAlias charset alias [alias ...] ``` | | Context: | server config | | Status: | Base | | Module: | mod\_xml2enc | This server-wide directive aliases one or more encoding to another encoding. This enables encodings not recognised by libxml2 to be handled internally by libxml2's encoding support using the translation table for a recognised encoding. This serves two purposes: to support character sets (or names) not recognised either by libxml2 or iconv, and to skip conversion for an encoding where it is known to be unnecessary. xml2EncDefault Directive ------------------------ | | | | --- | --- | | Description: | Sets a default encoding to assume when absolutely no information can be [automatically detected](#sniffing) | | Syntax: | ``` xml2EncDefault name ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Base | | Module: | mod\_xml2enc | If you are processing data with known encoding but no encoding information, you can set this default to help mod\_xml2enc process the data correctly. For example, to work with the default value of Latin1 (iso-8859-1) specified in HTTP/1.0, use: ``` xml2EncDefault iso-8859-1 ``` xml2StartParse Directive ------------------------ | | | | --- | --- | | Description: | Advise the parser to skip leading junk. | | Syntax: | ``` xml2StartParse element [element ...] ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Base | | Module: | mod\_xml2enc | Specify that the markup parser should start at the first instance of any of the elements specified. This can be used as a workaround where a broken backend inserts leading junk that messes up the parser ([example here](http://bahumbug.wordpress.com/2006/10/12/mod_proxy_html-revisited/)). It should never be used for XML, nor well-formed HTML. apache_http_server Apache Module mod_socache_dc Apache Module mod\_socache\_dc ============================== | | | | --- | --- | | Description: | Distcache based shared object cache provider. | | Status: | Extension | | Module Identifier: | socache\_dc\_module | | Source File: | mod\_socache\_dc.c | ### Summary `<mod_socache_dc>` is a shared object cache provider which provides for creation and access to a cache backed by the [distcache](http://distcache.sourceforge.net/) distributed session caching libraries. Details of other shared object cache providers can be found [here](../socache). apache_http_server Apache Module mod_privileges Apache Module mod\_privileges ============================= | | | | --- | --- | | Description: | Support for Solaris privileges and for running virtual hosts under different user IDs. | | Status: | Experimental | | Module Identifier: | privileges\_module | | Source File: | mod\_privileges.c | | Compatibility: | Available in Apache 2.3 and up, on Solaris 10 and OpenSolaris platforms | ### Summary This module enables different Virtual Hosts to run with different Unix User and Group IDs, and with different [Solaris Privileges](http://sosc-dr.sun.com/bigadmin/features/articles/least_privilege.jsp). In particular, it offers a solution to the problem of privilege separation between different Virtual Hosts, first promised by the abandoned perchild MPM. It also offers other security enhancements. Unlike perchild, `<mod_privileges>` is not itself an MPM. It works *within* a processing model to set privileges and User/Group *per request* in a running process. It is therefore not compatible with a threaded MPM, and will refuse to run under one. `<mod_privileges>` raises security issues similar to those of [suexec](../suexec). But unlike suexec, it applies not only to CGI programs but to the entire request processing cycle, including in-process applications and subprocesses. It is ideally suited to running PHP applications under **mod\_php**, which is also incompatible with threaded MPMs. It is also well-suited to other in-process scripting applications such as **mod\_perl**, **mod\_python**, and **mod\_ruby**, and to applications implemented in C as apache modules where privilege separation is an issue. Security Considerations ----------------------- `<mod_privileges>` introduces new security concerns in situations where **untrusted code** may be run **within the webserver process**. This applies to untrusted modules, and scripts running under modules such as mod\_php or mod\_perl. Scripts running externally (e.g. as CGI or in an appserver behind mod\_proxy or mod\_jk) are NOT affected. The basic security concerns with mod\_privileges are: * Running as a system user introduces the same security issues as mod\_suexec, and near-equivalents such as cgiwrap and suphp. * A privileges-aware malicious user extension (module or script) could escalate its privileges to anything available to the httpd process in any virtual host. This introduces new risks if (and only if) mod\_privileges is compiled with the BIG\_SECURITY\_HOLE option. * A privileges-aware malicious user extension (module or script) could escalate privileges to set its user ID to another system user (and/or group). The `PrivilegesMode` directive allows you to select either FAST or SECURE mode. You can mix modes, using FAST mode for trusted users and fully-audited code paths, while imposing SECURE mode where an untrusted user has scope to introduce code. Before describing the modes, we should also introduce the target use cases: Benign vs Hostile. In a benign situation, you want to separate users for their convenience, and protect them and the server against the risks posed by honest mistakes, but you trust your users are not deliberately subverting system security. In a hostile situation - e.g. commercial hosting - you may have users deliberately attacking the system or each other. FAST mode In FAST mode, requests are run in-process with the selected uid/gid and privileges, so the overhead is negligible. This is suitable for benign situations, but is not secure against an attacker escalating privileges with an in-process module or script. SECURE mode A request in SECURE mode forks a subprocess, which then drops privileges. This is a very similar case to running CGI with suexec, but for the entire request cycle, and with the benefit of fine-grained control of privileges. You can select different `PrivilegesMode`s for each virtual host, and even in a directory context within a virtual host. FAST mode is appropriate where the user(s) are trusted and/or have no privilege to load in-process code. SECURE mode is appropriate to cases where untrusted code might be run in-process. However, even in SECURE mode, there is no protection against a malicious user who is able to introduce privileges-aware code running *before the start of the request-processing cycle.* DTracePrivileges Directive -------------------------- | | | | --- | --- | | Description: | Determines whether the privileges required by dtrace are enabled. | | Syntax: | ``` DTracePrivileges On|Off ``` | | Default: | ``` DTracePrivileges Off ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_privileges | | Compatibility: | Available on Solaris 10 and OpenSolaris with non-threaded MPMs (`<prefork>` or custom MPM). | This server-wide directive determines whether Apache will run with the [privileges](http://sosc-dr.sun.com/bigadmin/features/articles/least_privilege.jsp) required to run [dtrace](http://sosc-dr.sun.com/bigadmin/content/dtrace/). Note that DTracePrivileges On will not in itself activate DTrace, but DTracePrivileges Off will prevent it working. PrivilegesMode Directive ------------------------ | | | | --- | --- | | Description: | Trade off processing speed and efficiency vs security against malicious privileges-aware code. | | Syntax: | ``` PrivilegesMode FAST|SECURE|SELECTIVE ``` | | Default: | ``` PrivilegesMode FAST ``` | | Context: | server config, virtual host, directory | | Status: | Experimental | | Module: | mod\_privileges | | Compatibility: | Available on Solaris 10 and OpenSolaris with non-threaded MPMs (`<prefork>` or custom MPM). | This directive trades off performance vs security against malicious, privileges-aware code. In SECURE mode, each request runs in a secure subprocess, incurring a substantial performance penalty. In FAST mode, the server is not protected against escalation of privileges as discussed above. This directive differs slightly between a `<Directory>` context (including equivalents such as Location/Files/If) and a top-level or `<VirtualHost>`. At top-level, it sets a default that will be inherited by virtualhosts. In a virtual host, FAST or SECURE mode acts on the entire HTTP request, and any settings in a `<Directory>` context will be **ignored**. A third pseudo-mode SELECTIVE defers the choice of FAST vs SECURE to directives in a `<Directory>` context. In a `<Directory>` context, it is applicable only where SELECTIVE mode was set for the VirtualHost. Only FAST or SECURE can be set in this context (SELECTIVE would be meaningless). **Warning** Where SELECTIVE mode is selected for a virtual host, the activation of privileges must be deferred until *after* the mapping phase of request processing has determined what `<Directory>` context applies to the request. This might give an attacker opportunities to introduce code through a `[RewriteMap](mod_rewrite#rewritemap)` running at top-level or `<VirtualHost>` context *before* privileges have been dropped and userid/gid set. VHostCGIMode Directive ---------------------- | | | | --- | --- | | Description: | Determines whether the virtualhost can run subprocesses, and the privileges available to subprocesses. | | Syntax: | ``` VHostCGIMode On|Off|Secure ``` | | Default: | ``` VHostCGIMode On ``` | | Context: | virtual host | | Status: | Experimental | | Module: | mod\_privileges | | Compatibility: | Available on Solaris 10 and OpenSolaris with non-threaded MPMs (`<prefork>` or custom MPM). | Determines whether the virtual host is allowed to run fork and exec, the [privileges](http://sosc-dr.sun.com/bigadmin/features/articles/least_privilege.jsp) required to run subprocesses. If this is set to Off the virtualhost is denied the privileges and will not be able to run traditional CGI programs or scripts under the traditional `<mod_cgi>`, nor similar external programs such as those created by `<mod_ext_filter>` or `[RewriteMap](mod_rewrite#rewritemap)` prog. Note that it does not prevent CGI programs running under alternative process and security models such as [mod\_fcgid](https://httpd.apache.org/mod_fcgid/), which is a recommended solution in Solaris. If set to On or Secure, the virtual host is permitted to run external programs and scripts as above. Setting `VHostCGIMode` Secure has the effect of denying privileges to the subprocesses, as described for `VHostSecure`. VHostCGIPrivs Directive ----------------------- | | | | --- | --- | | Description: | Assign arbitrary privileges to subprocesses created by a virtual host. | | Syntax: | ``` VHostCGIPrivs [+-]?privilege-name [[+-]?privilege-name] ... ``` | | Default: | `None` | | Context: | virtual host | | Status: | Experimental | | Module: | mod\_privileges | | Compatibility: | Available on Solaris 10 and OpenSolaris with non-threaded MPMs (`<prefork>` or custom MPM) and when `<mod_privileges>` is compiled with the BIG\_SECURITY\_HOLE compile-time option. | `VHostCGIPrivs` can be used to assign arbitrary [privileges](http://sosc-dr.sun.com/bigadmin/features/articles/least_privilege.jsp) to subprocesses created by a virtual host, as discussed under `VHostCGIMode`. Each privilege-name is the name of a Solaris privilege, such as file\_setid or sys\_nfs. A privilege-name may optionally be prefixed by + or -, which will respectively allow or deny a privilege. If used with neither + nor -, all privileges otherwise assigned to the virtualhost will be denied. You can use this to override any of the default sets and construct your own privilege set. **Security** This directive can open huge security holes in apache subprocesses, up to and including running them with root-level powers. Do not use it unless you fully understand what you are doing! VHostGroup Directive -------------------- | | | | --- | --- | | Description: | Sets the Group ID under which a virtual host runs. | | Syntax: | ``` VHostGroup unix-groupid ``` | | Default: | ``` Inherits the group id specified in Group ``` | | Context: | virtual host | | Status: | Experimental | | Module: | mod\_privileges | | Compatibility: | Available on Solaris 10 and OpenSolaris with non-threaded MPMs (`<prefork>` or custom MPM). | The `VHostGroup` directive sets the Unix group under which the server will process requests to a virtualhost. The group is set before the request is processed and reset afterwards using [Solaris Privileges](http://sosc-dr.sun.com/bigadmin/features/articles/least_privilege.jsp). Since the setting applies to the *process*, this is not compatible with threaded MPMs. Unix-group is one of: A group name Refers to the given group by name. `#` followed by a group number. Refers to a group by its number. **Security** This directive cannot be used to run apache as root! Nevertheless, it opens potential security issues similar to those discussed in the [suexec](../suexec) documentation. ### See also * `[Group](mod_unixd#group)` * `[SuexecUserGroup](mod_suexec#suexecusergroup)` VHostPrivs Directive -------------------- | | | | --- | --- | | Description: | Assign arbitrary privileges to a virtual host. | | Syntax: | ``` VHostPrivs [+-]?privilege-name [[+-]?privilege-name] ... ``` | | Default: | `None` | | Context: | virtual host | | Status: | Experimental | | Module: | mod\_privileges | | Compatibility: | Available on Solaris 10 and OpenSolaris with non-threaded MPMs (`<prefork>` or custom MPM) and when `<mod_privileges>` is compiled with the BIG\_SECURITY\_HOLE compile-time option. | `VHostPrivs` can be used to assign arbitrary [privileges](http://sosc-dr.sun.com/bigadmin/features/articles/least_privilege.jsp) to a virtual host. Each privilege-name is the name of a Solaris privilege, such as file\_setid or sys\_nfs. A privilege-name may optionally be prefixed by + or -, which will respectively allow or deny a privilege. If used with neither + nor -, all privileges otherwise assigned to the virtualhost will be denied. You can use this to override any of the default sets and construct your own privilege set. **Security** This directive can open huge security holes in apache, up to and including running requests with root-level powers. Do not use it unless you fully understand what you are doing! VHostSecure Directive --------------------- | | | | --- | --- | | Description: | Determines whether the server runs with enhanced security for the virtualhost. | | Syntax: | ``` VHostSecure On|Off ``` | | Default: | ``` VHostSecure On ``` | | Context: | virtual host | | Status: | Experimental | | Module: | mod\_privileges | | Compatibility: | Available on Solaris 10 and OpenSolaris with non-threaded MPMs (`<prefork>` or custom MPM). | Determines whether the virtual host processes requests with security enhanced by removal of [Privileges](http://sosc-dr.sun.com/bigadmin/features/articles/least_privilege.jsp) that are rarely needed in a webserver, but which are available by default to a normal Unix user and may therefore be required by modules and applications. It is recommended that you retain the default (On) unless it prevents an application running. Since the setting applies to the *process*, this is not compatible with threaded MPMs. **Note** If `VHostSecure` prevents an application running, this may be a warning sign that the application should be reviewed for security. VHostUser Directive ------------------- | | | | --- | --- | | Description: | Sets the User ID under which a virtual host runs. | | Syntax: | ``` VHostUser unix-userid ``` | | Default: | ``` Inherits the userid specified in User ``` | | Context: | virtual host | | Status: | Experimental | | Module: | mod\_privileges | | Compatibility: | Available on Solaris 10 and OpenSolaris with non-threaded MPMs (`<prefork>` or custom MPM). | The `VHostUser` directive sets the Unix userid under which the server will process requests to a virtualhost. The userid is set before the request is processed and reset afterwards using [Solaris Privileges](http://sosc-dr.sun.com/bigadmin/features/articles/least_privilege.jsp). Since the setting applies to the *process*, this is not compatible with threaded MPMs. Unix-userid is one of: A username Refers to the given user by name. `#` followed by a user number. Refers to a user by its number. **Security** This directive cannot be used to run apache as root! Nevertheless, it opens potential security issues similar to those discussed in the [suexec](../suexec) documentation. ### See also * `[User](mod_unixd#user)` * `[SuexecUserGroup](mod_suexec#suexecusergroup)`
programming_docs
apache_http_server Apache Module mod_proxy_ajp Apache Module mod\_proxy\_ajp ============================= | | | | --- | --- | | Description: | AJP support module for `<mod_proxy>` | | Status: | Extension | | Module Identifier: | proxy\_ajp\_module | | Source File: | mod\_proxy\_ajp.c | | Compatibility: | Available in version 2.1 and later | ### Summary This module *requires* the service of `<mod_proxy>`. It provides support for the `Apache JServ Protocol version 1.3` (hereafter *AJP13*). Thus, in order to get the ability of handling `AJP13` protocol, `<mod_proxy>` and `<mod_proxy_ajp>` have to be present in the server. **Warning** Do not enable proxying until you have [secured your server](mod_proxy#access). Open proxy servers are dangerous both to your network and to the Internet at large. Usage ----- This module is used to reverse proxy to a backend application server (e.g. Apache Tomcat) using the AJP13 protocol. The usage is similar to an HTTP reverse proxy, but uses the `ajp://` prefix: ### Simple Reverse Proxy ``` ProxyPass "/app" "ajp://backend.example.com:8009/app" ``` Options such as the `secret` option of Tomcat (required by default since Tomcat 8.5.51 and 9.0.31) can just be added as a separate parameter at the end of `[ProxyPass](mod_proxy#proxypass)` or `[BalancerMember](mod_proxy#balancermember)`. This parameter is available in Apache HTTP Server 2.4.42 and later: ### Simple Reverse Proxy with `secret` option ``` ProxyPass "/app" "ajp://backend.example.com:8009/app" secret=YOUR_AJP_SECRET ``` Balancers may also be used: ### Balancer Reverse Proxy ``` <Proxy "balancer://cluster"> BalancerMember "ajp://app1.example.com:8009" loadfactor=1 BalancerMember "ajp://app2.example.com:8009" loadfactor=2 ProxySet lbmethod=bytraffic </Proxy> ProxyPass "/app" "balancer://cluster/app" ``` Note that usually no `[ProxyPassReverse](mod_proxy#proxypassreverse)` directive is necessary. The AJP request includes the original host header given to the proxy, and the application server can be expected to generate self-referential headers relative to this host, so no rewriting is necessary. The main exception is when the URL path on the proxy differs from that on the backend. In this case, a redirect header can be rewritten relative to the original host URL (not the backend `ajp://` URL), for example: ### Rewriting Proxied Path ``` ProxyPass "/apps/foo" "ajp://backend.example.com:8009/foo" ProxyPassReverse "/apps/foo" "http://www.example.com/foo" ``` However, it is usually better to deploy the application on the backend server at the same path as the proxy rather than to take this approach. Environment Variables --------------------- Environment variables whose names have the prefix `AJP_` are forwarded to the origin server as AJP request attributes (with the `AJP_` prefix removed from the name of the key). Overview of the protocol ------------------------ The `AJP13` protocol is packet-oriented. A binary format was presumably chosen over the more readable plain text for reasons of performance. The web server communicates with the servlet container over TCP connections. To cut down on the expensive process of socket creation, the web server will attempt to maintain persistent TCP connections to the servlet container, and to reuse a connection for multiple request/response cycles. Once a connection is assigned to a particular request, it will not be used for any others until the request-handling cycle has terminated. In other words, requests are not multiplexed over connections. This makes for much simpler code at either end of the connection, although it does cause more connections to be open at once. Once the web server has opened a connection to the servlet container, the connection can be in one of the following states: * Idle No request is being handled over this connection. * Assigned The connection is handling a specific request. Once a connection is assigned to handle a particular request, the basic request information (e.g. HTTP headers, etc) is sent over the connection in a highly condensed form (e.g. common strings are encoded as integers). Details of that format are below in Request Packet Structure. If there is a body to the request `(content-length > 0)`, that is sent in a separate packet immediately after. At this point, the servlet container is presumably ready to start processing the request. As it does so, it can send the following messages back to the web server: * SEND\_HEADERS Send a set of headers back to the browser. * SEND\_BODY\_CHUNK Send a chunk of body data back to the browser. * GET\_BODY\_CHUNK Get further data from the request if it hasn't all been transferred yet. This is necessary because the packets have a fixed maximum size and arbitrary amounts of data can be included the body of a request (for uploaded files, for example). (Note: this is unrelated to HTTP chunked transfer). * END\_RESPONSE Finish the request-handling cycle. Each message is accompanied by a differently formatted packet of data. See Response Packet Structures below for details. Basic Packet Structure ---------------------- There is a bit of an XDR heritage to this protocol, but it differs in lots of ways (no 4 byte alignment, for example). AJP13 uses network byte order for all data types. There are four data types in the protocol: bytes, booleans, integers and strings. **Byte** A single byte. **Boolean** A single byte, `1 = true`, `0 = false`. Using other non-zero values as true (i.e. C-style) may work in some places, but it won't in others. **Integer** A number in the range of `0 to 2^16 (32768)`. Stored in 2 bytes with the high-order byte first. **String** A variable-sized string (length bounded by 2^16). Encoded with the length packed into two bytes first, followed by the string (including the terminating '\0'). Note that the encoded length does **not** include the trailing '\0' -- it is like `strlen`. This is a touch confusing on the Java side, which is littered with odd autoincrement statements to skip over these terminators. I believe the reason this was done was to allow the C code to be extra efficient when reading strings which the servlet container is sending back -- with the terminating \0 character, the C code can pass around references into a single buffer, without copying. if the \0 was missing, the C code would have to copy things out in order to get its notion of a string. ### Packet Size According to much of the code, the max packet size is `8 * 1024 bytes (8K)`. The actual length of the packet is encoded in the header. ### Packet Headers Packets sent from the server to the container begin with `0x1234`. Packets sent from the container to the server begin with `AB` (that's the ASCII code for A followed by the ASCII code for B). After those first two bytes, there is an integer (encoded as above) with the length of the payload. Although this might suggest that the maximum payload could be as large as 2^16, in fact, the code sets the maximum to be 8K. | *Packet Format (Server->Container)* | | --- | | Byte | 0 | 1 | 2 | 3 | 4...(n+3) | | Contents | 0x12 | 0x34 | Data Length (n) | Data | | *Packet Format (Container->Server)* | | --- | | Byte | 0 | 1 | 2 | 3 | 4...(n+3) | | Contents | A | B | Data Length (n) | Data | For most packets, the first byte of the payload encodes the type of message. The exception is for request body packets sent from the server to the container -- they are sent with a standard packet header (`0x1234` and then length of the packet), but without any prefix code after that. The web server can send the following messages to the servlet container: | | | | | --- | --- | --- | | Code | Type of Packet | Meaning | | 2 | Forward Request | Begin the request-processing cycle with the following data | | 7 | Shutdown | The web server asks the container to shut itself down. | | 8 | Ping | The web server asks the container to take control (secure login phase). | | 10 | CPing | The web server asks the container to respond quickly with a CPong. | | none | Data | Size (2 bytes) and corresponding body data. | To ensure some basic security, the container will only actually do the `Shutdown` if the request comes from the same machine on which it's hosted. The first `Data` packet is send immediately after the `Forward Request` by the web server. The servlet container can send the following types of messages to the webserver: | | | | | --- | --- | --- | | Code | Type of Packet | Meaning | | 3 | Send Body Chunk | Send a chunk of the body from the servlet container to the web server (and presumably, onto the browser). | | 4 | Send Headers | Send the response headers from the servlet container to the web server (and presumably, onto the browser). | | 5 | End Response | Marks the end of the response (and thus the request-handling cycle). | | 6 | Get Body Chunk | Get further data from the request if it hasn't all been transferred yet. | | 9 | CPong Reply | The reply to a CPing request | Each of the above messages has a different internal structure, detailed below. Request Packet Structure ------------------------ For messages from the server to the container of type *Forward Request*: ``` AJP13_FORWARD_REQUEST := prefix_code (byte) 0x02 = JK_AJP13_FORWARD_REQUEST method (byte) protocol (string) req_uri (string) remote_addr (string) remote_host (string) server_name (string) server_port (integer) is_ssl (boolean) num_headers (integer) request_headers *(req_header_name req_header_value) attributes *(attribut_name attribute_value) request_terminator (byte) OxFF ``` The `request_headers` have the following structure: ``` req_header_name := sc_req_header_name | (string) [see below for how this is parsed] sc_req_header_name := 0xA0xx (integer) req_header_value := (string) ``` The `attributes` are optional and have the following structure: ``` attribute_name := sc_a_name | (sc_a_req_attribute string) attribute_value := (string) ``` Not that the all-important header is `content-length`, because it determines whether or not the container looks for another packet immediately. ### Detailed description of the elements of Forward Request ### Request prefix For all requests, this will be 2. See above for details on other Prefix codes. ### Method The HTTP method, encoded as a single byte: | | | | --- | --- | | Command Name | Code | | OPTIONS | 1 | | GET | 2 | | HEAD | 3 | | POST | 4 | | PUT | 5 | | DELETE | 6 | | TRACE | 7 | | PROPFIND | 8 | | PROPPATCH | 9 | | MKCOL | 10 | | COPY | 11 | | MOVE | 12 | | LOCK | 13 | | UNLOCK | 14 | | ACL | 15 | | REPORT | 16 | | VERSION-CONTROL | 17 | | CHECKIN | 18 | | CHECKOUT | 19 | | UNCHECKOUT | 20 | | SEARCH | 21 | | MKWORKSPACE | 22 | | UPDATE | 23 | | LABEL | 24 | | MERGE | 25 | | BASELINE\_CONTROL | 26 | | MKACTIVITY | 27 | Later version of ajp13, will transport additional methods, even if they are not in this list. ### protocol, req\_uri, remote\_addr, remote\_host, server\_name, server\_port, is\_ssl These are all fairly self-explanatory. Each of these is required, and will be sent for every request. ### Headers The structure of `request_headers` is the following: First, the number of headers `num_headers` is encoded. Then, a series of header name `req_header_name` / value `req_header_value` pairs follows. Common header names are encoded as integers, to save space. If the header name is not in the list of basic headers, it is encoded normally (as a string, with prefixed length). The list of common headers `sc_req_header_name`and their codes is as follows (all are case-sensitive): | | | | | --- | --- | --- | | Name | Code value | Code name | | accept | 0xA001 | SC\_REQ\_ACCEPT | | accept-charset | 0xA002 | SC\_REQ\_ACCEPT\_CHARSET | | accept-encoding | 0xA003 | SC\_REQ\_ACCEPT\_ENCODING | | accept-language | 0xA004 | SC\_REQ\_ACCEPT\_LANGUAGE | | authorization | 0xA005 | SC\_REQ\_AUTHORIZATION | | connection | 0xA006 | SC\_REQ\_CONNECTION | | content-type | 0xA007 | SC\_REQ\_CONTENT\_TYPE | | content-length | 0xA008 | SC\_REQ\_CONTENT\_LENGTH | | cookie | 0xA009 | SC\_REQ\_COOKIE | | cookie2 | 0xA00A | SC\_REQ\_COOKIE2 | | host | 0xA00B | SC\_REQ\_HOST | | pragma | 0xA00C | SC\_REQ\_PRAGMA | | referer | 0xA00D | SC\_REQ\_REFERER | | user-agent | 0xA00E | SC\_REQ\_USER\_AGENT | The Java code that reads this grabs the first two-byte integer and if it sees an `'0xA0'` in the most significant byte, it uses the integer in the second byte as an index into an array of header names. If the first byte is not `0xA0`, it assumes that the two-byte integer is the length of a string, which is then read in. This works on the assumption that no header names will have length greater than `0x9FFF (==0xA000 - 1)`, which is perfectly reasonable, though somewhat arbitrary. **Note:** The `content-length` header is extremely important. If it is present and non-zero, the container assumes that the request has a body (a POST request, for example), and immediately reads a separate packet off the input stream to get that body. ### Attributes The attributes prefixed with a `?` (e.g. `?context`) are all optional. For each, there is a single byte code to indicate the type of attribute, and then its value (string or integer). They can be sent in any order (though the C code always sends them in the order listed below). A special terminating code is sent to signal the end of the list of optional attributes. The list of byte codes is: | | | | | | --- | --- | --- | --- | | Information | Code Value | Type Of Value | Note | | ?context | 0x01 | - | Not currently implemented | | ?servlet\_path | 0x02 | - | Not currently implemented | | ?remote\_user | 0x03 | String | | | ?auth\_type | 0x04 | String | | | ?query\_string | 0x05 | String | | | ?jvm\_route | 0x06 | String | | | ?ssl\_cert | 0x07 | String | | | ?ssl\_cipher | 0x08 | String | | | ?ssl\_session | 0x09 | String | | | ?req\_attribute | 0x0A | String | Name (the name of the attribute follows) | | ?ssl\_key\_size | 0x0B | Integer | | | ?secret | 0x0C | String | Supported since 2.4.42 | | are\_done | 0xFF | - | request\_terminator | The `context` and `servlet_path` are not currently set by the C code, and most of the Java code completely ignores whatever is sent over for those fields (and some of it will actually break if a string is sent along after one of those codes). I don't know if this is a bug or an unimplemented feature or just vestigial code, but it's missing from both sides of the connection. The `remote_user` and `auth_type` presumably refer to HTTP-level authentication, and communicate the remote user's username and the type of authentication used to establish their identity (e.g. Basic, Digest). The `query_string`, `ssl_cert`, `ssl_cipher`, `ssl_session` and `ssl_key_size` refer to the corresponding pieces of HTTP and HTTPS. The `jvm_route`, is used to support sticky sessions -- associating a user's sesson with a particular Tomcat instance in the presence of multiple, load-balancing servers. The `secret` is sent when the `secret=secret_keyword` parameter is used in `[ProxyPass](mod_proxy#proxypass)` or `[BalancerMember](mod_proxy#balancermember)` directives. The backend needs to support secret and the values must match. `request.secret` or `requiredSecret` are documented in the AJP configuration of the Apache Tomcat. Beyond this list of basic attributes, any number of other attributes can be sent via the `req_attribute` code `0x0A`. A pair of strings to represent the attribute name and value are sent immediately after each instance of that code. Environment values are passed in via this method. Finally, after all the attributes have been sent, the attribute terminator, `0xFF`, is sent. This signals both the end of the list of attributes and also then end of the Request Packet. Response Packet Structure ------------------------- for messages which the container can send back to the server. ``` AJP13_SEND_BODY_CHUNK := prefix_code 3 chunk_length (integer) chunk *(byte) chunk_terminator (byte) Ox00 AJP13_SEND_HEADERS := prefix_code 4 http_status_code (integer) http_status_msg (string) num_headers (integer) response_headers *(res_header_name header_value) res_header_name := sc_res_header_name | (string) [see below for how this is parsed] sc_res_header_name := 0xA0 (byte) header_value := (string) AJP13_END_RESPONSE := prefix_code 5 reuse (boolean) AJP13_GET_BODY_CHUNK := prefix_code 6 requested_length (integer) ``` ### Details: ### Send Body Chunk The chunk is basically binary data, and is sent directly back to the browser. ### Send Headers The status code and message are the usual HTTP things (e.g. `200` and `OK`). The response header names are encoded the same way the request header names are. See header\_encoding above for details about how the codes are distinguished from the strings. The codes for common headers are: | | | | --- | --- | | Name | Code value | | Content-Type | 0xA001 | | Content-Language | 0xA002 | | Content-Length | 0xA003 | | Date | 0xA004 | | Last-Modified | 0xA005 | | Location | 0xA006 | | Set-Cookie | 0xA007 | | Set-Cookie2 | 0xA008 | | Servlet-Engine | 0xA009 | | Status | 0xA00A | | WWW-Authenticate | 0xA00B | After the code or the string header name, the header value is immediately encoded. ### End Response Signals the end of this request-handling cycle. If the `reuse` flag is true `(anything other than 0 in the actual C code)`, this TCP connection can now be used to handle new incoming requests. If `reuse` is false (==0), the connection should be closed. ### Get Body Chunk The container asks for more data from the request (If the body was too large to fit in the first packet sent over or when the request is chunked). The server will send a body packet back with an amount of data which is the minimum of the `request_length`, the maximum send body size `(8186 (8 Kbytes - 6))`, and the number of bytes actually left to send from the request body. If there is no more data in the body (i.e. the servlet container is trying to read past the end of the body), the server will send back an *empty* packet, which is a body packet with a payload length of 0. `(0x12,0x34,0x00,0x00)` apache_http_server Apache Module mod_logio Apache Module mod\_logio ======================== | | | | --- | --- | | Description: | Logging of input and output bytes per request | | Status: | Extension | | Module Identifier: | logio\_module | | Source File: | mod\_logio.c | ### Summary This module provides the logging of input and output number of bytes received/sent per request. The numbers reflect the actual bytes as received on the network, which then takes into account the headers and bodies of requests and responses. The counting is done before SSL/TLS on input and after SSL/TLS on output, so the numbers will correctly reflect any changes made by encryption. This module requires `<mod_log_config>`. When KeepAlive connections are used with SSL, the overhead of the SSL handshake is reflected in the byte count of the first request on the connection. When per-directory SSL renegotiation occurs, the bytes are associated with the request that triggered the renegotiation. Custom Log Formats ------------------ This module adds three new logging directives. The characteristics of the request itself are logged by placing "`%`" directives in the format string, which are replaced in the log file by the values as follows: | Format String | Description | | --- | --- | | `%I` | Bytes received, including request and headers, cannot be zero. | | `%O` | Bytes sent, including headers, cannot be zero. | | `%S` | Bytes transferred (received and sent), including request and headers, cannot be zero. This is the combination of %I and %O. Available in Apache 2.4.7 and later | | `%^FB` | Delay in microseconds between when the request arrived and the first byte of the response headers are written. Only available if `LogIOTrackTTFB` is set to ON. Available in Apache 2.4.13 and later | Usually, the functionality is used like this: Combined I/O log format: `"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" %I %O"` LogIOTrackTTFB Directive ------------------------ | | | | --- | --- | | Description: | Enable tracking of time to first byte (TTFB) | | Syntax: | ``` LogIOTrackTTFB ON|OFF ``` | | Default: | ``` LogIOTrackTTFB OFF ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_logio | | Compatibility: | Apache HTTP Server 2.4.13 and later | This directive configures whether this module tracks the delay between the request being read and the first byte of the response headers being written. The resulting value may be logged with the `%^FB` format.
programming_docs
apache_http_server Apache Module mod_tls Apache Module mod\_tls ====================== | | | | --- | --- | | Description: | TLS v1.2 and v1.3 implemented in memory-safe Rust via the rustls library | | Status: | Experimental | | Module Identifier: | tls\_module | | Source File: | mod\_tls.c | | Compatibility: | Available in version 2.4.52 and later | ### Summary mod\_tls is an alternative to `<mod_ssl>` for providing https to a server. It's feature set is a subset, described in more detail below. It can be used as a companion to `<mod_ssl>`, e.g. both modules can be loaded at the same time. mod\_tls, being written in C, used the Rust implementation of TLS named [rustls](https://github.com/rustls/rustls) via its C interface [rustls-ffi](https://github.com/rustls/rustls-ffi). This gives *memory safe* cryptography and protocol handling at comparable performance. It can be configured for frontend and backend connections. The configuration directive have been kept mostly similar to `<mod_ssl>` ones. TLS in a VirtualHost context ---------------------------- ``` Listen 443 TLSEngine 443 <VirtualHost *:443> ServerName example.net TLSCertificate file_with_certificate.pem file_with_key.pem ... </VirtualHost> ``` The above is a minimal configuration. Instead of enabling mod\_tls in every virtual host, the port for incoming TLS connections is specified. You cannot mix virtual hosts with `<mod_ssl>` and mod\_tls on the same port. It's either or. SNI and ALPN are supported. You may use several virtual hosts on the same port and a mix of protocols like http/1.1 and h2. Feature Comparison with mod\_ssl -------------------------------- The table below gives a comparison of feature between `<mod_ssl>` and mod\_tls. If a feature of `<mod_ssl>` is no listed here, it is not supported by mod\_tls. The one difference, probably most relevant is the lack for client certificate support in the current version of mod\_tls. | Feature | mod\_ssl | mod\_tls | Comment | | --- | --- | --- | --- | | Frontend TLS | yes | yes | | | Backend TLS | yes | yes | | | TLS v1.3 | yes\* | yes | \*)with recent OpenSSL | | TLS v1.2 | yes | yes | | | TLS v1.0 | yes\* | no | \*)if enabled in OpenSSL | | SNI Virtual Hosts | yes | yes | | | Client Certificates | yes | no | | | Machine Certificates for Backend | yes | yes | | | OCSP Stapling | yes | yes\* | \*)via `<mod_md>` | | Backend OCSP check | yes | no\* | \*)stapling will be verified | | TLS version to allow | min-max | min | | | TLS ciphers | exclusive list | preferred/suppressed | | | TLS cipher ordering | client/server | client/server | | | TLS sessions | yes | yes | | | SNI strictness | default no | default yes | | | Option EnvVars | exhaustive | limited\* | \*)see var list | | Option ExportCertData | client+server | server | | | Backend CA | file/dir | file | | | Revocation CRLs | yes | no | | | TLS Renegotiation | yes\* | no | \*)in TLS v1.2 | | Encrypted Cert Keys | yes | no | | TLS Protocols ------------- mod\_tls supports TLS protocol version 1.2 and 1.3. Should there ever be a version 1.4 and `rustls` supports it, it will be available as well. In mod\_tls, you configure the *minimum* version to use, never the maximum: ``` TLSProtocol TLSv1.3+ ``` This allows only version 1.3 and whatever may be its successor one day when talking to your server or to a particular virtual host. TLS Ciphers ----------- The list of TLS ciphers supported in the `rustls` library, can be found [here](https://docs.rs/rustls/). All TLS v1.3 ciphers are supported. For TLS v1.2, only ciphers that rustls considers secure are available. mod\_tls supports the following names for TLS ciphers: 1. The [IANA assigned name](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4) which uses `\_` to separate parts. Example: `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384` 2. The OpenSSL name, using `-` as separator (for 1.2). Example: `ECDHE-ECDSA-AES256-SHA384`. Such names often appear in documentation. `mod\_tls` defines them for all TLS v1.2 ciphers. For TLS v1.3 ciphers, names starting with `TLS13_` are also supported. 3. The [IANA assigned identifier](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4), which is a 16-bit numeric value. Example: `0xc024`. You can use this in configurations as `TLS_CIPHER_0xc024`. You can configure a preference for ciphers, which means they will be used for clients that support them. If you do not configure a preference, `rustls` will use the one that it considers best. This is recommended. Should you nevertheless have the need to prefer one cipher over another, you may configure it like this: ``` TLSCiphersPrefer ECDHE-ECDSA-AES256-SHA384 # or several TLSCiphersPrefer ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305 ``` If you name a cipher that is unknown, the configuration will fail. If you name a cipher is not supported by `rustls` (or no longer supported in an updated version of `rustls` for security reasons), mod\_tls will log a `WARNING`, but continue to work. A similar mechanism exists, if you want to disable a particular cipher: ``` TLSCipherSuppress ECDHE-ECDSA-AES256-SHA384 ``` A suppressed cipher will not longer be used. If you name a cipher that is unknown, the configuration will fail. If you name a cipher is not supported by `rustls` (or no longer supported in an updated version of `rustls` for security reasons), mod\_tls will log a `WARNING`, but continue to work. Virtual Hosts ------------- mod\_tls uses the SNI (Server Name Indicator) to select one of the configured virtual hosts that match the port being served. Should the client not provide an SNI, the *first* configured virtual host will be selected. If the client *does* provide an SNI (as all today's clients do), it *must* match one virtual host (`[ServerName](core#servername)` or `[ServerAlias](core#serveralias)`) or the connection will fail. As with `<mod_ssl>`, you may specify ciphers and protocol versions for the base server (global) and/or individual virtual hosts that are selected via SNI by the client. ``` Listen 443 TLSEngine 443 <VirtualHost *:443> ServerName example1.net TLSCertificate example1-cert.pem ... </VirtualHost> <VirtualHost *:443> ServerName example2.net TLSCertificate example2-cert.pem ... TLSProtocol v1.3+ </VirtualHost> ``` The example above show different TLS settings for virtual hosts on the same port. This is supported. `example1` can be contacted via all TLS versions and `example2` only allows v1.3 or later. ACME Certificates ----------------- ACME certificates via `<mod_md>` are supported, just as for `<mod_ssl>`. A minimal configuration: ``` Listen 443 TLSEngine 443 MDomain example.net <VirtualHost *:443> ServerName example.net ... </VirtualHost> ``` OCSP Stapling ------------- mod\_tls has no own implementation to retrieve OCSP information for a certificate. However, it will use such for Stapling if it is provided by `<mod_md>`. See `<mod_md>`'s documentation on how to enable this. TLS Variables ------------- Via the directive `[TLSOptions](#tlsoptions)`, several variables are placed into the environment of requests and can be inspected, for example in a CGI script. The variable names are given by `<mod_ssl>`. Note that these are only a subset of the many variables that `<mod_ssl>` exposes. | Variable | TLSOption | Description | | --- | --- | --- | | SSL\_TLS\_SNI | \* | the server name indicator (SNI) send by the client | | SSL\_PROTOCOL | \* | the TLS protocol negotiated | | SSL\_CIPHER | \* | the name of the TLS cipher negotiated | | SSL\_VERSION\_INTERFACE | StdEnvVars | the module version | | SSL\_VERSION\_LIBRARY | StdEnvVars | the rustls-ffi version | | SSL\_SECURE\_RENEG | StdEnvVars | always `false` | | SSL\_COMPRESS\_METHOD | StdEnvVars | always `false` | | SSL\_CIPHER\_EXPORT | StdEnvVars | always `false` | | SSL\_CLIENT\_VERIFY | StdEnvVars | always `false` | | SSL\_SESSION\_RESUMED | StdEnvVars | either `Resumed` if a known TLS session id was presented by the client or `Initial` otherwise | | SSL\_SERVER\_CERT | ExportCertData | the selected server certificate in PEM format | The variable `SSL_SESSION_ID` is intentionally not supported as it contains sensitive information. Client Certificates ------------------- While `rustls` supports client certificates in principle, parts of the infrastructure to make *use* of these in a server are not offered. Among these features are: revocation lists, inspection of certificate extensions and the matched issuer chain for OCSP validation. Without these, revocation of client certificates is not possible. Offering authentication without revocation is not considered an option. Work will continue on this and client certificate support may become available in a future release. TLSCertificate Directive ------------------------ | | | | --- | --- | | Description: | adds a certificate and key (PEM encoded) to a server/virtual host. | | Syntax: | ``` TLSCertificate cert_file [key_file] ``` | | Context: | server config, virtual host | | Status: | Experimental | | Module: | mod\_tls | If you do not specify a separate key file, the key is assumed to also be found in the first file. You may add more than one certificate to a server/virtual host. The first certificate suitable for a client is then chosen. The path can be specified relative to the server root. TLSCiphersPrefer Directive -------------------------- | | | | --- | --- | | Description: | defines ciphers that are preferred. | | Syntax: | ``` TLSCiphersPrefer cipher(-list) ``` | | Context: | server config, virtual host | | Status: | Experimental | | Module: | mod\_tls | This will not disable any ciphers supported by `rustls`. If you specify a cipher that is completely unknown, the configuration will fail. If you specify a cipher that is known but not supported by `rustls`, a warning will be logged but the server will continue. ### Example ``` TLSCiphersPrefer ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305 ``` The example gives 2 ciphers preference over others, in the order they are mentioned. TLSCiphersSuppress Directive ---------------------------- | | | | --- | --- | | Description: | defines ciphers that are not to be used. | | Syntax: | ``` TLSCiphersSuppress cipher(-list) ``` | | Context: | server config, virtual host | | Status: | Experimental | | Module: | mod\_tls | This will not disable any unmentioned ciphers supported by `rustls`. If you specify a cipher that is completely unknown, the configuration will fail. If you specify a cipher that is known but not supported by `rustls`, a warning will be logged but the server will continue. ### Example ``` TLSCiphersSuppress ECDHE-ECDSA-CHACHA20-POLY1305 ``` The example removes a cipher for use in connections. TLSEngine Directive ------------------- | | | | --- | --- | | Description: | defines on which address+port the module shall handle incoming connections. | | Syntax: | ``` TLSEngine [address:]port ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_tls | This is set on a global level, not in individual `[<VirtualHost>](core#virtualhost)`s. It will affect all `[<VirtualHost>](core#virtualhost)` that match the specified address/port. You can use `TLSEngine` several times to use more than one address/port. ### Example ``` TLSEngine 443 ``` The example tells mod\_tls to handle incoming connection on port 443 for all listeners. TLSHonorClientOrder Directive ----------------------------- | | | | --- | --- | | Description: | determines if the order of ciphers supported by the client is honored | | Syntax: | ``` TLSHonorClientOrder on|off ``` | | Default: | ``` TLSHonorClientOrder on ``` | | Context: | server config, virtual host | | Status: | Experimental | | Module: | mod\_tls | `TLSHonorClientOrder` determines if the order of ciphers supported by the client is honored. TLSOptions Directive -------------------- | | | | --- | --- | | Description: | enables SSL variables for requests. | | Syntax: | ``` TLSOptions [+|-]option ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Experimental | | Module: | mod\_tls | `TLSOptions` is analog to `[SSLOptions](mod_ssl#ssloptions)` in `<mod_ssl>`. It can be set per directory/location and `option` can be: * `StdEnvVars`: adds more variables to the requests environment, as forwarded for example to CGI processing and other applications. * `ExportCertData`: adds certificate related variables to the request environment. * `Defaults`: resets all options to their default values. Adding variables to a request environment adds overhead, especially when certificates need to be inspected and fields extracted. Therefore most variables are not set by default. You can configure `TLSOptions` per location or generally on a server/virtual host. Prefixing an option with `-` disables this option while leaving others unchanged. A `+` prefix is the same as writing the option without one. The `Defaults` value can be used to reset any options that are inherited from other locations or the virtual host/server. ### Example ``` <Location /myplace/app> TLSOptions Defaults StdEnvVars ... </Location> ``` TLSProtocol Directive --------------------- | | | | --- | --- | | Description: | specifies the minimum version of the TLS protocol to use. | | Syntax: | ``` TLSProtocol version+ ``` | | Default: | ``` TLSProtocol v1.2+ ``` | | Context: | server config, virtual host | | Status: | Experimental | | Module: | mod\_tls | The default is `v1.2+`. Settings this to `v1.3+` would disable TLSv1.2. TLSProxyCA Directive -------------------- | | | | --- | --- | | Description: | sets the root certificates to validate the backend server with. | | Syntax: | ``` TLSProxyCA file.pem ``` | | Context: | server config, virtual host, proxy section | | Status: | Experimental | | Module: | mod\_tls | TLSProxyCiphersPrefer Directive ------------------------------- | | | | --- | --- | | Description: | defines ciphers that are preferred for a proxy connection. | | Syntax: | ``` TLSProxyCiphersPrefer cipher(-list) ``` | | Context: | server config, virtual host, proxy section | | Status: | Experimental | | Module: | mod\_tls | This will not disable any ciphers supported by `rustls`. If you specify a cipher that is completely unknown, the configuration will fail. If you specify a cipher that is known but not supported by `rustls`, a warning will be logged but the server will continue. TLSProxyCiphersSuppress Directive --------------------------------- | | | | --- | --- | | Description: | defines ciphers that are not to be used for a proxy connection. | | Syntax: | ``` TLSProxyCiphersSuppress cipher(-list) ``` | | Context: | server config, virtual host, proxy section | | Status: | Experimental | | Module: | mod\_tls | This will not disable any unmentioned ciphers supported by `rustls`. If you specify a cipher that is completely unknown, the configuration will fail. If you specify a cipher that is known but not supported by `rustls`, a warning will be logged but the server will continue. TLSProxyEngine Directive ------------------------ | | | | --- | --- | | Description: | enables TLS for backend connections. | | Syntax: | ``` TLSProxyEngine on|off ``` | | Context: | server config, virtual host, proxy section | | Status: | Experimental | | Module: | mod\_tls | `TLSProxyEngine` is analog to `[SSLProxyEngine](mod_ssl#sslproxyengine)` in `<mod_ssl>`. This can be used in a server/virtual host or `[<Proxy>](mod_proxy#proxy)` section to enable the module for outgoing connections using `<mod_proxy>`. TLSProxyMachineCertificate Directive ------------------------------------ | | | | --- | --- | | Description: | adds a certificate and key file (PEM encoded) to a proxy setup. | | Syntax: | ``` TLSProxyMachineCertificate cert_file [key_file] ``` | | Context: | server config, virtual host, proxy section | | Status: | Experimental | | Module: | mod\_tls | The certificate is used to authenticate against a proxied backend server. If you do not specify a separate key file, the key is assumed to also be found in the first file. You may add more than one certificate to a proxy setup. The first certificate suitable for a proxy connection to a backend is then chosen by `rustls`. The path can be specified relative to the server root. TLSProxyProtocol Directive -------------------------- | | | | --- | --- | | Description: | specifies the minimum version of the TLS protocol to use in proxy connections. | | Syntax: | ``` TLSProxyProtocol version+ ``` | | Default: | ``` TLSProxyProtocol v1.2+ ``` | | Context: | server config, virtual host, proxy section | | Status: | Experimental | | Module: | mod\_tls | The default is `v1.2+`. Settings this to `v1.3+` would disable TLSv1.2. TLSSessionCache Directive ------------------------- | | | | --- | --- | | Description: | specifies the cache for TLS session resumption. | | Syntax: | ``` TLSSessionCache cache-spec ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_tls | This uses a cache on the server side to allow clients to resume connections. You can set this to `none` or define a cache as in the `[SSLSessionCache](mod_ssl#sslsessioncache)` directive of `<mod_ssl>`. If not configured, `mod\_tls` will try to create a shared memory cache on its own, using `shmcb:tls/session-cache` as specification. Should that fail, a warning is logged, but the server continues. TLSStrictSNI Directive ---------------------- | | | | --- | --- | | Description: | enforces exact matches of client server indicators (SNI) against host names. | | Syntax: | ``` TLSStrictSNI on|off ``` | | Default: | ``` TLSStrictSNI on ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_tls | Client connections using SNI will be unsuccessful if no match is found. apache_http_server Apache Module mod_dumpio Apache Module mod\_dumpio ========================= | | | | --- | --- | | Description: | Dumps all I/O to error log as desired. | | Status: | Extension | | Module Identifier: | dumpio\_module | | Source File: | mod\_dumpio.c | ### Summary `mod_dumpio` allows for the logging of all input received by Apache and/or all output sent by Apache to be logged (dumped) to the error.log file. The data logging is done right after SSL decoding (for input) and right before SSL encoding (for output). As can be expected, this can produce extreme volumes of data, and should only be used when debugging problems. Enabling dumpio Support ----------------------- To enable the module, it should be compiled and loaded in to your running Apache configuration. Logging can then be enabled or disabled separately for input and output via the below directives. Additionally, `<mod_dumpio>` needs to be configured to `[LogLevel](core#loglevel)` `trace7`: ``` LogLevel dumpio:trace7 ``` DumpIOInput Directive --------------------- | | | | --- | --- | | Description: | Dump all input data to the error log | | Syntax: | ``` DumpIOInput On|Off ``` | | Default: | ``` DumpIOInput Off ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_dumpio | | Compatibility: | DumpIOInput is only available in Apache 2.1.3 and later. | Enable dumping of all input. ### Example ``` DumpIOInput On ``` DumpIOOutput Directive ---------------------- | | | | --- | --- | | Description: | Dump all output data to the error log | | Syntax: | ``` DumpIOOutput On|Off ``` | | Default: | ``` DumpIOOutput Off ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_dumpio | | Compatibility: | DumpIOOutput is only available in Apache 2.1.3 and later. | Enable dumping of all output. ### Example ``` DumpIOOutput On ```
programming_docs
apache_http_server Apache Module mod_authz_owner Apache Module mod\_authz\_owner =============================== | | | | --- | --- | | Description: | Authorization based on file ownership | | Status: | Extension | | Module Identifier: | authz\_owner\_module | | Source File: | mod\_authz\_owner.c | | Compatibility: | Available in Apache 2.1 and later | ### Summary This module authorizes access to files by comparing the userid used for HTTP authentication (the web userid) with the file-system owner or group of the requested file. The supplied username and password must be already properly verified by an authentication module, such as `<mod_auth_basic>` or `<mod_auth_digest>`. `<mod_authz_owner>` recognizes two arguments for the `[Require](mod_authz_core#require)` directive, `file-owner` and `file-group`, as follows: `file-owner` The supplied web-username must match the system's name for the owner of the file being requested. That is, if the operating system says the requested file is owned by `jones`, then the username used to access it through the web must be `jones` as well. `file-group` The name of the system group that owns the file must be present in a group database, which is provided, for example, by `<mod_authz_groupfile>` or `<mod_authz_dbm>`, and the web-username must be a member of that group. For example, if the operating system says the requested file is owned by (system) group `accounts`, the group `accounts` must appear in the group database and the web-username used in the request must be a member of that group. **Note** If `<mod_authz_owner>` is used in order to authorize a resource that is not actually present in the filesystem (*i.e.* a virtual resource), it will deny the access. Particularly it will never authorize [content negotiated "MultiViews"](../content-negotiation#multiviews) resources. Configuration Examples ---------------------- ### Require file-owner Consider a multi-user system running the Apache Web server, with each user having his or her own files in `~/public_html/private`. Assuming that there is a single `[AuthDBMUserFile](mod_authn_dbm#authdbmuserfile)` database that lists all of their web-usernames, and that these usernames match the system's usernames that actually own the files on the server, then the following stanza would allow only the user himself access to his own files. User `jones` would not be allowed to access files in `/home/smith/public_html/private` unless they were owned by `jones` instead of `smith`. ``` <Directory "/home/*/public_html/private"> AuthType Basic AuthName MyPrivateFiles AuthBasicProvider dbm AuthDBMUserFile "/usr/local/apache2/etc/.htdbm-all" Require file-owner </Directory> ``` ### Require file-group Consider a system similar to the one described above, but with some users that share their project files in `~/public_html/project-foo`. The files are owned by the system group `foo` and there is a single `[AuthDBMGroupFile](mod_authz_dbm#authdbmgroupfile)` database that contains all of the web-usernames and their group membership, *i.e.* they must be at least member of a group named `foo`. So if `jones` and `smith` are both member of the group `foo`, then both will be authorized to access the `project-foo` directories of each other. ``` <Directory "/home/*/public_html/project-foo"> AuthType Basic AuthName "Project Foo Files" AuthBasicProvider dbm # combined user/group database AuthDBMUserFile "/usr/local/apache2/etc/.htdbm-all" AuthDBMGroupFile "/usr/local/apache2/etc/.htdbm-all" Satisfy All Require file-group </Directory> ``` apache_http_server Apache Module mod_so Apache Module mod\_so ===================== | | | | --- | --- | | Description: | Loading of executable code and modules into the server at start-up or restart time | | Status: | Extension | | Module Identifier: | so\_module | | Source File: | mod\_so.c | | Compatibility: | This is a Base module (always included) on Windows | ### Summary On selected operating systems this module can be used to load modules into Apache HTTP Server at runtime via the [Dynamic Shared Object](../dso) (DSO) mechanism, rather than requiring a recompilation. On Unix, the loaded code typically comes from shared object files (usually with `.so` extension), on Windows this may either be the `.so` or `.dll` extension. **Warning** Modules built for one major version of the Apache HTTP Server will generally not work on another. (e.g. 1.3 vs. 2.0, or 2.0 vs. 2.2) There are usually API changes between one major version and another that require that modules be modified to work with the new version. Creating Loadable Modules for Windows ------------------------------------- **Note** On Windows, where loadable files typically have a file extension of `.dll`, Apache httpd modules are called `mod_whatever.so`, just as they are on other platforms. However, you may encounter third-party modules, such as PHP for example, that continue to use the `.dll` convention. While `mod_so` still loads modules with `ApacheModuleFoo.dll` names, the new naming convention is preferred; if you are converting your loadable module for 2.0, please fix the name to this 2.0 convention. The Apache httpd module API is unchanged between the Unix and Windows versions. Many modules will run on Windows with no or little change from Unix, although others rely on aspects of the Unix architecture which are not present in Windows, and will not work. When a module does work, it can be added to the server in one of two ways. As with Unix, it can be compiled into the server. Because Apache httpd for Windows does not have the `Configure` program of Apache httpd for Unix, the module's source file must be added to the ApacheCore project file, and its symbols must be added to the `os\win32\modules.c` file. The second way is to compile the module as a DLL, a shared library that can be loaded into the server at runtime, using the `LoadModule` directive. These module DLLs can be distributed and run on any Apache httpd for Windows installation, without recompilation of the server. To create a module DLL, a small change is necessary to the module's source file: The module record must be exported from the DLL (which will be created later; see below). To do this, add the `AP_MODULE_DECLARE_DATA` (defined in the Apache httpd header files) to your module's module record definition. For example, if your module has: ``` module foo_module; ``` Replace the above with: ``` module AP_MODULE_DECLARE_DATA foo_module; ``` Note that this will only be activated on Windows, so the module can continue to be used, unchanged, with Unix if needed. Also, if you are familiar with `.DEF` files, you can export the module record with that method instead. Now, create a DLL containing your module. You will need to link this against the libhttpd.lib export library that is created when the libhttpd.dll shared library is compiled. You may also have to change the compiler settings to ensure that the Apache httpd header files are correctly located. You can find this library in your server root's modules directory. It is best to grab an existing module .dsp file from the tree to assure the build environment is configured correctly, or alternately compare the compiler and link options to your .dsp. This should create a DLL version of your module. Now simply place it in the `modules` directory of your server root, and use the `LoadModule` directive to load it. LoadFile Directive ------------------ | | | | --- | --- | | Description: | Link in the named object file or library | | Syntax: | ``` LoadFile filename [filename] ... ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_so | The `LoadFile` directive links in the named object files or libraries when the server is started or restarted; this is used to load additional code which may be required for some module to work. *Filename* is either an absolute path or relative to [ServerRoot](core#serverroot). For example: ``` LoadFile "libexec/libxmlparse.so" ``` LoadModule Directive -------------------- | | | | --- | --- | | Description: | Links in the object file or library, and adds to the list of active modules | | Syntax: | ``` LoadModule module filename ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_so | The `LoadModule` directive links in the object file or library *filename* and adds the module structure named *module* to the list of active modules. *Module* is the name of the external variable of type `module` in the file, and is listed as the Module Identifier in the module documentation. For example: ``` LoadModule status_module "modules/mod_status.so" ``` loads the named module from the modules subdirectory of the ServerRoot. apache_http_server Apache MPM netware Apache MPM netware ================== | | | | --- | --- | | Description: | Multi-Processing Module implementing an exclusively threaded web server optimized for Novell NetWare | | Status: | MPM | | Module Identifier: | mpm\_netware\_module | | Source File: | mpm\_netware.c | ### Summary This Multi-Processing Module (MPM) implements an exclusively threaded web server that has been optimized for Novell NetWare. The main thread is responsible for launching child worker threads which listen for connections and serve them when they arrive. Apache HTTP Server always tries to maintain several spare or idle worker threads, which stand ready to serve incoming requests. In this way, clients do not need to wait for a new child threads to be spawned before their requests can be served. The `[StartThreads](mpm_common#startthreads)`, `[MinSpareThreads](mpm_common#minsparethreads)`, `[MaxSpareThreads](mpm_common#maxsparethreads)`, and `[MaxThreads](#maxthreads)` regulate how the main thread creates worker threads to serve requests. In general, Apache httpd is very self-regulating, so most sites do not need to adjust these directives from their default values. Sites with limited memory may need to decrease `[MaxThreads](#maxthreads)` to keep the server from thrashing (spawning and terminating idle threads). More information about tuning process creation is provided in the [performance hints](../misc/perf-tuning) documentation. `[MaxConnectionsPerChild](mpm_common#maxconnectionsperchild)` controls how frequently the server recycles processes by killing old ones and launching new ones. On the NetWare OS it is highly recommended that this directive remain set to 0. This allows worker threads to continue servicing requests indefinitely. MaxThreads Directive -------------------- | | | | --- | --- | | Description: | Set the maximum number of worker threads | | Syntax: | ``` MaxThreads number ``` | | Default: | ``` MaxThreads 2048 ``` | | Context: | server config | | Status: | MPM | | Module: | mpm\_netware | The `MaxThreads` directive sets the desired maximum number worker threads allowable. The default value is also the compiled in hard limit. Therefore it can only be lowered, for example: ``` MaxThreads 512 ``` apache_http_server Apache Module mod_session_crypto Apache Module mod\_session\_crypto ================================== | | | | --- | --- | | Description: | Session encryption support | | Status: | Experimental | | Module Identifier: | session\_crypto\_module | | Source File: | mod\_session\_crypto.c | | Compatibility: | Available in Apache 2.3 and later | ### Summary **Warning** The session modules make use of HTTP cookies, and as such can fall victim to Cross Site Scripting attacks, or expose potentially private information to clients. Please ensure that the relevant risks have been taken into account before enabling the session functionality on your server. This submodule of `<mod_session>` provides support for the encryption of user sessions before being written to a local database, or written to a remote browser via an HTTP cookie. This can help provide privacy to user sessions where the contents of the session should be kept private from the user, or where protection is needed against the effects of cross site scripting attacks. For more details on the session interface, see the documentation for the `<mod_session>` module. Basic Usage ----------- To create a simple encrypted session and store it in a cookie called session, configure the session as follows: ### Browser based encrypted session ``` Session On SessionCookieName session path=/ SessionCryptoPassphrase secret ``` The session will be encrypted with the given key. Different servers can be configured to share sessions by ensuring the same encryption key is used on each server. If the encryption key is changed, sessions will be invalidated automatically. For documentation on how the session can be used to store username and password details, see the `<mod_auth_form>` module. SessionCryptoCipher Directive ----------------------------- | | | | --- | --- | | Description: | The crypto cipher to be used to encrypt the session | | Syntax: | ``` SessionCryptoCipher name ``` | | Default: | ``` SessionCryptoCipher aes256 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Experimental | | Module: | mod\_session\_crypto | | Compatibility: | Available in Apache 2.3.0 and later | The `SessionCryptoCipher` directive allows the cipher to be used during encryption. If not specified, the cipher defaults to `aes256`. Possible values depend on the crypto driver in use, and could be one of: * 3des192 * aes128 * aes192 * aes256 SessionCryptoDriver Directive ----------------------------- | | | | --- | --- | | Description: | The crypto driver to be used to encrypt the session | | Syntax: | ``` SessionCryptoDriver name [param[=value]] ``` | | Default: | `none` | | Context: | server config | | Status: | Experimental | | Module: | mod\_session\_crypto | | Compatibility: | Available in Apache 2.3.0 and later | The `SessionCryptoDriver` directive specifies the name of the crypto driver to be used for encryption. If not specified, the driver defaults to the recommended driver compiled into APR-util. The NSS crypto driver requires some parameters for configuration, which are specified as parameters with optional values after the driver name. ### NSS without a certificate database ``` SessionCryptoDriver nss ``` ### NSS with certificate database ``` SessionCryptoDriver nss dir=certs ``` ### NSS with certificate database and parameters ``` SessionCryptoDriver nss dir=certs key3=key3.db cert7=cert7.db secmod=secmod ``` ### NSS with paths containing spaces ``` SessionCryptoDriver nss "dir=My Certs" key3=key3.db cert7=cert7.db secmod=secmod ``` The NSS crypto driver might have already been configured by another part of the server, for example from `mod_nss` or `<mod_ldap>`. If found to have already been configured, a warning will be logged, and the existing configuration will have taken affect. To avoid this warning, use the noinit parameter as follows. ### NSS with certificate database ``` SessionCryptoDriver nss noinit ``` To prevent confusion, ensure that all modules requiring NSS are configured with identical parameters. The openssl crypto driver supports an optional parameter to specify the engine to be used for encryption. ### OpenSSL with engine support ``` SessionCryptoDriver openssl engine=name ``` SessionCryptoPassphrase Directive --------------------------------- | | | | --- | --- | | Description: | The key used to encrypt the session | | Syntax: | ``` SessionCryptoPassphrase secret [ secret ... ] ``` | | Default: | `none` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Experimental | | Module: | mod\_session\_crypto | | Compatibility: | Available in Apache 2.3.0 and later | The `SessionCryptoPassphrase` directive specifies the keys to be used to enable symmetrical encryption on the contents of the session before writing the session, or decrypting the contents of the session after reading the session. Keys are more secure when they are long, and consist of truly random characters. Changing the key on a server has the effect of invalidating all existing sessions. Multiple keys can be specified in order to support key rotation. The first key listed will be used for encryption, while all keys listed will be attempted for decryption. To rotate keys across multiple servers over a period of time, add a new secret to the end of the list, and once rolled out completely to all servers, remove the first key from the start of the list. As of version 2.4.7 if the value begins with exec: the resulting command will be executed and the first line returned to standard output by the program will be used as the key. ``` #key used as-is SessionCryptoPassphrase secret #Run /path/to/program to get key SessionCryptoPassphrase exec:/path/to/program #Run /path/to/otherProgram and provide arguments SessionCryptoPassphrase "exec:/path/to/otherProgram argument1" ``` SessionCryptoPassphraseFile Directive ------------------------------------- | | | | --- | --- | | Description: | File containing keys used to encrypt the session | | Syntax: | ``` SessionCryptoPassphraseFile filename ``` | | Default: | `none` | | Context: | server config, virtual host, directory | | Status: | Experimental | | Module: | mod\_session\_crypto | | Compatibility: | Available in Apache 2.3.0 and later | The `SessionCryptoPassphraseFile` directive specifies the name of a configuration file containing the keys to use for encrypting or decrypting the session, specified one per line. The file is read on server start, and a graceful restart will be necessary for httpd to pick up changes to the keys. Unlike the `[SessionCryptoPassphrase](#sessioncryptopassphrase)` directive, the keys are not exposed within the httpd configuration and can be hidden by protecting the file appropriately. Multiple keys can be specified in order to support key rotation. The first key listed will be used for encryption, while all keys listed will be attempted for decryption. To rotate keys across multiple servers over a period of time, add a new secret to the end of the list, and once rolled out completely to all servers, remove the first key from the start of the list. apache_http_server Apache Module mod_proxy_balancer Apache Module mod\_proxy\_balancer ================================== | | | | --- | --- | | Description: | `<mod_proxy>` extension for load balancing | | Status: | Extension | | Module Identifier: | proxy\_balancer\_module | | Source File: | mod\_proxy\_balancer.c | | Compatibility: | Available in version 2.1 and later | ### Summary This module *requires* the service of `<mod_proxy>` and it provides load balancing for all the supported protocols. The most important ones are: * HTTP, using `<mod_proxy_http>` * FTP, using `<mod_proxy_ftp>` * AJP13, using `<mod_proxy_ajp>` * WebSocket, using `<mod_proxy_wstunnel>` The Load balancing scheduler algorithm is not provided by this module but from other ones such as: * `<mod_lbmethod_byrequests>` * `<mod_lbmethod_bytraffic>` * `<mod_lbmethod_bybusyness>` * `<mod_lbmethod_heartbeat>` Thus, in order to get the ability of load balancing, `<mod_proxy>`, `<mod_proxy_balancer>` and at least one of load balancing scheduler algorithm modules have to be present in the server. **Warning** Do not enable proxying until you have [secured your server](mod_proxy#access). Open proxy servers are dangerous both to your network and to the Internet at large. Load balancer scheduler algorithm --------------------------------- At present, there are 4 load balancer scheduler algorithms available for use: Request Counting (`<mod_lbmethod_byrequests>`), Weighted Traffic Counting (`<mod_lbmethod_bytraffic>`), Pending Request Counting (`<mod_lbmethod_bybusyness>`) and Heartbeat Traffic Counting (`<mod_lbmethod_heartbeat>`). These are controlled via the `lbmethod` value of the Balancer definition. See the `[ProxyPass](mod_proxy#proxypass)` directive for more information, especially regarding how to configure the Balancer and BalancerMembers. Load balancer stickyness ------------------------ The balancer supports stickyness. When a request is proxied to some back-end, then all following requests from the same user should be proxied to the same back-end. Many load balancers implement this feature via a table that maps client IP addresses to back-ends. This approach is transparent to clients and back-ends, but suffers from some problems: unequal load distribution if clients are themselves hidden behind proxies, stickyness errors when a client uses a dynamic IP address that changes during a session and loss of stickyness, if the mapping table overflows. The module `<mod_proxy_balancer>` implements stickyness on top of two alternative means: cookies and URL encoding. Providing the cookie can be either done by the back-end or by the Apache web server itself. The URL encoding is usually done on the back-end. Examples of a balancer configuration ------------------------------------ Before we dive into the technical details, here's an example of how you might use `<mod_proxy_balancer>` to provide load balancing between two back-end servers: ``` <Proxy "balancer://mycluster"> BalancerMember "http://192.168.1.50:80" BalancerMember "http://192.168.1.51:80" </Proxy> ProxyPass "/test" "balancer://mycluster" ProxyPassReverse "/test" "balancer://mycluster" ``` Another example of how to provide load balancing with stickyness using `<mod_headers>`, even if the back-end server does not set a suitable session cookie: ``` Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED <Proxy "balancer://mycluster"> BalancerMember "http://192.168.1.50:80" route=1 BalancerMember "http://192.168.1.51:80" route=2 ProxySet stickysession=ROUTEID </Proxy> ProxyPass "/test" "balancer://mycluster" ProxyPassReverse "/test" "balancer://mycluster" ``` Exported Environment Variables ------------------------------ At present there are 6 environment variables exported: BALANCER\_SESSION\_STICKY This is assigned the stickysession value used for the current request. It is the name of the cookie or request parameter used for sticky sessions BALANCER\_SESSION\_ROUTE This is assigned the route parsed from the current request. BALANCER\_NAME This is assigned the name of the balancer used for the current request. The value is something like `balancer://foo`. BALANCER\_WORKER\_NAME This is assigned the name of the worker used for the current request. The value is something like `http://hostA:1234`. BALANCER\_WORKER\_ROUTE This is assigned the route of the worker that will be used for the current request. BALANCER\_ROUTE\_CHANGED This is set to 1 if the session route does not match the worker route (BALANCER\_SESSION\_ROUTE != BALANCER\_WORKER\_ROUTE) or the session does not yet have an established route. This can be used to determine when/if the client needs to be sent an updated route when sticky sessions are used. Enabling Balancer Manager Support --------------------------------- This module *requires* the service of `<mod_status>`. Balancer manager enables dynamic update of balancer members. You can use balancer manager to change the balance factor of a particular member, or put it in the off line mode. Thus, in order to get the ability of load balancer management, `<mod_status>` and `<mod_proxy_balancer>` have to be present in the server. To enable load balancer management for browsers from the example.com domain add this code to your `httpd.conf` configuration file ``` <Location "/balancer-manager"> SetHandler balancer-manager Require host example.com </Location> ``` You can now access load balancer manager by using a Web browser to access the page `http://your.server.name/balancer-manager`. Please note that only Balancers defined outside of `<Location ...>` containers can be dynamically controlled by the Manager. Details on load balancer stickyness ----------------------------------- When using cookie based stickyness, you need to configure the name of the cookie that contains the information about which back-end to use. This is done via the stickysession attribute added to either `[ProxyPass](mod_proxy#proxypass)` or `[ProxySet](mod_proxy#proxyset)`. The name of the cookie is case-sensitive. The balancer extracts the value of the cookie and looks for a member worker with route equal to that value. The route must also be set in either `[ProxyPass](mod_proxy#proxypass)` or `[ProxySet](mod_proxy#proxyset)`. The cookie can either be set by the back-end, or as shown in the above [example](#example) by the Apache web server itself. Some back-ends use a slightly different form of stickyness cookie, for instance Apache Tomcat. Tomcat adds the name of the Tomcat instance to the end of its session id cookie, separated with a dot (`.`) from the session id. Thus if the Apache web server finds a dot in the value of the stickyness cookie, it only uses the part behind the dot to search for the route. In order to let Tomcat know about its instance name, you need to set the attribute `jvmRoute` inside the Tomcat configuration file `conf/server.xml` to the value of the route of the worker that connects to the respective Tomcat. The name of the session cookie used by Tomcat (and more generally by Java web applications based on servlets) is `JSESSIONID` (upper case) but can be configured to something else. The second way of implementing stickyness is URL encoding. The web server searches for a query parameter in the URL of the request. The name of the parameter is specified again using stickysession. The value of the parameter is used to lookup a member worker with route equal to that value. Since it is not easy to extract and manipulate all URL links contained in responses, generally the work of adding the parameters to each link is done by the back-end generating the content. In some cases it might be feasible doing this via the web server using `<mod_substitute>` or `<mod_sed>`. This can have negative impact on performance though. The Java standards implement URL encoding slightly different. They use a path info appended to the URL using a semicolon (`;`) as the separator and add the session id behind. As in the cookie case, Apache Tomcat can include the configured `jvmRoute` in this path info. To let Apache find this sort of path info, you need to set `scolonpathdelim` to `On` in `[ProxyPass](mod_proxy#proxypass)` or `[ProxySet](mod_proxy#proxyset)`. Finally you can support cookies and URL encoding at the same time, by configuring the name of the cookie and the name of the URL parameter separated by a vertical bar (`|`) as in the following example: ``` ProxyPass "/test" "balancer://mycluster" stickysession=JSESSIONID|jsessionid scolonpathdelim=On <Proxy "balancer://mycluster"> BalancerMember "http://192.168.1.50:80" route=node1 BalancerMember "http://192.168.1.51:80" route=node2 </Proxy> ``` If the cookie and the request parameter both provide routing information for the same request, the information from the request parameter is used. Troubleshooting load balancer stickyness ---------------------------------------- If you experience stickyness errors, e.g. users lose their application sessions and need to login again, you first want to check whether this is because the back-ends are sometimes unavailable or whether your configuration is wrong. To find out about possible stability problems with the back-ends, check your Apache error log for proxy error messages. To verify your configuration, first check, whether the stickyness is based on a cookie or on URL encoding. Next step would be logging the appropriate data in the access log by using an enhanced `[LogFormat](mod_log_config#logformat)`. The following fields are useful: `%{MYCOOKIE}C` The value contained in the cookie with name `MYCOOKIE`. The name should be the same given in the stickysession attribute. `%{Set-Cookie}o` This logs any cookie set by the back-end. You can track, whether the back-end sets the session cookie you expect, and to which value it is set. `%{BALANCER_SESSION_STICKY}e` The name of the cookie or request parameter used to lookup the routing information. `%{BALANCER_SESSION_ROUTE}e` The route information found in the request. `%{BALANCER_WORKER_ROUTE}e` The route of the worker chosen. `%{BALANCER_ROUTE_CHANGED}e` Set to `1` if the route in the request is different from the route of the worker, i.e. the request couldn't be handled sticky. Common reasons for loss of session are session timeouts, which are usually configurable on the back-end server. The balancer also logs detailed information about handling stickyness to the error log, if the log level is set to `debug` or higher. This is an easy way to troubleshoot stickyness problems, but the log volume might be too high for production servers under high load.
programming_docs
apache_http_server Apache Module mod_dir Apache Module mod\_dir ====================== | | | | --- | --- | | Description: | Provides for "trailing slash" redirects and serving directory index files | | Status: | Base | | Module Identifier: | dir\_module | | Source File: | mod\_dir.c | ### Summary The index of a directory can come from one of two sources: * A file written by the user, typically called `index.html`. The `[DirectoryIndex](#directoryindex)` directive sets the name of this file. This is controlled by `<mod_dir>`. * Otherwise, a listing generated by the server. This is provided by `<mod_autoindex>`. The two functions are separated so that you can completely remove (or replace) automatic index generation should you want to. A "trailing slash" redirect is issued when the server receives a request for a URL `http://servername/foo/dirname` where `dirname` is a directory. Directories require a trailing slash, so `<mod_dir>` issues a redirect to `http://servername/foo/dirname/`. DirectoryCheckHandler Directive ------------------------------- | | | | --- | --- | | Description: | Toggle how this module responds when another handler is configured | | Syntax: | ``` DirectoryCheckHandler On|Off ``` | | Default: | ``` DirectoryCheckHandler Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_dir | | Compatibility: | Available in 2.4.8 and later. Releases prior to 2.4 implicitly act as if "DirectoryCheckHandler ON" was specified. | The `DirectoryCheckHandler` directive determines whether `<mod_dir>` should check for directory indexes or add trailing slashes when some other handler has been configured for the current URL. Handlers can be set by directives such as `[SetHandler](core#sethandler)` or by other modules, such as `<mod_rewrite>` during per-directory substitutions. In releases prior to 2.4, this module did not take any action if any other handler was configured for a URL. This allows directory indexes to be served even when a `SetHandler` directive is specified for an entire directory, but it can also result in some conflicts with modules such as `<mod_rewrite>`. DirectoryIndex Directive ------------------------ | | | | --- | --- | | Description: | List of resources to look for when the client requests a directory | | Syntax: | ``` DirectoryIndex disabled | local-url [local-url] ... ``` | | Default: | ``` DirectoryIndex index.html ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_dir | The `DirectoryIndex` directive sets the list of resources to look for, when the client requests an index of the directory by specifying a / at the end of the directory name. Local-url is the (%-encoded) URL of a document on the server relative to the requested directory; it is usually the name of a file in the directory. Several URLs may be given, in which case the server will return the first one that it finds. If none of the resources exist and the `Indexes` option is set, the server will generate its own listing of the directory. ### Example ``` DirectoryIndex index.html ``` then a request for `http://example.com/docs/` would return `http://example.com/docs/index.html` if it exists, or would list the directory if it did not. Note that the documents do not need to be relative to the directory; ``` DirectoryIndex index.html index.txt /cgi-bin/index.pl ``` would cause the CGI script `/cgi-bin/index.pl` to be executed if neither `index.html` or `index.txt` existed in a directory. A single argument of "disabled" prevents `<mod_dir>` from searching for an index. An argument of "disabled" will be interpreted literally if it has any arguments before or after it, even if they are "disabled" as well. **Note:** Multiple `DirectoryIndex` directives within the [*same context*](../sections) will add to the list of resources to look for rather than replace: ``` # Example A: Set index.html as an index page, then add index.php to that list as well. <Directory "/foo"> DirectoryIndex index.html DirectoryIndex index.php </Directory> # Example B: This is identical to example A, except it's done with a single directive. <Directory "/foo"> DirectoryIndex index.html index.php </Directory> # Example C: To replace the list, you must explicitly reset it first: # In this example, only index.php will remain as an index resource. <Directory "/foo"> DirectoryIndex index.html DirectoryIndex disabled DirectoryIndex index.php </Directory> ``` DirectoryIndexRedirect Directive -------------------------------- | | | | --- | --- | | Description: | Configures an external redirect for directory indexes. | | Syntax: | ``` DirectoryIndexRedirect on | off | permanent | temp | seeother | 3xx-code ``` | | Default: | ``` DirectoryIndexRedirect off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_dir | | Compatibility: | Available in version 2.3.14 and later | By default, the `DirectoryIndex` is selected and returned transparently to the client. `DirectoryIndexRedirect` causes an external redirect to instead be issued. The argument can be: * `on`: issues a 302 redirection to the index resource. * `off`: does not issue a redirection. This is the legacy behaviour of mod\_dir. * `permanent`: issues a 301 (permanent) redirection to the index resource. * `temp`: this has the same effect as `on` * `seeother`: issues a 303 redirection (also known as "See Other") to the index resource. * 3xx-code: issues a redirection marked by the chosen 3xx code. ### Example ``` DirectoryIndexRedirect on ``` A request for `http://example.com/docs/` would return a temporary redirect to `http://example.com/docs/index.html` if it exists. DirectorySlash Directive ------------------------ | | | | --- | --- | | Description: | Toggle trailing slash redirects on or off | | Syntax: | ``` DirectorySlash On|Off ``` | | Default: | ``` DirectorySlash On ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_dir | The `DirectorySlash` directive determines whether `<mod_dir>` should fixup URLs pointing to a directory or not. Typically if a user requests a resource without a trailing slash, which points to a directory, `<mod_dir>` redirects him to the same resource, but *with* trailing slash for some good reasons: * The user is finally requesting the canonical URL of the resource * `<mod_autoindex>` works correctly. Since it doesn't emit the path in the link, it would point to the wrong path. * `[DirectoryIndex](#directoryindex)` will be evaluated *only* for directories requested with trailing slash. * Relative URL references inside html pages will work correctly. If you don't want this effect *and* the reasons above don't apply to you, you can turn off the redirect as shown below. However, be aware that there are possible security implications to doing this. ``` # see security warning below! <Location "/some/path"> DirectorySlash Off SetHandler some-handler </Location> ``` **Security Warning** Turning off the trailing slash redirect may result in an information disclosure. Consider a situation where `<mod_autoindex>` is active (`Options +Indexes`) and `[DirectoryIndex](#directoryindex)` is set to a valid resource (say, `index.html`) and there's no other special handler defined for that URL. In this case a request with a trailing slash would show the `index.html` file. **But a request without trailing slash would list the directory contents**. Also note that some browsers may erroneously change POST requests into GET (thus discarding POST data) when a redirect is issued. FallbackResource Directive -------------------------- | | | | --- | --- | | Description: | Define a default URL for requests that don't map to a file | | Syntax: | ``` FallbackResource disabled | local-url ``` | | Default: | ``` disabled - httpd will return 404 (Not Found) ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_dir | | Compatibility: | The `disabled` argument is available in version 2.4.4 and later | Use this to set a handler for any URL that doesn't map to anything in your filesystem, and would otherwise return HTTP 404 (Not Found). For example ``` FallbackResource /not-404.php ``` will cause requests for non-existent files to be handled by `not-404.php`, while requests for files that exist are unaffected. It is frequently desirable to have a single file or resource handle all requests to a particular directory, except those requests that correspond to an existing file or script. This is often referred to as a 'front controller.' In earlier versions of httpd, this effect typically required `<mod_rewrite>`, and the use of the `-f` and `-d` tests for file and directory existence. This now requires only one line of configuration. ``` FallbackResource /index.php ``` Existing files, such as images, css files, and so on, will be served normally. Use the `disabled` argument to disable that feature if inheritance from a parent directory is not desired. In a sub-URI, such as *http://example.com/blog/* this *sub-URI* has to be supplied as local-url: ``` <Directory "/web/example.com/htdocs/blog"> FallbackResource /blog/index.php </Directory> <Directory "/web/example.com/htdocs/blog/images"> FallbackResource disabled </Directory> ``` A fallback handler (in the above case, `/blog/index.php`) can access the original requested URL via the server variable `REQUEST_URI`. For example, to access this variable in PHP, use `$_SERVER['REQUEST_URI']`. apache_http_server Apache Module mod_dialup Apache Module mod\_dialup ========================= | | | | --- | --- | | Description: | Send static content at a bandwidth rate limit, defined by the various old modem standards | | Status: | Experimental | | Module Identifier: | dialup\_module | | Source File: | mod\_dialup.c | ### Summary It is a module that sends static content at a bandwidth rate limit, defined by the various old modem standards. So, you can browse your site with a 56k V.92 modem, by adding something like this: ``` <Location "/mysite"> ModemStandard "V.92" </Location> ``` Previously to do bandwidth rate limiting modules would have to block an entire thread, for each client, and insert sleeps to slow the bandwidth down. Using the new suspend feature, a handler can get callback N milliseconds in the future, and it will be invoked by the Event MPM on a different thread, once the timer hits. From there the handler can continue to send data to the client. ModemStandard Directive ----------------------- | | | | --- | --- | | Description: | Modem standard to simulate | | Syntax: | ``` ModemStandard V.21|V.26bis|V.32|V.34|V.92 ``` | | Context: | directory | | Status: | Experimental | | Module: | mod\_dialup | Specify what modem standard you wish to simulate. ``` <Location "/mysite"> ModemStandard "V.26bis" </Location> ``` apache_http_server Apache Module mod_proxy_wstunnel Apache Module mod\_proxy\_wstunnel ================================== | | | | --- | --- | | Description: | Websockets support module for `<mod_proxy>` | | Status: | Extension | | Module Identifier: | proxy\_wstunnel\_module | | Source File: | mod\_proxy\_wstunnel.c | | Compatibility: | Available in httpd 2.4.5 and later | ### Summary This module *requires* the service of `<mod_proxy>`. It provides support for the tunnelling of web socket connections to a backend websockets server. The connection is automatically upgraded to a websocket connection: ### HTTP Response ``` Upgrade: WebSocket Connection: Upgrade ``` Proxying requests to a websockets server like `echo.websocket.org` can be done using the `[ProxyPass](mod_proxy#proxypass)` directive: ``` ProxyPass "/ws2/" "ws://echo.websocket.org/" ProxyPass "/wss2/" "wss://echo.websocket.org/" ``` Proxying both HTTP and websockets at the same time, with a specific set of URL's being websocket-only, can be done by specifying the websockets `[ProxyPass](mod_proxy#proxypass)` directive before the HTTP directive: ``` ProxyPassMatch ^/(myApp/ws)$ ws://backend.example.com:9080/$1 ProxyPass / http://backend.example.com:9080/ ``` Proxying both HTTP and websockets at the same time, where the websockets URL's are not websocket-only or not known in advance can be done by using the `[RewriteRule](mod_rewrite#rewriterule)` directive to configure the websockets proxying: ``` ProxyPass / http://example.com:9080/ RewriteEngine on RewriteCond %{HTTP:Upgrade} websocket [NC] RewriteCond %{HTTP:Connection} upgrade [NC] RewriteRule ^/?(.*) "ws://example.com:9080/$1" [P,L] ``` Load balancing for multiple backends can be achieved using `<mod_proxy_balancer>`. In fact the module can be used to upgrade to other protocols, you can set the `upgrade` parameter in the `[ProxyPass](mod_proxy#proxypass)` directive to allow the module to accept other protocol. NONE means you bypass the check for the header but still upgrade to WebSocket. ANY means that `Upgrade` will read in the request headers and use in the response `Upgrade` ProxyWebsocketFallbackToProxyHttp Directive ------------------------------------------- | | | | --- | --- | | Description: | Instructs this module to let `<mod_proxy_http>` handle the request | | Syntax: | ``` ProxyWebsocketFallbackToProxyHttp On|Off ``` | | Default: | ``` ProxyWebsocketFallbackToProxyHttp On ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy\_wstunnel | | Compatibility: | Available in httpd 2.4.48 and later | Since httpd 2.4.47, `<mod_proxy_http>` can handle WebSocket upgrading and tunneling in accordance to RFC 7230, this directive controls whether `<mod_proxy_wstunnel>` should hand over to `<mod_proxy_http>` to this, which is the case by default. Setting to *Off* lets `<mod_proxy_wstunnel>` handle WebSocket requests as in httpd 2.4.46 and earlier. apache_http_server Apache Module mod_authz_core Apache Module mod\_authz\_core ============================== | | | | --- | --- | | Description: | Core Authorization | | Status: | Base | | Module Identifier: | authz\_core\_module | | Source File: | mod\_authz\_core.c | | Compatibility: | Available in Apache HTTPD 2.3 and later | ### Summary This module provides core authorization capabilities so that authenticated users can be allowed or denied access to portions of the web site. `<mod_authz_core>` provides the functionality to register various authorization providers. It is usually used in conjunction with an authentication provider module such as `<mod_authn_file>` and an authorization module such as `<mod_authz_user>`. It also allows for advanced logic to be applied to the authorization processing. Authorization Containers ------------------------ The authorization container directives `[<RequireAll>](#requireall)`, `[<RequireAny>](#requireany)` and `[<RequireNone>](#requirenone)` may be combined with each other and with the `[Require](#require)` directive to express complex authorization logic. The example below expresses the following authorization logic. In order to access the resource, the user must either be the `superadmin` user, or belong to both the `admins` group and the `Administrators` LDAP group and either belong to the `sales` group or have the LDAP `dept` attribute `sales`. Furthermore, in order to access the resource, the user must not belong to either the `temps` group or the LDAP group `Temporary Employees`. ``` <Directory "/www/mydocs"> <RequireAll> <RequireAny> Require user superadmin <RequireAll> Require group admins Require ldap-group "cn=Administrators,o=Airius" <RequireAny> Require group sales Require ldap-attribute dept="sales" </RequireAny> </RequireAll> </RequireAny> <RequireNone> Require group temps Require ldap-group "cn=Temporary Employees,o=Airius" </RequireNone> </RequireAll> </Directory> ``` The Require Directives ---------------------- `<mod_authz_core>` provides some generic authorization providers which can be used with the `[Require](#require)` directive. ### Require env The `env` provider allows access to the server to be controlled based on the existence of an [environment variable](../env). When `Require env env-variable` is specified, then the request is allowed access if the environment variable env-variable exists. The server provides the ability to set environment variables in a flexible way based on characteristics of the client request using the directives provided by `<mod_setenvif>`. Therefore, this directive can be used to allow access based on such factors as the clients `User-Agent` (browser type), `Referer`, or other HTTP request header fields. ``` SetEnvIf User-Agent "^KnockKnock/2\.0" let_me_in <Directory "/docroot"> Require env let_me_in </Directory> ``` In this case, browsers with a user-agent string beginning with `KnockKnock/2.0` will be allowed access, and all others will be denied. When the server looks up a path via an internal [subrequest](https://httpd.apache.org/docs/2.4/en/glossary.html#subrequest "see glossary") such as looking for a `[DirectoryIndex](mod_dir#directoryindex)` or generating a directory listing with `<mod_autoindex>`, per-request environment variables are *not* inherited in the subrequest. Additionally, `[SetEnvIf](mod_setenvif#setenvif)` directives are not separately evaluated in the subrequest due to the API phases `<mod_setenvif>` takes action in. ### Require all The `all` provider mimics the functionality that was previously provided by the 'Allow from all' and 'Deny from all' directives. This provider can take one of two arguments which are 'granted' or 'denied'. The following examples will grant or deny access to all requests. ``` Require all granted ``` ``` Require all denied ``` ### Require method The `method` provider allows using the HTTP method in authorization decisions. The GET and HEAD methods are treated as equivalent. The TRACE method is not available to this provider, use `[TraceEnable](core#traceenable)` instead. The following example will only allow GET, HEAD, POST, and OPTIONS requests: ``` Require method GET POST OPTIONS ``` The following example will allow GET, HEAD, POST, and OPTIONS requests without authentication, and require a valid user for all other methods: ``` <RequireAny>  Require method GET POST OPTIONS  Require valid-user </RequireAny> ``` ### Require expr The `expr` provider allows basing authorization decisions on arbitrary expressions. ``` Require expr "%{TIME_HOUR} -ge 9 && %{TIME_HOUR} -le 17" ``` ``` <RequireAll> Require expr "!(%{QUERY_STRING} =~ /secret/)" Require expr "%{REQUEST_URI} in { '/example.cgi', '/other.cgi' }" </RequireAll> ``` ``` Require expr "!(%{QUERY_STRING} =~ /secret/) && %{REQUEST_URI} in { '/example.cgi', '/other.cgi' }" ``` The syntax is described in the [ap\_expr](../expr) documentation. Before httpd 2.4.16, the surrounding double-quotes MUST be omitted. Normally, the expression is evaluated before authentication. However, if the expression returns false and references the variable `%{REMOTE_USER}`, authentication will be performed and the expression will be re-evaluated. Creating Authorization Provider Aliases --------------------------------------- Extended authorization providers can be created within the configuration file and assigned an alias name. The alias providers can then be referenced through the `[Require](#require)` directive in the same way as a base authorization provider. Besides the ability to create and alias an extended provider, it also allows the same extended authorization provider to be referenced by multiple locations. ### Example The example below creates two different ldap authorization provider aliases based on the ldap-group authorization provider. This example allows a single authorization location to check group membership within multiple ldap hosts: ``` <AuthzProviderAlias ldap-group ldap-group-alias1 "cn=my-group,o=ctx"> AuthLDAPBindDN "cn=youruser,o=ctx" AuthLDAPBindPassword yourpassword AuthLDAPUrl "ldap://ldap.host/o=ctx" </AuthzProviderAlias> <AuthzProviderAlias ldap-group ldap-group-alias2 "cn=my-other-group,o=dev"> AuthLDAPBindDN "cn=yourotheruser,o=dev" AuthLDAPBindPassword yourotherpassword AuthLDAPUrl "ldap://other.ldap.host/o=dev?cn" </AuthzProviderAlias> Alias "/secure" "/webpages/secure" <Directory "/webpages/secure"> Require all granted AuthBasicProvider file AuthType Basic AuthName LDAP_Protected_Place #implied OR operation Require ldap-group-alias1 Require ldap-group-alias2 </Directory> ``` AuthMerging Directive --------------------- | | | | --- | --- | | Description: | Controls the manner in which each configuration section's authorization logic is combined with that of preceding configuration sections. | | Syntax: | ``` AuthMerging Off | And | Or ``` | | Default: | ``` AuthMerging Off ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_authz\_core | When authorization is enabled, it is normally inherited by each subsequent [configuration section](../sections#merging), unless a different set of authorization directives is specified. This is the default action, which corresponds to an explicit setting of `AuthMerging Off`. However, there may be circumstances in which it is desirable for a configuration section's authorization to be combined with that of its predecessor while configuration sections are being merged. Two options are available for this case, `And` and `Or`. When a configuration section contains `AuthMerging And` or `AuthMerging Or`, its authorization logic is combined with that of the nearest predecessor (according to the overall order of configuration sections) which also contains authorization logic as if the two sections were jointly contained within a `[<RequireAll>](#requireall)` or `[<RequireAny>](#requireany)` directive, respectively. The setting of `AuthMerging` is not inherited outside of the configuration section in which it appears. In the following example, only users belonging to group `alpha` may access `/www/docs`. Users belonging to either groups `alpha` or `beta` may access `/www/docs/ab`. However, the default `Off` setting of `AuthMerging` applies to the `[<Directory>](core#directory)` configuration section for `/www/docs/ab/gamma`, so that section's authorization directives override those of the preceding sections. Thus only users belong to the group `gamma` may access `/www/docs/ab/gamma`. ``` <Directory "/www/docs"> AuthType Basic AuthName Documents AuthBasicProvider file AuthUserFile "/usr/local/apache/passwd/passwords" Require group alpha </Directory> <Directory "/www/docs/ab"> AuthMerging Or Require group beta </Directory> <Directory "/www/docs/ab/gamma"> Require group gamma </Directory> ``` <AuthzProviderAlias> Directive ------------------------------ | | | | --- | --- | | Description: | Enclose a group of directives that represent an extension of a base authorization provider and referenced by the specified alias | | Syntax: | ``` <AuthzProviderAlias baseProvider Alias Require-Parameters> ... </AuthzProviderAlias> ``` | | Context: | server config | | Status: | Base | | Module: | mod\_authz\_core | `<AuthzProviderAlias>` and `</AuthzProviderAlias>` are used to enclose a group of authorization directives that can be referenced by the alias name using the directive `[Require](#require)`. If several parameters are needed in Require-Parameters, they must be enclosed in quotation marks. Otherwise, only the first one is taken into account. ``` # In this example, for both addresses to be taken into account, they MUST be enclosed # between quotation marks <AuthzProviderAlias ip reject-ips "XXX.XXX.XXX.XXX YYY.YYY.YYY.YYY"> </AuthzProviderAlias> <Directory "/path/to/dir"> <RequireAll> Require not reject-ips Require all granted </RequireAll> </Directory> ``` AuthzSendForbiddenOnFailure Directive ------------------------------------- | | | | --- | --- | | Description: | Send '403 FORBIDDEN' instead of '401 UNAUTHORIZED' if authentication succeeds but authorization fails | | Syntax: | ``` AuthzSendForbiddenOnFailure On|Off ``` | | Default: | ``` AuthzSendForbiddenOnFailure Off ``` | | Context: | directory, .htaccess | | Status: | Base | | Module: | mod\_authz\_core | | Compatibility: | Available in Apache HTTPD 2.3.11 and later | If authentication succeeds but authorization fails, Apache HTTPD will respond with an HTTP response code of '401 UNAUTHORIZED' by default. This usually causes browsers to display the password dialogue to the user again, which is not wanted in all situations. `AuthzSendForbiddenOnFailure` allows to change the response code to '403 FORBIDDEN'. **Security Warning** Modifying the response in case of missing authorization weakens the security of the password, because it reveals to a possible attacker, that his guessed password was right. Require Directive ----------------- | | | | --- | --- | | Description: | Tests whether an authenticated user is authorized by an authorization provider. | | Syntax: | ``` Require [not] entity-name [entity-name] ... ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_authz\_core | This directive tests whether an authenticated user is authorized according to a particular authorization provider and the specified restrictions. `<mod_authz_core>` provides the following generic authorization providers: `Require all granted` Access is allowed unconditionally. `Require all denied` Access is denied unconditionally. `Require env env-var [env-var] ...` Access is allowed only if one of the given environment variables is set. `Require method http-method [http-method] ...` Access is allowed only for the given HTTP methods. `Require expr expression` Access is allowed if expression evaluates to true. Some of the allowed syntaxes provided by `<mod_authz_user>`, `<mod_authz_host>`, and `<mod_authz_groupfile>` are: `Require user userid [userid] ...` Only the named users can access the resource. `Require group group-name [group-name] ...` Only users in the named groups can access the resource. `Require valid-user` All valid users can access the resource. `Require ip 10 172.20 192.168.2` Clients in the specified IP address ranges can access the resource. `Require forward-dns dynamic.example.org` A client the IP of which is resolved from the name dynamic.example.org will be granted access. Other authorization modules that implement require options include `<mod_authnz_ldap>`, `<mod_authz_dbm>`, `<mod_authz_dbd>`, `<mod_authz_owner>` and `<mod_ssl>`. In most cases, for a complete authentication and authorization configuration, `Require` must be accompanied by `[AuthName](mod_authn_core#authname)`, `[AuthType](mod_authn_core#authtype)` and `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` or `[AuthDigestProvider](mod_auth_digest#authdigestprovider)` directives, and directives such as `[AuthUserFile](mod_authn_file#authuserfile)` and `[AuthGroupFile](mod_authz_groupfile#authgroupfile)` (to define users and groups) in order to work correctly. Example: ``` AuthType Basic AuthName "Restricted Resource" AuthBasicProvider file AuthUserFile "/web/users" AuthGroupFile "/web/groups" Require group admin ``` Access controls which are applied in this way are effective for **all** methods. **This is what is normally desired.** If you wish to apply access controls only to specific methods, while leaving other methods unprotected, then place the `Require` statement into a `[<Limit>](core#limit)` section. The result of the `Require` directive may be negated through the use of the `not` option. As with the other negated authorization directive `<RequireNone>`, when the `Require` directive is negated it can only fail or return a neutral result, and therefore may never independently authorize a request. In the following example, all users in the `alpha` and `beta` groups are authorized, except for those who are also in the `reject` group. ``` <Directory "/www/docs"> <RequireAll> Require group alpha beta Require not group reject </RequireAll> </Directory> ``` When multiple `Require` directives are used in a single [configuration section](../sections#merging) and are not contained in another authorization directive like `[<RequireAll>](#requireall)`, they are implicitly contained within a `[<RequireAny>](#requireany)` directive. Thus the first one to authorize a user authorizes the entire request, and subsequent `Require` directives are ignored. **Security Warning** Exercise caution when setting authorization directives in `[Location](core#location)` sections that overlap with content served out of the filesystem. By default, these [configuration sections](../sections#merging) overwrite authorization configuration in `[Directory](core#directory)`, and `[Files](core#files)` sections. The `[AuthMerging](#authmerging)` directive can be used to control how authorization configuration sections are merged. ### See also * [Access Control howto](../howto/access) * [Authorization Containers](#logic) * `<mod_authn_core>` * `<mod_authz_host>` <RequireAll> Directive ---------------------- | | | | --- | --- | | Description: | Enclose a group of authorization directives of which none must fail and at least one must succeed for the enclosing directive to succeed. | | Syntax: | ``` <RequireAll> ... </RequireAll> ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_authz\_core | `<RequireAll>` and `</RequireAll>` are used to enclose a group of authorization directives of which none must fail and at least one must succeed in order for the `<RequireAll>` directive to succeed. If none of the directives contained within the `<RequireAll>` directive fails, and at least one succeeds, then the `<RequireAll>` directive succeeds. If none succeed and none fail, then it returns a neutral result. In all other cases, it fails. ### See also * [Authorization Containers](#logic) * [Authentication, Authorization, and Access Control](../howto/auth) <RequireAny> Directive ---------------------- | | | | --- | --- | | Description: | Enclose a group of authorization directives of which one must succeed for the enclosing directive to succeed. | | Syntax: | ``` <RequireAny> ... </RequireAny> ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_authz\_core | `<RequireAny>` and `</RequireAny>` are used to enclose a group of authorization directives of which one must succeed in order for the `<RequireAny>` directive to succeed. If one or more of the directives contained within the `<RequireAny>` directive succeed, then the `<RequireAny>` directive succeeds. If none succeed and none fail, then it returns a neutral result. In all other cases, it fails. Because negated authorization directives are unable to return a successful result, they can not significantly influence the result of a `<RequireAny>` directive. (At most they could cause the directive to fail in the case where they failed and all other directives returned a neutral value.) Therefore negated authorization directives are not permitted within a `<RequireAny>` directive. ### See also * [Authorization Containers](#logic) * [Authentication, Authorization, and Access Control](../howto/auth) <RequireNone> Directive ----------------------- | | | | --- | --- | | Description: | Enclose a group of authorization directives of which none must succeed for the enclosing directive to not fail. | | Syntax: | ``` <RequireNone> ... </RequireNone> ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_authz\_core | `<RequireNone>` and `</RequireNone>` are used to enclose a group of authorization directives of which none must succeed in order for the `<RequireNone>` directive to not fail. If one or more of the directives contained within the `<RequireNone>` directive succeed, then the `<RequireNone>` directive fails. In all other cases, it returns a neutral result. Thus as with the other negated authorization directive `Require not`, it can never independently authorize a request because it can never return a successful result. It can be used, however, to restrict the set of users who are authorized to access a resource. Because negated authorization directives are unable to return a successful result, they can not significantly influence the result of a `<RequireNone>` directive. Therefore negated authorization directives are not permitted within a `<RequireNone>` directive. ### See also * [Authorization Containers](#logic) * [Authentication, Authorization, and Access Control](../howto/auth)
programming_docs
apache_http_server Apache Module mod_cache_disk Apache Module mod\_cache\_disk ============================== | | | | --- | --- | | Description: | Disk based storage module for the HTTP caching filter. | | Status: | Extension | | Module Identifier: | cache\_disk\_module | | Source File: | mod\_cache\_disk.c | ### Summary `<mod_cache_disk>` implements a disk based storage manager for `<mod_cache>`. The headers and bodies of cached responses are stored separately on disk, in a directory structure derived from the md5 hash of the cached URL. Multiple content negotiated responses can be stored concurrently, however the caching of partial content is not yet supported by this module. Atomic cache updates to both header and body files are achieved without the need for locking by storing the device and inode numbers of the body file within the header file. This has the side effect that cache entries manually moved into the cache will be ignored. The `[htcacheclean](../programs/htcacheclean)` tool is provided to list cached URLs, remove cached URLs, or to maintain the size of the disk cache within size and/or inode limits. The tool can be run on demand, or can be daemonized to offer continuous monitoring of directory sizes. **Note:** `<mod_cache_disk>` requires the services of `<mod_cache>`, which must be loaded before mod\_cache\_disk. **Note:** `<mod_cache_disk>` uses the sendfile feature to serve files from the cache when supported by the platform, and when enabled with `[EnableSendfile](core#enablesendfile)`. However, per-directory and .htaccess configuration of `[EnableSendfile](core#enablesendfile)` are ignored by `<mod_cache_disk>` as the corresponding settings are not available to the module when a request is being served from the cache. CacheDirLength Directive ------------------------ | | | | --- | --- | | Description: | The number of characters in subdirectory names | | Syntax: | ``` CacheDirLength length ``` | | Default: | ``` CacheDirLength 2 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache\_disk | The `CacheDirLength` directive sets the number of characters for each subdirectory name in the cache hierarchy. It can be used in conjunction with `CacheDirLevels` to determine the approximate structure of your cache hierarchy. A high value for `CacheDirLength` combined with a low value for `CacheDirLevels` will result in a relatively flat hierarchy, with a large number of subdirectories at each level. The result of `[CacheDirLevels](#cachedirlevels)`\* `CacheDirLength` must not be higher than 20. CacheDirLevels Directive ------------------------ | | | | --- | --- | | Description: | The number of levels of subdirectories in the cache. | | Syntax: | ``` CacheDirLevels levels ``` | | Default: | ``` CacheDirLevels 2 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache\_disk | The `CacheDirLevels` directive sets the number of subdirectory levels in the cache. Cached data will be saved this many directory levels below the `[CacheRoot](#cacheroot)` directory. A high value for `CacheDirLevels` combined with a low value for `CacheDirLength` will result in a relatively deep hierarchy, with a small number of subdirectories at each level. The result of `CacheDirLevels`\* `[CacheDirLength](#cachedirlength)` must not be higher than 20. CacheMaxFileSize Directive -------------------------- | | | | --- | --- | | Description: | The maximum size (in bytes) of a document to be placed in the cache | | Syntax: | ``` CacheMaxFileSize bytes ``` | | Default: | ``` CacheMaxFileSize 1000000 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache\_disk | The `CacheMaxFileSize` directive sets the maximum size, in bytes, for a document to be considered for storage in the cache. ``` CacheMaxFileSize 64000 ``` CacheMinFileSize Directive -------------------------- | | | | --- | --- | | Description: | The minimum size (in bytes) of a document to be placed in the cache | | Syntax: | ``` CacheMinFileSize bytes ``` | | Default: | ``` CacheMinFileSize 1 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache\_disk | The `CacheMinFileSize` directive sets the minimum size, in bytes, for a document to be considered for storage in the cache. ``` CacheMinFileSize 64 ``` CacheReadSize Directive ----------------------- | | | | --- | --- | | Description: | The minimum size (in bytes) of the document to read and be cached before sending the data downstream | | Syntax: | ``` CacheReadSize bytes ``` | | Default: | ``` CacheReadSize 0 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache\_disk | The `CacheReadSize` directive sets the minimum amount of data, in bytes, to be read from the backend before the data is sent to the client. The default of zero causes all data read of any size to be passed downstream to the client immediately as it arrives. Setting this to a higher value causes the disk cache to buffer at least this amount before sending the result to the client. This can improve performance when caching content from a reverse proxy. This directive only takes effect when the data is being saved to the cache, as opposed to data being served from the cache. ``` CacheReadSize 102400 ``` CacheReadTime Directive ----------------------- | | | | --- | --- | | Description: | The minimum time (in milliseconds) that should elapse while reading before data is sent downstream | | Syntax: | ``` CacheReadTime milliseconds ``` | | Default: | ``` CacheReadTime 0 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache\_disk | The `CacheReadTime` directive sets the minimum amount of elapsed time that should pass before making an attempt to send data downstream to the client. During the time period, data will be buffered before sending the result to the client. This can improve performance when caching content from a reverse proxy. The default of zero disables this option. This directive only takes effect when the data is being saved to the cache, as opposed to data being served from the cache. It is recommended that this option be used alongside the `[CacheReadSize](#cachereadsize)` directive to ensure that the server does not buffer excessively should data arrive faster than expected. ``` CacheReadTime 1000 ``` CacheRoot Directive ------------------- | | | | --- | --- | | Description: | The directory root under which cache files are stored | | Syntax: | ``` CacheRoot directory ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache\_disk | The `CacheRoot` directive defines the name of the directory on the disk to contain cache files. If the `<mod_cache_disk>` module has been loaded or compiled in to the Apache server, this directive *must* be defined. Failing to provide a value for `CacheRoot` will result in a configuration file processing error. The `[CacheDirLevels](#cachedirlevels)` and `[CacheDirLength](#cachedirlength)` directives define the structure of the directories under the specified root directory. ``` CacheRoot c:/cacheroot ``` apache_http_server Apache Module mod_cache Apache Module mod\_cache ======================== | | | | --- | --- | | Description: | RFC 2616 compliant HTTP caching filter. | | Status: | Extension | | Module Identifier: | cache\_module | | Source File: | mod\_cache.c | ### Summary This module should be used with care, as when the `[CacheQuickHandler](#cachequickhandler)` directive is in its default value of **on**, the `[Allow](mod_access_compat#allow)` and `[Deny](mod_access_compat#deny)` directives will be circumvented. You should not enable quick handler caching for any content to which you wish to limit access by client host name, address or environment variable. `<mod_cache>` implements an [RFC 2616](http://www.ietf.org/rfc/rfc2616.txt) compliant **HTTP content caching filter**, with support for the caching of content negotiated responses containing the Vary header. RFC 2616 compliant caching provides a mechanism to verify whether stale or expired content is still fresh, and can represent a significant performance boost when the origin server supports **conditional requests** by honouring the [If-None-Match](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26) HTTP request header. Content is only regenerated from scratch when the content has changed, and not when the cached entry expires. As a filter, `<mod_cache>` can be placed in front of content originating from any handler, including **flat files** (served from a slow disk cached on a fast disk), the output of a **CGI script** or **dynamic content generator**, or content **proxied from another server**. In the default configuration, `<mod_cache>` inserts the caching filter as far forward as possible within the filter stack, utilising the **quick handler** to bypass all per request processing when returning content to the client. In this mode of operation, `<mod_cache>` may be thought of as a caching proxy server bolted to the front of the webserver, while running within the webserver itself. When the quick handler is switched off using the `[CacheQuickHandler](#cachequickhandler)` directive, it becomes possible to insert the **CACHE** filter at a point in the filter stack chosen by the administrator. This provides the opportunity to cache content before that content is personalised by the `<mod_include>` filter, or optionally compressed by the `<mod_deflate>` filter. Under normal operation, `<mod_cache>` will respond to and can be controlled by the [Cache-Control](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9) and [Pragma](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32) headers sent from a client in a request, or from a server within a response. Under exceptional circumstances, `<mod_cache>` can be configured to override these headers and force site specific behaviour, however such behaviour will be limited to this cache only, and will not affect the operation of other caches that may exist between the client and server, and as a result is not recommended unless strictly necessary. RFC 2616 allows for the cache to return stale data while the existing stale entry is refreshed from the origin server, and this is supported by `<mod_cache>` when the `[CacheLock](#cachelock)` directive is suitably configured. Such responses will contain a [Warning](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46) HTTP header with a 110 response code. RFC 2616 also allows a cache to return stale data when the attempt made to refresh the stale data returns an error 500 or above, and this behaviour is supported by default by `<mod_cache>`. Such responses will contain a [Warning](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.46) HTTP header with a 111 response code. `<mod_cache>` requires the services of one or more storage management modules. The following storage management modules are included in the base Apache distribution: `<mod_cache_disk>` Implements a disk based storage manager. Headers and bodies are stored separately on disk, in a directory structure derived from the md5 hash of the cached URL. Multiple content negotiated responses can be stored concurrently, however the caching of partial content is not supported by this module. The `[htcacheclean](../programs/htcacheclean)` tool is provided to list cached URLs, remove cached URLs, or to maintain the size of the disk cache within size and inode limits. `<mod_cache_socache>` Implements a shared object cache based storage manager. Headers and bodies are stored together beneath a single key based on the URL of the response being cached. Multiple content negotiated responses can be stored concurrently, however the caching of partial content is not supported by this module. Further details, discussion, and examples, are provided in the [Caching Guide](../caching). Related Modules and Directives ------------------------------ | Related Modules | Related Directives | | --- | --- | | * `<mod_cache_disk>` * `<mod_cache_socache>` | * `[CacheRoot](mod_cache_disk#cacheroot)` * `[CacheDirLevels](mod_cache_disk#cachedirlevels)` * `[CacheDirLength](mod_cache_disk#cachedirlength)` * `[CacheMinFileSize](mod_cache_disk#cacheminfilesize)` * `[CacheMaxFileSize](mod_cache_disk#cachemaxfilesize)` * `[CacheSocache](mod_cache_socache#cachesocache)` * `[CacheSocacheMaxTime](mod_cache_socache#cachesocachemaxtime)` * `[CacheSocacheMinTime](mod_cache_socache#cachesocachemintime)` * `[CacheSocacheMaxSize](mod_cache_socache#cachesocachemaxsize)` * `[CacheSocacheReadSize](mod_cache_socache#cachesocachereadsize)` * `[CacheSocacheReadTime](mod_cache_socache#cachesocachereadtime)` | Sample Configuration -------------------- ### Sample httpd.conf ``` # # Sample Cache Configuration # LoadModule cache_module modules/mod_cache.so <IfModule mod_cache.c> LoadModule cache_disk_module modules/mod_cache_disk.so <IfModule mod_cache_disk.c> CacheRoot "c:/cacheroot" CacheEnable disk "/" CacheDirLevels 5 CacheDirLength 3 </IfModule> # When acting as a proxy, don't cache the list of security updates CacheDisable "http://security.update.server/update-list/" </IfModule> ``` Avoiding the Thundering Herd ---------------------------- When a cached entry becomes stale, `<mod_cache>` will submit a conditional request to the backend, which is expected to confirm whether the cached entry is still fresh, and send an updated entity if not. A small but finite amount of time exists between the time the cached entity becomes stale, and the time the stale entity is fully refreshed. On a busy server, a significant number of requests might arrive during this time, and cause a **thundering herd** of requests to strike the backend suddenly and unpredictably. To keep the thundering herd at bay, the `[CacheLock](#cachelock)` directive can be used to define a directory in which locks are created for URLs **in flight**. The lock is used as a **hint** by other requests to either suppress an attempt to cache (someone else has gone to fetch the entity), or to indicate that a stale entry is being refreshed (stale content will be returned in the mean time). ### Initial caching of an entry When an entity is cached for the first time, a lock will be created for the entity until the response has been fully cached. During the lifetime of the lock, the cache will suppress the second and subsequent attempt to cache the same entity. While this doesn't hold back the thundering herd, it does stop the cache attempting to cache the same entity multiple times simultaneously. ### Refreshment of a stale entry When an entity reaches its freshness lifetime and becomes stale, a lock will be created for the entity until the response has either been confirmed as still fresh, or replaced by the backend. During the lifetime of the lock, the second and subsequent incoming request will cause stale data to be returned, and the thundering herd is kept at bay. ### Locks and Cache-Control: no-cache Locks are used as a **hint only** to enable the cache to be more gentle on backend servers, however the lock can be overridden if necessary. If the client sends a request with a Cache-Control header forcing a reload, any lock that may be present will be ignored, and the client's request will be honored immediately and the cached entry refreshed. As a further safety mechanism, locks have a configurable maximum age. Once this age has been reached, the lock is removed, and a new request is given the opportunity to create a new lock. This maximum age can be set using the `[CacheLockMaxAge](#cachelockmaxage)` directive, and defaults to 5 seconds. ### Example configuration ### Enabling the cache lock ``` # # Enable the cache lock # <IfModule mod_cache.c> CacheLock on CacheLockPath "/tmp/mod_cache-lock" CacheLockMaxAge 5 </IfModule> ``` Fine Control with the CACHE Filter ---------------------------------- Under the default mode of cache operation, the cache runs as a quick handler, short circuiting the majority of server processing and offering the highest cache performance available. In this mode, the cache **bolts onto** the front of the server, acting as if a free standing RFC 2616 caching proxy had been placed in front of the server. While this mode offers the best performance, the administrator may find that under certain circumstances they may want to perform further processing on the request after the request is cached, such as to inject personalisation into the cached page, or to apply authorization restrictions to the content. Under these circumstances, an administrator is often forced to place independent reverse proxy servers either behind or in front of the caching server to achieve this. To solve this problem the `[CacheQuickHandler](#cachequickhandler)` directive can be set to **off**, and the server will process all phases normally handled by a non-cached request, including the **authentication and authorization** phases. In addition, the administrator may optionally specify the **precise point within the filter chain** where caching is to take place by adding the **CACHE** filter to the output filter chain. For example, to cache content before applying compression to the response, place the **CACHE** filter before the **DEFLATE** filter as in the example below: ``` # Cache content before optional compression CacheQuickHandler off AddOutputFilterByType CACHE;DEFLATE text/plain ``` Another option is to have content cached before personalisation is applied by `<mod_include>` (or another content processing filter). In this example templates containing tags understood by `<mod_include>` are cached before being parsed: ``` # Cache content before mod_include and mod_deflate CacheQuickHandler off AddOutputFilterByType CACHE;INCLUDES;DEFLATE text/html ``` You may place the **CACHE** filter anywhere you wish within the filter chain. In this example, content is cached after being parsed by `<mod_include>`, but before being processed by `<mod_deflate>`: ``` # Cache content between mod_include and mod_deflate CacheQuickHandler off AddOutputFilterByType INCLUDES;CACHE;DEFLATE text/html ``` **Warning:** If the location of the **CACHE** filter in the filter chain is changed for any reason, you may need to **flush your cache** to ensure that your data served remains consistent. `<mod_cache>` is not in a position to enforce this for you. Cache Status and Logging ------------------------ Once `<mod_cache>` has made a decision as to whether or not an entity is to be served from cache, the detailed reason for the decision is written to the subprocess environment within the request under the **cache-status** key. This reason can be logged by the `[LogFormat](mod_log_config#logformat)` directive as follows: ``` LogFormat "%{cache-status}e ..." ``` Based on the caching decision made, the reason is also written to the subprocess environment under one the following four keys, as appropriate: cache-hit The response was served from cache. cache-revalidate The response was stale and was successfully revalidated, then served from cache. cache-miss The response was served from the upstream server. cache-invalidate The cached entity was invalidated by a request method other than GET or HEAD. This makes it possible to support conditional logging of cached requests as per the following example: ``` CustomLog "cached-requests.log" common env=cache-hit CustomLog "uncached-requests.log" common env=cache-miss CustomLog "revalidated-requests.log" common env=cache-revalidate CustomLog "invalidated-requests.log" common env=cache-invalidate ``` For module authors, a hook called cache\_status is available, allowing modules to respond to the caching outcomes above in customised ways. CacheDefaultExpire Directive ---------------------------- | | | | --- | --- | | Description: | The default duration to cache a document when no expiry date is specified. | | Syntax: | ``` CacheDefaultExpire seconds ``` | | Default: | ``` CacheDefaultExpire 3600 (one hour) ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | The `CacheDefaultExpire` directive specifies a default time, in seconds, to cache a document if neither an expiry date nor last-modified date are provided with the document. The value specified with the `[CacheMaxExpire](#cachemaxexpire)` directive does *not* override this setting. ``` CacheDefaultExpire 86400 ``` CacheDetailHeader Directive --------------------------- | | | | --- | --- | | Description: | Add an X-Cache-Detail header to the response. | | Syntax: | ``` CacheDetailHeader on|off ``` | | Default: | ``` CacheDetailHeader off ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | | Compatibility: | Available in Apache 2.3.9 and later | When the `CacheDetailHeader` directive is switched on, an **X-Cache-Detail** header will be added to the response containing the detailed reason for a particular caching decision. It can be useful during development of cached RESTful services to have additional information about the caching decision written to the response headers, so as to confirm whether `Cache-Control` and other headers have been correctly used by the service and client. If the normal handler is used, this directive may appear within a `[<Directory>](core#directory)` or `[<Location>](core#location)` directive. If the quick handler is used, this directive must appear within a server or virtual host context, otherwise the setting will be ignored. ``` # Enable the X-Cache-Detail header CacheDetailHeader on ``` ``` X-Cache-Detail: "conditional cache hit: entity refreshed" from localhost ``` CacheDisable Directive ---------------------- | | | | --- | --- | | Description: | Disable caching of specified URLs | | Syntax: | ``` CacheDisable url-string | on ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | The `CacheDisable` directive instructs `<mod_cache>` to *not* cache urls at or below url-string. ### Example ``` CacheDisable "/local_files" ``` If used in a `[<Location>](core#location)` directive, the path needs to be specified below the Location, or if the word "on" is used, caching for the whole location will be disabled. ### Example ``` <Location "/foo"> CacheDisable on </Location> ``` The `no-cache` environment variable can be set to disable caching on a finer grained set of resources in versions 2.2.12 and later. ### See also * [Environment Variables in Apache](../env) CacheEnable Directive --------------------- | | | | --- | --- | | Description: | Enable caching of specified URLs using a specified storage manager | | Syntax: | ``` CacheEnable cache_type [url-string] ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_cache | | Compatibility: | A url-string of '/' applied to forward proxy content in 2.2 and earlier. | The `CacheEnable` directive instructs `<mod_cache>` to cache urls at or below url-string. The cache storage manager is specified with the cache\_type argument. The `CacheEnable` directive can alternatively be placed inside either `[<Location>](core#location)` or `[<LocationMatch>](core#locationmatch)` sections to indicate the content is cacheable. cache\_type `disk` instructs `<mod_cache>` to use the disk based storage manager implemented by `<mod_cache_disk>`. cache\_type `socache` instructs `<mod_cache>` to use the shared object cache based storage manager implemented by `<mod_cache_socache>`. In the event that the URL space overlaps between different `CacheEnable` directives (as in the example below), each possible storage manager will be run until the first one that actually processes the request. The order in which the storage managers are run is determined by the order of the `CacheEnable` directives in the configuration file. `CacheEnable` directives within `[<Location>](core#location)` or `[<LocationMatch>](core#locationmatch)` sections are processed before globally defined `CacheEnable` directives. When acting as a forward proxy server, url-string must minimally begin with a protocol for which caching should be enabled. ``` # Cache content (normal handler only) CacheQuickHandler off <Location "/foo"> CacheEnable disk </Location> # Cache regex (normal handler only) CacheQuickHandler off <LocationMatch "foo$"> CacheEnable disk </LocationMatch> # Cache all but forward proxy url's (normal or quick handler) CacheEnable disk / # Cache FTP-proxied url's (normal or quick handler) CacheEnable disk ftp:// # Cache forward proxy content from www.example.org (normal or quick handler) CacheEnable disk http://www.example.org/ ``` A hostname starting with a **"\*"** matches all hostnames with that suffix. A hostname starting with **"."** matches all hostnames containing the domain components that follow. ``` # Match www.example.org, and fooexample.org CacheEnable disk "http://*example.org/" # Match www.example.org, but not fooexample.org CacheEnable disk "http://.example.org/" ``` The `no-cache` environment variable can be set to disable caching on a finer grained set of resources in versions 2.2.12 and later. ### See also * [Environment Variables in Apache](../env) CacheHeader Directive --------------------- | | | | --- | --- | | Description: | Add an X-Cache header to the response. | | Syntax: | ``` CacheHeader on|off ``` | | Default: | ``` CacheHeader off ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | | Compatibility: | Available in Apache 2.3.9 and later | When the `CacheHeader` directive is switched on, an **X-Cache** header will be added to the response with the cache status of this response. If the normal handler is used, this directive may appear within a `[<Directory>](core#directory)` or `[<Location>](core#location)` directive. If the quick handler is used, this directive must appear within a server or virtual host context, otherwise the setting will be ignored. **HIT** The entity was fresh, and was served from cache. **REVALIDATE** The entity was stale, was successfully revalidated and was served from cache. **MISS** The entity was fetched from the upstream server and was not served from cache. ``` # Enable the X-Cache header CacheHeader on ``` ``` X-Cache: HIT from localhost ``` CacheIgnoreCacheControl Directive --------------------------------- | | | | --- | --- | | Description: | Ignore request to not serve cached content to client | | Syntax: | ``` CacheIgnoreCacheControl On|Off ``` | | Default: | ``` CacheIgnoreCacheControl Off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache | Ordinarily, requests containing a `Cache-Control: no-cache` or Pragma: no-cache header value will not be served from the cache. The `CacheIgnoreCacheControl` directive allows this behavior to be overridden. `CacheIgnoreCacheControl On` tells the server to attempt to serve the resource from the cache even if the request contains no-cache header values. Resources requiring authorization will *never* be cached. ``` CacheIgnoreCacheControl On ``` **Warning:** This directive will allow serving from the cache even if the client has requested that the document not be served from the cache. This might result in stale content being served. ### See also * `[CacheStorePrivate](#cachestoreprivate)` * `[CacheStoreNoStore](#cachestorenostore)` CacheIgnoreHeaders Directive ---------------------------- | | | | --- | --- | | Description: | Do not store the given HTTP header(s) in the cache. | | Syntax: | ``` CacheIgnoreHeaders header-string [header-string] ... ``` | | Default: | ``` CacheIgnoreHeaders None ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache | According to RFC 2616, hop-by-hop HTTP headers are not stored in the cache. The following HTTP headers are hop-by-hop headers and thus do not get stored in the cache in *any* case regardless of the setting of `CacheIgnoreHeaders`: * `Connection` * `Keep-Alive` * `Proxy-Authenticate` * `Proxy-Authorization` * `TE` * `Trailers` * `Transfer-Encoding` * `Upgrade` `CacheIgnoreHeaders` specifies additional HTTP headers that should not to be stored in the cache. For example, it makes sense in some cases to prevent cookies from being stored in the cache. `CacheIgnoreHeaders` takes a space separated list of HTTP headers that should not be stored in the cache. If only hop-by-hop headers not should be stored in the cache (the RFC 2616 compliant behaviour), `CacheIgnoreHeaders` can be set to `None`. ### Example 1 ``` CacheIgnoreHeaders Set-Cookie ``` ### Example 2 ``` CacheIgnoreHeaders None ``` **Warning:** If headers like `Expires` which are needed for proper cache management are not stored due to a `CacheIgnoreHeaders` setting, the behaviour of mod\_cache is undefined. CacheIgnoreNoLastMod Directive ------------------------------ | | | | --- | --- | | Description: | Ignore the fact that a response has no Last Modified header. | | Syntax: | ``` CacheIgnoreNoLastMod On|Off ``` | | Default: | ``` CacheIgnoreNoLastMod Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | Ordinarily, documents without a last-modified date are not cached. Under some circumstances the last-modified date is removed (during `<mod_include>` processing for example) or not provided at all. The `CacheIgnoreNoLastMod` directive provides a way to specify that documents without last-modified dates should be considered for caching, even without a last-modified date. If neither a last-modified date nor an expiry date are provided with the document then the value specified by the `[CacheDefaultExpire](#cachedefaultexpire)` directive will be used to generate an expiration date. ``` CacheIgnoreNoLastMod On ``` CacheIgnoreQueryString Directive -------------------------------- | | | | --- | --- | | Description: | Ignore query string when caching | | Syntax: | ``` CacheIgnoreQueryString On|Off ``` | | Default: | ``` CacheIgnoreQueryString Off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache | Ordinarily, requests with query string parameters are cached separately for each unique query string. This is according to RFC 2616/13.9 done only if an expiration time is specified. The `CacheIgnoreQueryString` directive tells the cache to cache requests even if no expiration time is specified, and to reply with a cached reply even if the query string differs. From a caching point of view the request is treated as if having no query string when this directive is enabled. ``` CacheIgnoreQueryString On ``` CacheIgnoreURLSessionIdentifiers Directive ------------------------------------------ | | | | --- | --- | | Description: | Ignore defined session identifiers encoded in the URL when caching | | Syntax: | ``` CacheIgnoreURLSessionIdentifiers identifier [identifier] ... ``` | | Default: | ``` CacheIgnoreURLSessionIdentifiers None ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache | Sometimes applications encode the session identifier into the URL like in the following Examples: * `/someapplication/image.gif;jsessionid=123456789` * `/someapplication/image.gif?PHPSESSIONID=12345678` This causes cacheable resources to be stored separately for each session, which is often not desired. `CacheIgnoreURLSessionIdentifiers` lets define a list of identifiers that are removed from the key that is used to identify an entity in the cache, such that cacheable resources are not stored separately for each session. `CacheIgnoreURLSessionIdentifiers None` clears the list of ignored identifiers. Otherwise, each identifier is added to the list. ### Example 1 ``` CacheIgnoreURLSessionIdentifiers jsessionid ``` ### Example 2 ``` CacheIgnoreURLSessionIdentifiers None ``` CacheKeyBaseURL Directive ------------------------- | | | | --- | --- | | Description: | Override the base URL of reverse proxied cache keys. | | Syntax: | ``` CacheKeyBaseURL URL ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache | | Compatibility: | Available in Apache 2.3.9 and later | When the `CacheKeyBaseURL` directive is specified, the URL provided will be used as the base URL to calculate the URL of the cache keys in the reverse proxy configuration. When not specified, the scheme, hostname and port of the current virtual host is used to construct the cache key. When a cluster of machines is present, and all cached entries should be cached beneath the same cache key, a new base URL can be specified with this directive. ``` # Override the base URL of the cache key. CacheKeyBaseURL "http://www.example.com/" ``` Take care when setting this directive. If two separate virtual hosts are accidentally given the same base URL, entries from one virtual host will be served to the other. CacheLastModifiedFactor Directive --------------------------------- | | | | --- | --- | | Description: | The factor used to compute an expiry date based on the LastModified date. | | Syntax: | ``` CacheLastModifiedFactor float ``` | | Default: | ``` CacheLastModifiedFactor 0.1 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | In the event that a document does not provide an expiry date but does provide a last-modified date, an expiry date can be calculated based on the time since the document was last modified. The `CacheLastModifiedFactor` directive specifies a factor to be used in the generation of this expiry date according to the following formula: `expiry-period = time-since-last-modified-date * factor expiry-date = current-date + expiry-period` For example, if the document was last modified 10 hours ago, and factor is 0.1 then the expiry-period will be set to 10\*0.1 = 1 hour. If the current time was 3:00pm then the computed expiry-date would be 3:00pm + 1hour = 4:00pm. If the expiry-period would be longer than that set by `[CacheMaxExpire](#cachemaxexpire)`, then the latter takes precedence. ``` CacheLastModifiedFactor 0.5 ``` CacheLock Directive ------------------- | | | | --- | --- | | Description: | Enable the thundering herd lock. | | Syntax: | ``` CacheLock on|off ``` | | Default: | ``` CacheLock off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache | | Compatibility: | Available in Apache 2.2.15 and later | The `CacheLock` directive enables the thundering herd lock for the given URL space. In a minimal configuration the following directive is all that is needed to enable the thundering herd lock in the default system temp directory. ``` # Enable cache lock CacheLock on ``` CacheLockMaxAge Directive ------------------------- | | | | --- | --- | | Description: | Set the maximum possible age of a cache lock. | | Syntax: | ``` CacheLockMaxAge integer ``` | | Default: | ``` CacheLockMaxAge 5 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache | The `CacheLockMaxAge` directive specifies the maximum age of any cache lock. A lock older than this value in seconds will be ignored, and the next incoming request will be given the opportunity to re-establish the lock. This mechanism prevents a slow client taking an excessively long time to refresh an entity. CacheLockPath Directive ----------------------- | | | | --- | --- | | Description: | Set the lock path directory. | | Syntax: | ``` CacheLockPath directory ``` | | Default: | ``` CacheLockPath /tmp/mod_cache-lock ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache | The `CacheLockPath` directive allows you to specify the directory in which the locks are created. By default, the system's temporary folder is used. Locks consist of empty files that only exist for stale URLs in flight, so is significantly less resource intensive than the traditional disk cache. CacheMaxExpire Directive ------------------------ | | | | --- | --- | | Description: | The maximum time in seconds to cache a document | | Syntax: | ``` CacheMaxExpire seconds ``` | | Default: | ``` CacheMaxExpire 86400 (one day) ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | The `CacheMaxExpire` directive specifies the maximum number of seconds for which cacheable HTTP documents will be retained without checking the origin server. Thus, documents will be out of date at most this number of seconds. This maximum value is enforced even if an expiry date was supplied with the document. ``` CacheMaxExpire 604800 ``` CacheMinExpire Directive ------------------------ | | | | --- | --- | | Description: | The minimum time in seconds to cache a document | | Syntax: | ``` CacheMinExpire seconds ``` | | Default: | ``` CacheMinExpire 0 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | The `CacheMinExpire` directive specifies the minimum number of seconds for which cacheable HTTP documents will be retained without checking the origin server. This is only used if no valid expire time was supplied with the document. ``` CacheMinExpire 3600 ``` CacheQuickHandler Directive --------------------------- | | | | --- | --- | | Description: | Run the cache from the quick handler. | | Syntax: | ``` CacheQuickHandler on|off ``` | | Default: | ``` CacheQuickHandler on ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache | | Compatibility: | Apache HTTP Server 2.3.3 and later | The `CacheQuickHandler` directive controls the phase in which the cache is handled. In the default enabled configuration, the cache operates within the quick handler phase. This phase short circuits the majority of server processing, and represents the most performant mode of operation for a typical server. The cache **bolts onto** the front of the server, and the majority of server processing is avoided. When disabled, the cache operates as a normal handler, and is subject to the full set of phases when handling a server request. While this mode is slower than the default, it allows the cache to be used in cases where full processing is required, such as when content is subject to authorization. ``` # Run cache as a normal handler CacheQuickHandler off ``` It is also possible, when the quick handler is disabled, for the administrator to choose the precise location within the filter chain where caching is to be performed, by adding the **CACHE** filter to the chain. ``` # Cache content before mod_include and mod_deflate CacheQuickHandler off AddOutputFilterByType CACHE;INCLUDES;DEFLATE text/html ``` If the CACHE filter is specified more than once, the last instance will apply. CacheStaleOnError Directive --------------------------- | | | | --- | --- | | Description: | Serve stale content in place of 5xx responses. | | Syntax: | ``` CacheStaleOnError on|off ``` | | Default: | ``` CacheStaleOnError on ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | | Compatibility: | Available in Apache 2.3.9 and later | When the `CacheStaleOnError` directive is switched on, and when stale data is available in the cache, the cache will respond to 5xx responses from the backend by returning the stale data instead of the 5xx response. While the Cache-Control headers sent by clients will be respected, and the raw 5xx responses returned to the client on request, the 5xx response so returned to the client will not invalidate the content in the cache. ``` # Serve stale data on error. CacheStaleOnError on ``` CacheStoreExpired Directive --------------------------- | | | | --- | --- | | Description: | Attempt to cache responses that the server reports as expired | | Syntax: | ``` CacheStoreExpired On|Off ``` | | Default: | ``` CacheStoreExpired Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | Since httpd 2.2.4, responses which have already expired are not stored in the cache. The `CacheStoreExpired` directive allows this behavior to be overridden. `CacheStoreExpired` On tells the server to attempt to cache the resource if it is stale. Subsequent requests would trigger an If-Modified-Since request of the origin server, and the response may be fulfilled from cache if the backend resource has not changed. ``` CacheStoreExpired On ``` CacheStoreNoStore Directive --------------------------- | | | | --- | --- | | Description: | Attempt to cache requests or responses that have been marked as no-store. | | Syntax: | ``` CacheStoreNoStore On|Off ``` | | Default: | ``` CacheStoreNoStore Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | Ordinarily, requests or responses with `Cache-Control: no-store` header values will not be stored in the cache. The `CacheStoreNoStore` directive allows this behavior to be overridden. `CacheStoreNoStore` On tells the server to attempt to cache the resource even if it contains no-store header values. Resources requiring authorization will *never* be cached. ``` CacheStoreNoStore On ``` **Warning:** As described in RFC 2616, the no-store directive is intended to "prevent the inadvertent release or retention of sensitive information (for example, on backup tapes)." Enabling this option could store sensitive information in the cache. You are hereby warned. ### See also * `[CacheIgnoreCacheControl](#cacheignorecachecontrol)` * `[CacheStorePrivate](#cachestoreprivate)` CacheStorePrivate Directive --------------------------- | | | | --- | --- | | Description: | Attempt to cache responses that the server has marked as private | | Syntax: | ``` CacheStorePrivate On|Off ``` | | Default: | ``` CacheStorePrivate Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache | Ordinarily, responses with `Cache-Control: private` header values will not be stored in the cache. The `CacheStorePrivate` directive allows this behavior to be overridden. `CacheStorePrivate` On tells the server to attempt to cache the resource even if it contains private header values. Resources requiring authorization will *never* be cached. ``` CacheStorePrivate On ``` **Warning:** This directive will allow caching even if the upstream server has requested that the resource not be cached. This directive is only ideal for a 'private' cache. ### See also * `[CacheIgnoreCacheControl](#cacheignorecachecontrol)` * `[CacheStoreNoStore](#cachestorenostore)`
programming_docs
apache_http_server Apache Module mod_ident Apache Module mod\_ident ======================== | | | | --- | --- | | Description: | RFC 1413 ident lookups | | Status: | Extension | | Module Identifier: | ident\_module | | Source File: | mod\_ident.c | | Compatibility: | Available in Apache 2.1 and later | ### Summary This module queries an [RFC 1413](http://www.ietf.org/rfc/rfc1413.txt) compatible daemon on a remote host to look up the owner of a connection. IdentityCheck Directive ----------------------- | | | | --- | --- | | Description: | Enables logging of the RFC 1413 identity of the remote user | | Syntax: | ``` IdentityCheck On|Off ``` | | Default: | ``` IdentityCheck Off ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_ident | | Compatibility: | Moved out of core in Apache 2.1 | This directive enables [RFC 1413](http://www.ietf.org/rfc/rfc1413.txt)-compliant logging of the remote user name for each connection, where the client machine runs identd or something similar. This information is logged in the access log using the `%...l` [format string](mod_log_config#formats). The information should not be trusted in any way except for rudimentary usage tracking. Note that this can cause serious latency problems accessing your server since every request requires one of these lookups to be performed. When firewalls or proxy servers are involved, each lookup might possibly fail and add a latency duration as defined by the `[IdentityCheckTimeout](#identitychecktimeout)` directive to each hit. So in general this is not very useful on public servers accessible from the Internet. IdentityCheckTimeout Directive ------------------------------ | | | | --- | --- | | Description: | Determines the timeout duration for ident requests | | Syntax: | ``` IdentityCheckTimeout seconds ``` | | Default: | ``` IdentityCheckTimeout 30 ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_ident | This directive specifies the timeout duration of an ident request. The default value of 30 seconds is recommended by [RFC 1413](http://www.ietf.org/rfc/rfc1413.txt), mainly because of possible network latency. However, you may want to adjust the timeout value according to your local network speed. apache_http_server Apache Module mod_authz_dbd Apache Module mod\_authz\_dbd ============================= | | | | --- | --- | | Description: | Group Authorization and Login using SQL | | Status: | Extension | | Module Identifier: | authz\_dbd\_module | | Source File: | mod\_authz\_dbd.c | | Compatibility: | Available in Apache 2.4 and later | ### Summary This module provides authorization capabilities so that authenticated users can be allowed or denied access to portions of the web site by group membership. Similar functionality is provided by `<mod_authz_groupfile>` and `<mod_authz_dbm>`, with the exception that this module queries a SQL database to determine whether a user is a member of a group. This module can also provide database-backed user login/logout capabilities. These are likely to be of most value when used in conjunction with `<mod_authn_dbd>`. This module relies on `<mod_dbd>` to specify the backend database driver and connection parameters, and manage the database connections. The Require Directives ---------------------- Apache's `[Require](mod_authz_core#require)` directives are used during the authorization phase to ensure that a user is allowed to access a resource. mod\_authz\_dbd extends the authorization types with `dbd-group`, `dbd-login` and `dbd-logout`. Since v2.4.8, [expressions](../expr) are supported within the DBD require directives. ### Require dbd-group This directive specifies group membership that is required for the user to gain access. ``` Require dbd-group team AuthzDBDQuery "SELECT group FROM authz WHERE user = %s" ``` ### Require dbd-login This directive specifies a query to be run indicating the user has logged in. ``` Require dbd-login AuthzDBDQuery "UPDATE authn SET login = 'true' WHERE user = %s" ``` ### Require dbd-logout This directive specifies a query to be run indicating the user has logged out. ``` Require dbd-logout AuthzDBDQuery "UPDATE authn SET login = 'false' WHERE user = %s" ``` Database Login -------------- In addition to the standard authorization function of checking group membership, this module can also provide server-side user session management via database-backed login/logout capabilities. Specifically, it can update a user's session status in the database whenever the user visits designated URLs (subject of course to users supplying the necessary credentials). This works by defining two special `[Require](mod_authz_core#require)` types: `Require dbd-login` and `Require dbd-logout`. For usage details, see the configuration example below. Client Login integration ------------------------ Some administrators may wish to implement client-side session management that works in concert with the server-side login/logout capabilities offered by this module, for example, by setting or unsetting an HTTP cookie or other such token when a user logs in or out. To support such integration, `<mod_authz_dbd>` exports an optional hook that will be run whenever a user's status is updated in the database. Other session management modules can then use the hook to implement functions that start and end client-side sessions. Configuration example --------------------- ``` # mod_dbd configuration DBDriver pgsql DBDParams "dbname=apacheauth user=apache pass=xxxxxx" DBDMin 4 DBDKeep 8 DBDMax 20 DBDExptime 300 <Directory "/usr/www/my.site/team-private/"> # mod_authn_core and mod_auth_basic configuration # for mod_authn_dbd AuthType Basic AuthName Team AuthBasicProvider dbd # mod_authn_dbd SQL query to authenticate a logged-in user AuthDBDUserPWQuery \ "SELECT password FROM authn WHERE user = %s AND login = 'true'" # mod_authz_core configuration for mod_authz_dbd Require dbd-group team # mod_authz_dbd configuration AuthzDBDQuery "SELECT group FROM authz WHERE user = %s" # when a user fails to be authenticated or authorized, # invite them to login; this page should provide a link # to /team-private/login.html ErrorDocument 401 "/login-info.html" <Files "login.html"> # don't require user to already be logged in! AuthDBDUserPWQuery "SELECT password FROM authn WHERE user = %s" # dbd-login action executes a statement to log user in Require dbd-login AuthzDBDQuery "UPDATE authn SET login = 'true' WHERE user = %s" # return user to referring page (if any) after # successful login AuthzDBDLoginToReferer On </Files> <Files "logout.html"> # dbd-logout action executes a statement to log user out Require dbd-logout AuthzDBDQuery "UPDATE authn SET login = 'false' WHERE user = %s" </Files> </Directory> ``` AuthzDBDLoginToReferer Directive -------------------------------- | | | | --- | --- | | Description: | Determines whether to redirect the Client to the Referring page on successful login or logout if a `Referer` request header is present | | Syntax: | ``` AuthzDBDLoginToReferer On|Off ``` | | Default: | ``` AuthzDBDLoginToReferer Off ``` | | Context: | directory | | Status: | Extension | | Module: | mod\_authz\_dbd | In conjunction with `Require dbd-login` or `Require dbd-logout`, this provides the option to redirect the client back to the Referring page (the URL in the `Referer` HTTP request header, if present). When there is no `Referer` header, `AuthzDBDLoginToReferer On` will be ignored. AuthzDBDQuery Directive ----------------------- | | | | --- | --- | | Description: | Specify the SQL Query for the required operation | | Syntax: | ``` AuthzDBDQuery query ``` | | Context: | directory | | Status: | Extension | | Module: | mod\_authz\_dbd | The `AuthzDBDQuery` specifies an SQL query to run. The purpose of the query depends on the `[Require](mod_authz_core#require)` directive in effect. * When used with a `Require dbd-group` directive, it specifies a query to look up groups for the current user. This is the standard functionality of other authorization modules such as `<mod_authz_groupfile>` and `<mod_authz_dbm>`. The first column value of each row returned by the query statement should be a string containing a group name. Zero, one, or more rows may be returned. ``` Require dbd-group AuthzDBDQuery "SELECT group FROM groups WHERE user = %s" ``` * When used with a `Require dbd-login` or `Require dbd-logout` directive, it will never deny access, but will instead execute a SQL statement designed to log the user in or out. The user must already be authenticated with `<mod_authn_dbd>`. ``` Require dbd-login AuthzDBDQuery "UPDATE authn SET login = 'true' WHERE user = %s" ``` In all cases, the user's ID will be passed as a single string parameter when the SQL query is executed. It may be referenced within the query statement using a `%s` format specifier. AuthzDBDRedirectQuery Directive ------------------------------- | | | | --- | --- | | Description: | Specify a query to look up a login page for the user | | Syntax: | ``` AuthzDBDRedirectQuery query ``` | | Context: | directory | | Status: | Extension | | Module: | mod\_authz\_dbd | Specifies an optional SQL query to use after successful login (or logout) to redirect the user to a URL, which may be specific to the user. The user's ID will be passed as a single string parameter when the SQL query is executed. It may be referenced within the query statement using a `%s` format specifier. ``` AuthzDBDRedirectQuery "SELECT userpage FROM userpages WHERE user = %s" ``` The first column value of the first row returned by the query statement should be a string containing a URL to which to redirect the client. Subsequent rows will be ignored. If no rows are returned, the client will not be redirected. Note that `AuthzDBDLoginToReferer` takes precedence if both are set. apache_http_server Module Index Module Index ============ Below is a list of all of the modules that come as part of the Apache HTTP Server distribution. See also the complete alphabetical list of [all Apache HTTP Server directives](https://httpd.apache.org/docs/2.4/en/mod/directives.html). Core Features and Multi-Processing Modules ------------------------------------------ <core> Core Apache HTTP Server features that are always available <mpm_common> A collection of directives that are implemented by more than one multi-processing module (MPM) <event> A variant of the `<worker>` MPM with the goal of consuming threads only for connections with active processing <mpm_netware> Multi-Processing Module implementing an exclusively threaded web server optimized for Novell NetWare <mpmt_os2> Hybrid multi-process, multi-threaded MPM for OS/2 <prefork> Implements a non-threaded, pre-forking web server <mpm_winnt> Multi-Processing Module optimized for Windows NT. <worker> Multi-Processing Module implementing a hybrid multi-threaded multi-process web server Other Modules ------------- [A](#A) | [B](#B) | [C](#C) | [D](#D) | [E](#E) | [F](#F) | [H](#H) | [I](#I) | [L](#L) | [M](#M) | [N](#N) | [P](#P) | [R](#R) | [S](#S) | [T](#T) | [U](#U) | [V](#V) | [W](#W) | [X](#X) <mod_access_compat> Group authorizations based on host (name or IP address) <mod_actions> Execute CGI scripts based on media type or request method. <mod_alias> Provides for mapping different parts of the host filesystem in the document tree and for URL redirection <mod_allowmethods> Easily restrict what HTTP methods can be used on the server <mod_asis> Sends files that contain their own HTTP headers <mod_auth_basic> Basic HTTP authentication <mod_auth_digest> User authentication using MD5 Digest Authentication <mod_auth_form> Form authentication <mod_authn_anon> Allows "anonymous" user access to authenticated areas <mod_authn_core> Core Authentication <mod_authn_dbd> User authentication using an SQL database <mod_authn_dbm> User authentication using DBM files <mod_authn_file> User authentication using text files <mod_authn_socache> Manages a cache of authentication credentials to relieve the load on backends <mod_authnz_fcgi> Allows a FastCGI authorizer application to handle Apache httpd authentication and authorization <mod_authnz_ldap> Allows an LDAP directory to be used to store the database for HTTP Basic authentication. <mod_authz_core> Core Authorization <mod_authz_dbd> Group Authorization and Login using SQL <mod_authz_dbm> Group authorization using DBM files <mod_authz_groupfile> Group authorization using plaintext files <mod_authz_host> Group authorizations based on host (name or IP address) <mod_authz_owner> Authorization based on file ownership <mod_authz_user> User Authorization <mod_autoindex> Generates directory indexes, automatically, similar to the Unix `ls` command or the Win32 `dir` shell command <mod_brotli> Compress content via Brotli before it is delivered to the client <mod_buffer> Support for request buffering <mod_cache> RFC 2616 compliant HTTP caching filter. <mod_cache_disk> Disk based storage module for the HTTP caching filter. <mod_cache_socache> Shared object cache (socache) based storage module for the HTTP caching filter. <mod_cern_meta> CERN httpd metafile semantics <mod_cgi> Execution of CGI scripts <mod_cgid> Execution of CGI scripts using an external CGI daemon <mod_charset_lite> Specify character set translation or recoding <mod_data> Convert response body into an RFC2397 data URL <mod_dav> Distributed Authoring and Versioning ([WebDAV](http://www.webdav.org/)) functionality <mod_dav_fs> Filesystem provider for `<mod_dav>` <mod_dav_lock> Generic locking module for `<mod_dav>` <mod_dbd> Manages SQL database connections <mod_deflate> Compress content before it is delivered to the client <mod_dialup> Send static content at a bandwidth rate limit, defined by the various old modem standards <mod_dir> Provides for "trailing slash" redirects and serving directory index files <mod_dumpio> Dumps all I/O to error log as desired. <mod_echo> A simple echo server to illustrate protocol modules <mod_env> Modifies the environment which is passed to CGI scripts and SSI pages <mod_example_hooks> Illustrates the Apache module API <mod_expires> Generation of `Expires` and `Cache-Control` HTTP headers according to user-specified criteria <mod_ext_filter> Pass the response body through an external program before delivery to the client <mod_file_cache> Caches a static list of files in memory <mod_filter> Context-sensitive smart filter configuration module <mod_headers> Customization of HTTP request and response headers <mod_heartbeat> Sends messages with server status to frontend proxy <mod_heartmonitor> Centralized monitor for mod\_heartbeat origin servers <mod_http2> Support for the HTTP/2 transport layer <mod_ident> RFC 1413 ident lookups <mod_imagemap> Server-side imagemap processing <mod_include> Server-parsed html documents (Server Side Includes) <mod_info> Provides a comprehensive overview of the server configuration <mod_isapi> ISAPI Extensions within Apache for Windows <mod_lbmethod_bybusyness> Pending Request Counting load balancer scheduler algorithm for `<mod_proxy_balancer>` <mod_lbmethod_byrequests> Request Counting load balancer scheduler algorithm for `<mod_proxy_balancer>` <mod_lbmethod_bytraffic> Weighted Traffic Counting load balancer scheduler algorithm for `<mod_proxy_balancer>` <mod_lbmethod_heartbeat> Heartbeat Traffic Counting load balancer scheduler algorithm for `<mod_proxy_balancer>` <mod_ldap> LDAP connection pooling and result caching services for use by other LDAP modules <mod_log_config> Logging of the requests made to the server <mod_log_debug> Additional configurable debug logging <mod_log_forensic> Forensic Logging of the requests made to the server <mod_logio> Logging of input and output bytes per request <mod_lua> Provides Lua hooks into various portions of the httpd request processing <mod_macro> Provides macros within apache httpd runtime configuration files <mod_md> Managing domains across virtual hosts, certificate provisioning via the ACME protocol <mod_mime> Associates the requested filename's extensions with the file's behavior (handlers and filters) and content (mime-type, language, character set and encoding) <mod_mime_magic> Determines the MIME type of a file by looking at a few bytes of its contents <mod_negotiation> Provides for [content negotiation](../content-negotiation) <mod_nw_ssl> Enable SSL encryption for NetWare <mod_privileges> Support for Solaris privileges and for running virtual hosts under different user IDs. <mod_proxy> Multi-protocol proxy/gateway server <mod_proxy_ajp> AJP support module for `<mod_proxy>` <mod_proxy_balancer> `<mod_proxy>` extension for load balancing <mod_proxy_connect> `<mod_proxy>` extension for `CONNECT` request handling <mod_proxy_express> Dynamic mass reverse proxy extension for `<mod_proxy>` <mod_proxy_fcgi> FastCGI support module for `<mod_proxy>` <mod_proxy_fdpass> fdpass external process support module for `<mod_proxy>` <mod_proxy_ftp> FTP support module for `<mod_proxy>` <mod_proxy_hcheck> Dynamic health check of Balancer members (workers) for `<mod_proxy>` <mod_proxy_html> Rewrite HTML links in to ensure they are addressable from Clients' networks in a proxy context. <mod_proxy_http> HTTP support module for `<mod_proxy>` <mod_proxy_http2> HTTP/2 support module for `<mod_proxy>` <mod_proxy_scgi> SCGI gateway module for `<mod_proxy>` <mod_proxy_uwsgi> UWSGI gateway module for `<mod_proxy>` <mod_proxy_wstunnel> Websockets support module for `<mod_proxy>` <mod_ratelimit> Bandwidth Rate Limiting for Clients <mod_reflector> Reflect a request body as a response via the output filter stack. <mod_remoteip> Replaces the original client IP address for the connection with the useragent IP address list presented by a proxies or a load balancer via the request headers. <mod_reqtimeout> Set timeout and minimum data rate for receiving requests <mod_request> Filters to handle and make available HTTP request bodies <mod_rewrite> Provides a rule-based rewriting engine to rewrite requested URLs on the fly <mod_sed> Filter Input (request) and Output (response) content using `sed` syntax <mod_session> Session support <mod_session_cookie> Cookie based session support <mod_session_crypto> Session encryption support <mod_session_dbd> DBD/SQL based session support <mod_setenvif> Allows the setting of environment variables based on characteristics of the request <mod_slotmem_plain> Slot-based shared memory provider. <mod_slotmem_shm> Slot-based shared memory provider. <mod_so> Loading of executable code and modules into the server at start-up or restart time <mod_socache_dbm> DBM based shared object cache provider. <mod_socache_dc> Distcache based shared object cache provider. <mod_socache_memcache> Memcache based shared object cache provider. <mod_socache_redis> Redis based shared object cache provider. <mod_socache_shmcb> shmcb based shared object cache provider. <mod_speling> Attempts to correct mistaken URLs by ignoring capitalization, or attempting to correct various minor misspellings. <mod_ssl> Strong cryptography using the Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols <mod_status> Provides information on server activity and performance <mod_substitute> Perform search and replace operations on response bodies <mod_suexec> Allows CGI scripts to run as a specified user and Group <mod_systemd> Provides better support for systemd integration <mod_tls> TLS v1.2 and v1.3 implemented in memory-safe Rust via the rustls library <mod_unique_id> Provides an environment variable with a unique identifier for each request <mod_unixd> Basic (required) security for Unix-family platforms. <mod_userdir> User-specific directories <mod_usertrack> *Clickstream* logging of user activity on a site <mod_version> Version dependent configuration <mod_vhost_alias> Provides for dynamically configured mass virtual hosting <mod_watchdog> provides infrastructure for other modules to periodically run tasks <mod_xml2enc> Enhanced charset/internationalisation support for libxml2-based filter modules
programming_docs
apache_http_server Apache Module mod_proxy_connect Apache Module mod\_proxy\_connect ================================= | | | | --- | --- | | Description: | `<mod_proxy>` extension for `CONNECT` request handling | | Status: | Extension | | Module Identifier: | proxy\_connect\_module | | Source File: | mod\_proxy\_connect.c | ### Summary This module *requires* the service of `<mod_proxy>`. It provides support for the `CONNECT` HTTP method. This method is mainly used to tunnel SSL requests through proxy servers. Thus, in order to get the ability of handling `CONNECT` requests, `<mod_proxy>` and `<mod_proxy_connect>` have to be present in the server. CONNECT is also used when the server needs to send an HTTPS request through a forward proxy. In this case the server acts as a CONNECT client. This functionality is part of `<mod_proxy>` and `<mod_proxy_connect>` is not needed in this case. **Warning** Do not enable proxying until you have [secured your server](mod_proxy#access). Open proxy servers are dangerous both to your network and to the Internet at large. Request notes ------------- `<mod_proxy_connect>` creates the following request notes for logging using the `%{VARNAME}n` format in `[LogFormat](mod_log_config#logformat)` or `[ErrorLogFormat](core#errorlogformat)`: proxy-source-port The local port used for the connection to the backend server. AllowCONNECT Directive ---------------------- | | | | --- | --- | | Description: | Ports that are allowed to `CONNECT` through the proxy | | Syntax: | ``` AllowCONNECT port[-port] [port[-port]] ... ``` | | Default: | ``` AllowCONNECT 443 563 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy\_connect | | Compatibility: | Moved from `<mod_proxy>` in Apache 2.3.5. Port ranges available since Apache 2.3.7. | The `AllowCONNECT` directive specifies a list of port numbers or ranges to which the proxy `CONNECT` method may connect. Today's browsers use this method when a `https` connection is requested and proxy tunneling over HTTP is in effect. By default, only the default https port (`443`) and the default snews port (`563`) are enabled. Use the `AllowCONNECT` directive to override this default and allow connections to the listed ports only. apache_http_server Apache Module mod_lbmethod_bybusyness Apache Module mod\_lbmethod\_bybusyness ======================================= | | | | --- | --- | | Description: | Pending Request Counting load balancer scheduler algorithm for `<mod_proxy_balancer>` | | Status: | Extension | | Module Identifier: | lbmethod\_bybusyness\_module | | Source File: | mod\_lbmethod\_bybusyness.c | | Compatibility: | Split off from `<mod_proxy_balancer>` in 2.3 | ### Summary This module does not provide any configuration directives of its own. It requires the services of `<mod_proxy_balancer>`, and provides the `bybusyness` load balancing method. Pending Request Counting Algorithm ---------------------------------- Enabled via `lbmethod=bybusyness`, this scheduler keeps track of how many requests each worker is currently assigned at present. A new request is automatically assigned to the worker with the lowest number of active requests. This is useful in the case of workers that queue incoming requests independently of Apache, to ensure that queue length stays even and a request is always given to the worker most likely to service it the fastest and reduce latency. In the case of multiple least-busy workers, the statistics (and weightings) used by the Request Counting method are used to break the tie. Over time, the distribution of work will come to resemble that characteristic of `byrequests` (as implemented by `<mod_lbmethod_byrequests>`). apache_http_server Apache Module mod_cgid Apache Module mod\_cgid ======================= | | | | --- | --- | | Description: | Execution of CGI scripts using an external CGI daemon | | Status: | Base | | Module Identifier: | cgid\_module | | Source File: | mod\_cgid.c | | Compatibility: | Unix threaded MPMs only | ### Summary Except for the optimizations and the additional `[ScriptSock](#scriptsock)` directive noted below, `<mod_cgid>` behaves similarly to `<mod_cgi>`. **See the `<mod_cgi>` summary for additional details about Apache and CGI.** On certain unix operating systems, forking a process from a multi-threaded server is a very expensive operation because the new process will replicate all the threads of the parent process. In order to avoid incurring this expense on each CGI invocation, `<mod_cgid>` creates an external daemon that is responsible for forking child processes to run CGI scripts. The main server communicates with this daemon using a unix domain socket. This module is used by default instead of `<mod_cgi>` whenever a multi-threaded MPM is selected during the compilation process. At the user level, this module is identical in configuration and operation to `<mod_cgi>`. The only exception is the additional directive `ScriptSock` which gives the name of the socket to use for communication with the cgi daemon. CGIDScriptTimeout Directive --------------------------- | | | | --- | --- | | Description: | The length of time to wait for more output from the CGI program | | Syntax: | ``` CGIDScriptTimeout time[s|ms] ``` | | Default: | ``` value of Timeout directive when unset or set to 0 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Base | | Module: | mod\_cgid | | Compatibility: | Available in httpd 2.4.10 and later; in prior releases no timeout was applied | This directive limits the length of time to wait for more output from the CGI program. If the time is exceeded, the request and CGI are terminated. ### Example ``` CGIDScriptTimeout 20 ``` ScriptSock Directive -------------------- | | | | --- | --- | | Description: | The filename prefix of the socket to use for communication with the cgi daemon | | Syntax: | ``` ScriptSock file-path ``` | | Default: | ``` ScriptSock cgisock ``` | | Context: | server config | | Status: | Base | | Module: | mod\_cgid | This directive sets the filename prefix of the socket to use for communication with the CGI daemon, an extension corresponding to the process ID of the server will be appended. The socket will be opened using the permissions of the user who starts Apache (usually root). To maintain the security of communications with CGI scripts, it is important that no other user has permission to write in the directory where the socket is located. If file-path is not an absolute path, the location specified will be relative to the value of `[DefaultRuntimeDir](core#defaultruntimedir)`. ### Example ``` ScriptSock /var/run/cgid.sock ``` apache_http_server Apache Module mod_authz_user Apache Module mod\_authz\_user ============================== | | | | --- | --- | | Description: | User Authorization | | Status: | Base | | Module Identifier: | authz\_user\_module | | Source File: | mod\_authz\_user.c | | Compatibility: | Available in Apache 2.1 and later | ### Summary This module provides authorization capabilities so that authenticated users can be allowed or denied access to portions of the web site. `<mod_authz_user>` grants access if the authenticated user is listed in a `Require user` directive. Alternatively `Require valid-user` can be used to grant access to all successfully authenticated users. The Require Directives ---------------------- Apache's `[Require](mod_authz_core#require)` directives are used during the authorization phase to ensure that a user is allowed to access a resource. mod\_authz\_user extends the authorization types with `user` and `valid-user`. Since v2.4.8, [expressions](../expr) are supported within the user require directives. ### Require user This directive specifies a list of users that are allowed to gain access. ``` Require user john paul george ringo ``` ### Require valid-user When this directive is specified, any successfully authenticated user will be allowed to gain access. ``` Require valid-user ``` apache_http_server Apache Module mod_vhost_alias Apache Module mod\_vhost\_alias =============================== | | | | --- | --- | | Description: | Provides for dynamically configured mass virtual hosting | | Status: | Extension | | Module Identifier: | vhost\_alias\_module | | Source File: | mod\_vhost\_alias.c | ### Summary This module creates dynamically configured virtual hosts, by allowing the IP address and/or the `Host:` header of the HTTP request to be used as part of the pathname to determine what files to serve. This allows for easy use of a huge number of virtual hosts with similar configurations. **Note** If `<mod_alias>` or `<mod_userdir>` are used for translating URIs to filenames, they will override the directives of `<mod_vhost_alias>` described below. For example, the following configuration will map `/cgi-bin/script.pl` to `/usr/local/apache2/cgi-bin/script.pl` in all cases: ``` ScriptAlias "/cgi-bin/" "/usr/local/apache2/cgi-bin/" VirtualScriptAlias "/never/found/%0/cgi-bin/" ``` Directory Name Interpolation ---------------------------- All the directives in this module interpolate a string into a pathname. The interpolated string (henceforth called the "name") may be either the server name (see the `[UseCanonicalName](core#usecanonicalname)` directive for details on how this is determined) or the IP address of the virtual host on the server in dotted-quad format. The interpolation is controlled by specifiers inspired by `printf` which have a number of formats: | | | | --- | --- | | `%%` | insert a `%` | | `%p` | insert the port number of the virtual host | | `%N.M` | insert (part of) the name | `N` and `M` are used to specify substrings of the name. `N` selects from the dot-separated components of the name, and `M` selects characters within whatever `N` has selected. `M` is optional and defaults to zero if it isn't present; the dot must be present if and only if `M` is present. The interpretation is as follows: | | | | --- | --- | | `0` | the whole name | | `1` | the first part | | `2` | the second part | | `-1` | the last part | | `-2` | the penultimate part | | `2+` | the second and all subsequent parts | | `-2+` | the penultimate and all preceding parts | | `1+` and `-1+` | the same as `0` | If `N` or `M` is greater than the number of parts available a single underscore is interpolated. Examples -------- For simple name-based virtual hosts you might use the following directives in your server configuration file: ``` UseCanonicalName Off VirtualDocumentRoot "/usr/local/apache/vhosts/%0" ``` A request for `http://www.example.com/directory/file.html` will be satisfied by the file `/usr/local/apache/vhosts/www.example.com/directory/file.html`. For a very large number of virtual hosts it is a good idea to arrange the files to reduce the size of the `vhosts` directory. To do this you might use the following in your configuration file: ``` UseCanonicalName Off VirtualDocumentRoot "/usr/local/apache/vhosts/%3+/%2.1/%2.2/%2.3/%2" ``` A request for `http://www.domain.example.com/directory/file.html` will be satisfied by the file `/usr/local/apache/vhosts/example.com/d/o/m/domain/directory/file.html`. A more even spread of files can be achieved by hashing from the end of the name, for example: ``` VirtualDocumentRoot "/usr/local/apache/vhosts/%3+/%2.-1/%2.-2/%2.-3/%2" ``` The example request would come from `/usr/local/apache/vhosts/example.com/n/i/a/domain/directory/file.html`. Alternatively you might use: ``` VirtualDocumentRoot "/usr/local/apache/vhosts/%3+/%2.1/%2.2/%2.3/%2.4+" ``` The example request would come from `/usr/local/apache/vhosts/example.com/d/o/m/ain/directory/file.html`. A very common request by users is the ability to point multiple domains to multiple document roots without having to worry about the length or number of parts of the hostname being requested. If the requested hostname is `sub.www.domain.example.com` instead of simply `www.domain.example.com`, then using %3+ will result in the document root being `/usr/local/apache/vhosts/domain.example.com/...` instead of the intended `example.com` directory. In such cases, it can be beneficial to use the combination `%-2.0.%-1.0`, which will always yield the domain name and the tld, for example `example.com` regardless of the number of subdomains appended to the hostname. As such, one can make a configuration that will direct all first, second or third level subdomains to the same directory: ``` VirtualDocumentRoot "/usr/local/apache/vhosts/%-2.0.%-1.0" ``` In the example above, both `www.example.com` as well as `www.sub.example.com` or `example.com` will all point to `/usr/local/apache/vhosts/example.com`. For IP-based virtual hosting you might use the following in your configuration file: ``` UseCanonicalName DNS VirtualDocumentRootIP "/usr/local/apache/vhosts/%1/%2/%3/%4/docs" VirtualScriptAliasIP "/usr/local/apache/vhosts/%1/%2/%3/%4/cgi-bin" ``` A request for `http://www.domain.example.com/directory/file.html` would be satisfied by the file `/usr/local/apache/vhosts/10/20/30/40/docs/directory/file.html` if the IP address of `www.domain.example.com` were 10.20.30.40. A request for `http://www.domain.example.com/cgi-bin/script.pl` would be satisfied by executing the program `/usr/local/apache/vhosts/10/20/30/40/cgi-bin/script.pl`. If you want to include the `.` character in a `VirtualDocumentRoot` directive, but it clashes with a `%` directive, you can work around the problem in the following way: ``` VirtualDocumentRoot "/usr/local/apache/vhosts/%2.0.%3.0" ``` A request for `http://www.domain.example.com/directory/file.html` will be satisfied by the file `/usr/local/apache/vhosts/domain.example/directory/file.html`. The `[LogFormat](mod_log_config#logformat)` directives `%V` and `%A` are useful in conjunction with this module. VirtualDocumentRoot Directive ----------------------------- | | | | --- | --- | | Description: | Dynamically configure the location of the document root for a given virtual host | | Syntax: | ``` VirtualDocumentRoot interpolated-directory|none ``` | | Default: | ``` VirtualDocumentRoot none ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_vhost\_alias | The `VirtualDocumentRoot` directive allows you to determine where Apache HTTP Server will find your documents based on the value of the server name. The result of expanding *interpolated-directory* is used as the root of the document tree in a similar manner to the `[DocumentRoot](core#documentroot)` directive's argument. If *interpolated-directory* is `none` then `VirtualDocumentRoot` is turned off. This directive cannot be used in the same context as `[VirtualDocumentRootIP](#virtualdocumentrootip)`. **Note** `VirtualDocumentRoot` will override any `[DocumentRoot](core#documentroot)` directives you may have put in the same context or child contexts. Putting a `VirtualDocumentRoot` in the global server scope will effectively override `[DocumentRoot](core#documentroot)` directives in any virtual hosts defined later on, unless you set `VirtualDocumentRoot` to `None` in each virtual host. VirtualDocumentRootIP Directive ------------------------------- | | | | --- | --- | | Description: | Dynamically configure the location of the document root for a given virtual host | | Syntax: | ``` VirtualDocumentRootIP interpolated-directory|none ``` | | Default: | ``` VirtualDocumentRootIP none ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_vhost\_alias | The `VirtualDocumentRootIP` directive is like the `[VirtualDocumentRoot](#virtualdocumentroot)` directive, except that it uses the IP address of the server end of the connection for directory interpolation instead of the server name. VirtualScriptAlias Directive ---------------------------- | | | | --- | --- | | Description: | Dynamically configure the location of the CGI directory for a given virtual host | | Syntax: | ``` VirtualScriptAlias interpolated-directory|none ``` | | Default: | ``` VirtualScriptAlias none ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_vhost\_alias | The `VirtualScriptAlias` directive allows you to determine where Apache httpd will find CGI scripts in a similar manner to `[VirtualDocumentRoot](#virtualdocumentroot)` does for other documents. It matches requests for URIs starting `/cgi-bin/`, much like `[ScriptAlias](mod_alias#scriptalias)` `/cgi-bin/` would. VirtualScriptAliasIP Directive ------------------------------ | | | | --- | --- | | Description: | Dynamically configure the location of the CGI directory for a given virtual host | | Syntax: | ``` VirtualScriptAliasIP interpolated-directory|none ``` | | Default: | ``` VirtualScriptAliasIP none ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_vhost\_alias | The `VirtualScriptAliasIP` directive is like the `[VirtualScriptAlias](#virtualscriptalias)` directive, except that it uses the IP address of the server end of the connection for directory interpolation instead of the server name. apache_http_server Apache Module mod_lbmethod_heartbeat Apache Module mod\_lbmethod\_heartbeat ====================================== | | | | --- | --- | | Description: | Heartbeat Traffic Counting load balancer scheduler algorithm for `<mod_proxy_balancer>` | | Status: | Experimental | | Module Identifier: | lbmethod\_heartbeat\_module | | Source File: | mod\_lbmethod\_heartbeat.c | | Compatibility: | Available in version 2.3 and later | ### Summary `lbmethod=heartbeat` uses the services of `<mod_heartmonitor>` to balance between origin servers that are providing heartbeat info via the `<mod_heartbeat>` module. This modules load balancing algorithm favors servers with more ready (idle) capacity over time, but does not select the server with the most ready capacity every time. Servers that have 0 active clients are penalized, with the assumption that they are not fully initialized. HeartbeatStorage Directive -------------------------- | | | | --- | --- | | Description: | Path to read heartbeat data | | Syntax: | ``` HeartbeatStorage file-path ``` | | Default: | ``` HeartbeatStorage logs/hb.dat ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_lbmethod\_heartbeat | The `HeartbeatStorage` directive specifies the path to read heartbeat data. This flat-file is used only when `<mod_slotmem_shm>` is not loaded. apache_http_server Apache Module mod_filter Apache Module mod\_filter ========================= | | | | --- | --- | | Description: | Context-sensitive smart filter configuration module | | Status: | Base | | Module Identifier: | filter\_module | | Source File: | mod\_filter.c | | Compatibility: | Version 2.1 and later | ### Summary This module enables smart, context-sensitive configuration of output content filters. For example, apache can be configured to process different content-types through different filters, even when the content-type is not known in advance (e.g. in a proxy). `<mod_filter>` works by introducing indirection into the filter chain. Instead of inserting filters in the chain, we insert a filter harness which in turn dispatches conditionally to a filter provider. Any content filter may be used as a provider to `<mod_filter>`; no change to existing filter modules is required (although it may be possible to simplify them). Smart Filtering --------------- In the traditional filtering model, filters are inserted unconditionally using `[AddOutputFilter](mod_mime#addoutputfilter)` and family. Each filter then needs to determine whether to run, and there is little flexibility available for server admins to allow the chain to be configured dynamically. `<mod_filter>` by contrast gives server administrators a great deal of flexibility in configuring the filter chain. In fact, filters can be inserted based on complex boolean [expressions](../expr) This generalises the limited flexibility offered by `AddOutputFilterByType`. Filter Declarations, Providers and Chains ----------------------------------------- Figure 1: The traditional filter model In the traditional model, output filters are a simple chain from the content generator (handler) to the client. This works well provided the filter chain can be correctly configured, but presents problems when the filters need to be configured dynamically based on the outcome of the handler. Figure 2: The `<mod_filter>` model `<mod_filter>` works by introducing indirection into the filter chain. Instead of inserting filters in the chain, we insert a filter harness which in turn dispatches conditionally to a filter provider. Any content filter may be used as a provider to `<mod_filter>`; no change to existing filter modules is required (although it may be possible to simplify them). There can be multiple providers for one filter, but no more than one provider will run for any single request. A filter chain comprises any number of instances of the filter harness, each of which may have any number of providers. A special case is that of a single provider with unconditional dispatch: this is equivalent to inserting the provider filter directly into the chain. Configuring the Chain --------------------- There are three stages to configuring a filter chain with `<mod_filter>`. For details of the directives, see below. Declare Filters The `[FilterDeclare](#filterdeclare)` directive declares a filter, assigning it a name and filter type. Required only if the filter is not the default type AP\_FTYPE\_RESOURCE. Register Providers The `[FilterProvider](#filterprovider)` directive registers a provider with a filter. The filter may have been declared with `[FilterDeclare](#filterdeclare)`; if not, FilterProvider will implicitly declare it with the default type AP\_FTYPE\_RESOURCE. The provider must have been registered with `ap_register_output_filter` by some module. The final argument to `[FilterProvider](#filterprovider)` is an expression: the provider will be selected to run for a request if and only if the expression evaluates to true. The expression may evaluate HTTP request or response headers, environment variables, or the Handler used by this request. Unlike earlier versions, mod\_filter now supports complex expressions involving multiple criteria with AND / OR logic (&& / ||) and brackets. The details of the expression syntax are described in the [ap\_expr documentation](../expr). Configure the Chain The above directives build components of a smart filter chain, but do not configure it to run. The `[FilterChain](#filterchain)` directive builds a filter chain from smart filters declared, offering the flexibility to insert filters at the beginning or end of the chain, remove a filter, or clear the chain. Filtering and Response Status ----------------------------- mod\_filter normally only runs filters on responses with HTTP status 200 (OK). If you want to filter documents with other response statuses, you can set the filter-errordocs environment variable, and it will work on all responses regardless of status. To refine this further, you can use expression conditions with `FilterProvider`. Upgrading from Apache HTTP Server 2.2 Configuration --------------------------------------------------- The `[FilterProvider](#filterprovider)` directive has changed from httpd 2.2: the match and dispatch arguments are replaced with a single but more versatile expression. In general, you can convert a match/dispatch pair to the two sides of an expression, using something like: ``` "dispatch = 'match'" ``` The Request headers, Response headers and Environment variables are now interpreted from syntax %{req:foo}, %{resp:foo} and %{env:foo} respectively. The variables %{HANDLER} and %{CONTENT\_TYPE} are also supported. Note that the match no longer support substring matches. They can be replaced by regular expression matches. Examples -------- Server side Includes (SSI) A simple case of replacing `AddOutputFilterByType` ``` FilterDeclare SSI FilterProvider SSI INCLUDES "%{CONTENT_TYPE} =~ m|^text/html|" FilterChain SSI ``` Server side Includes (SSI) The same as the above but dispatching on handler (classic SSI behaviour; .shtml files get processed). ``` FilterProvider SSI INCLUDES "%{HANDLER} = 'server-parsed'" FilterChain SSI ``` Emulating mod\_gzip with mod\_deflate Insert INFLATE filter only if "gzip" is NOT in the Accept-Encoding header. This filter runs with ftype CONTENT\_SET. ``` FilterDeclare gzip CONTENT_SET FilterProvider gzip inflate "%{req:Accept-Encoding} !~ /gzip/" FilterChain gzip ``` Image Downsampling Suppose we want to downsample all web images, and have filters for GIF, JPEG and PNG. ``` FilterProvider unpack jpeg_unpack "%{CONTENT_TYPE} = 'image/jpeg'" FilterProvider unpack gif_unpack "%{CONTENT_TYPE} = 'image/gif'" FilterProvider unpack png_unpack "%{CONTENT_TYPE} = 'image/png'" FilterProvider downsample downsample_filter "%{CONTENT_TYPE} = m|^image/(jpeg|gif|png)|" FilterProtocol downsample "change=yes" FilterProvider repack jpeg_pack "%{CONTENT_TYPE} = 'image/jpeg'" FilterProvider repack gif_pack "%{CONTENT_TYPE} = 'image/gif'" FilterProvider repack png_pack "%{CONTENT_TYPE} = 'image/png'" <Location "/image-filter"> FilterChain unpack downsample repack </Location> ``` Protocol Handling ----------------- Historically, each filter is responsible for ensuring that whatever changes it makes are correctly represented in the HTTP response headers, and that it does not run when it would make an illegal change. This imposes a burden on filter authors to re-implement some common functionality in every filter: * Many filters will change the content, invalidating existing content tags, checksums, hashes, and lengths. * Filters that require an entire, unbroken response in input need to ensure they don't get byteranges from a backend. * Filters that transform output in a filter need to ensure they don't violate a `Cache-Control: no-transform` header from the backend. * Filters may make responses uncacheable. `<mod_filter>` aims to offer generic handling of these details of filter implementation, reducing the complexity required of content filter modules. This is work-in-progress; the `[FilterProtocol](#filterprotocol)` implements some of this functionality for back-compatibility with Apache 2.0 modules. For httpd 2.1 and later, the `ap_register_output_filter_protocol` and `ap_filter_protocol` API enables filter modules to declare their own behaviour. At the same time, `<mod_filter>` should not interfere with a filter that wants to handle all aspects of the protocol. By default (i.e. in the absence of any `[FilterProtocol](#filterprotocol)` directives), `<mod_filter>` will leave the headers untouched. At the time of writing, this feature is largely untested, as modules in common use are designed to work with 2.0. Modules using it should test it carefully. AddOutputFilterByType Directive ------------------------------- | | | | --- | --- | | Description: | assigns an output filter to a particular media-type | | Syntax: | ``` AddOutputFilterByType filter[;filter...] media-type [media-type] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_filter | | Compatibility: | Had severe limitations before being moved to `<mod_filter>` in version 2.3.7 | This directive activates a particular output [filter](../filter) for a request depending on the response [media-type](https://httpd.apache.org/docs/2.4/en/glossary.html#media-type "see glossary"). The following example uses the `DEFLATE` filter, which is provided by `<mod_deflate>`. It will compress all output (either static or dynamic) which is labeled as `text/html` or `text/plain` before it is sent to the client. ``` AddOutputFilterByType DEFLATE text/html text/plain ``` If you want the content to be processed by more than one filter, their names have to be separated by semicolons. It's also possible to use one `AddOutputFilterByType` directive for each of these filters. The configuration below causes all script output labeled as `text/html` to be processed at first by the `INCLUDES` filter and then by the `DEFLATE` filter. ``` <Location "/cgi-bin/"> Options Includes AddOutputFilterByType INCLUDES;DEFLATE text/html </Location> ``` ### See also * `[AddOutputFilter](mod_mime#addoutputfilter)` * `[SetOutputFilter](core#setoutputfilter)` * [filters](../filter) FilterChain Directive --------------------- | | | | --- | --- | | Description: | Configure the filter chain | | Syntax: | ``` FilterChain [+=-@!]filter-name ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Base | | Module: | mod\_filter | This configures an actual filter chain, from declared filters. `FilterChain` takes any number of arguments, each optionally preceded with a single-character control that determines what to do: `+filter-name` Add filter-name to the end of the filter chain `@filter-name` Insert filter-name at the start of the filter chain `-filter-name` Remove filter-name from the filter chain `=filter-name` Empty the filter chain and insert filter-name `!` Empty the filter chain `filter-name` Equivalent to `+filter-name` FilterDeclare Directive ----------------------- | | | | --- | --- | | Description: | Declare a smart filter | | Syntax: | ``` FilterDeclare filter-name [type] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Base | | Module: | mod\_filter | This directive declares an output filter together with a header or environment variable that will determine runtime configuration. The first argument is a filter-name for use in `[FilterProvider](#filterprovider)`, `[FilterChain](#filterchain)` and `[FilterProtocol](#filterprotocol)` directives. The final (optional) argument is the type of filter, and takes values of `ap_filter_type` - namely `RESOURCE` (the default), `CONTENT_SET`, `PROTOCOL`, `TRANSCODE`, `CONNECTION` or `NETWORK`. FilterProtocol Directive ------------------------ | | | | --- | --- | | Description: | Deal with correct HTTP protocol handling | | Syntax: | ``` FilterProtocol filter-name [provider-name] proto-flags ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Base | | Module: | mod\_filter | This directs `<mod_filter>` to deal with ensuring the filter doesn't run when it shouldn't, and that the HTTP response headers are correctly set taking into account the effects of the filter. There are two forms of this directive. With three arguments, it applies specifically to a filter-name and a provider-name for that filter. With two arguments it applies to a filter-name whenever the filter runs *any* provider. Flags specified with this directive are merged with the flags that underlying providers may have registered with `<mod_filter>`. For example, a filter may internally specify the equivalent of `change=yes`, but a particular configuration of the module can override with `change=no`. proto-flags is one or more of `change=yes|no` Specifies whether the filter changes the content, including possibly the content length. The "no" argument is supported in 2.4.7 and later. `change=1:1` The filter changes the content, but will not change the content length `byteranges=no` The filter cannot work on byteranges and requires complete input `proxy=no` The filter should not run in a proxy context `proxy=transform` The filter transforms the response in a manner incompatible with the HTTP `Cache-Control: no-transform` header. `cache=no` The filter renders the output uncacheable (eg by introducing randomised content changes) FilterProvider Directive ------------------------ | | | | --- | --- | | Description: | Register a content filter | | Syntax: | ``` FilterProvider filter-name provider-name expression ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Base | | Module: | mod\_filter | This directive registers a *provider* for the smart filter. The provider will be called if and only if the expression declared evaluates to true when the harness is first called. provider-name must have been registered by loading a module that registers the name with `ap_register_output_filter`. expression is an [ap\_expr](../expr). ### See also * [Expressions in Apache HTTP Server](../expr), for a complete reference and examples. * `<mod_include>` FilterTrace Directive --------------------- | | | | --- | --- | | Description: | Get debug/diagnostic information from `<mod_filter>` | | Syntax: | ``` FilterTrace filter-name level ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_filter | This directive generates debug information from `<mod_filter>`. It is designed to help test and debug providers (filter modules), although it may also help with `<mod_filter>` itself. The debug output depends on the level set: `0` (default) No debug information is generated. `1` `<mod_filter>` will record buckets and brigades passing through the filter to the error log, before the provider has processed them. This is similar to the information generated by [mod\_diagnostics](http://apache.webthing.com/mod_diagnostics/). `2` (not yet implemented) Will dump the full data passing through to a tempfile before the provider. **For single-user debug only**; this will not support concurrent hits.
programming_docs
apache_http_server Apache Module mod_suexec Apache Module mod\_suexec ========================= | | | | --- | --- | | Description: | Allows CGI scripts to run as a specified user and Group | | Status: | Extension | | Module Identifier: | suexec\_module | | Source File: | mod\_suexec.c | ### Summary This module, in combination with the `[suexec](../programs/suexec)` support program allows CGI scripts to run as a specified user and Group. SuexecUserGroup Directive ------------------------- | | | | --- | --- | | Description: | User and group for CGI programs to run as | | Syntax: | ``` SuexecUserGroup User Group ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_suexec | The `SuexecUserGroup` directive allows you to specify a user and group for CGI programs to run as. Non-CGI requests are still processed with the user specified in the `[User](mod_unixd#user)` directive. ### Example ``` SuexecUserGroup nobody nogroup ``` Startup will fail if this directive is specified but the suEXEC feature is disabled. ### See also * `[Suexec](mod_unixd#suexec)` apache_http_server Apache Module mod_include Apache Module mod\_include ========================== | | | | --- | --- | | Description: | Server-parsed html documents (Server Side Includes) | | Status: | Base | | Module Identifier: | include\_module | | Source File: | mod\_include.c | ### Summary This module provides a filter which will process files before they are sent to the client. The processing is controlled by specially formatted SGML comments, referred to as elements. These elements allow conditional text, the inclusion of other files or programs, as well as the setting and printing of environment variables. Enabling Server-Side Includes ----------------------------- Server Side Includes are implemented by the `INCLUDES` [filter](../filter). If documents containing server-side include directives are given the extension .shtml, the following directives will make Apache parse them and assign the resulting document the mime type of `text/html`: ``` AddType text/html .shtml AddOutputFilter INCLUDES .shtml ``` The following directive must be given for the directories containing the shtml files (typically in a `[<Directory>](core#directory)` section, but this directive is also valid in `.htaccess` files if `[AllowOverride](core#allowoverride)` `Options` is set): ``` Options +Includes ``` For backwards compatibility, the `server-parsed` [handler](../handler) also activates the INCLUDES filter. As well, Apache will activate the INCLUDES filter for any document with mime type `text/x-server-parsed-html` or `text/x-server-parsed-html3` (and the resulting output will have the mime type `text/html`). For more information, see our [Tutorial on Server Side Includes](../howto/ssi). PATH\_INFO with Server Side Includes ------------------------------------ Files processed for server-side includes no longer accept requests with `PATH_INFO` (trailing pathname information) by default. You can use the `[AcceptPathInfo](core#acceptpathinfo)` directive to configure the server to accept requests with `PATH_INFO`. Available Elements ------------------ The document is parsed as an HTML document, with special commands embedded as SGML comments. A command has the syntax: ``` <!--#element attribute=value attribute=value ... --> ``` The value will often be enclosed in double quotes, but single quotes (`'`) and backticks (```) are also possible. Many commands only allow a single attribute-value pair. Note that the comment terminator (`-->`) should be preceded by whitespace to ensure that it isn't considered part of an SSI token. Note that the leading `<!--#` is *one* token and may not contain any whitespaces. The allowed elements are listed in the following table: | Element | Description | | --- | --- | | `comment` | SSI comment | | `config` | configure output formats | | `echo` | print variables | | `exec` | execute external programs | | `fsize` | print size of a file | | `flastmod` | print last modification time of a file | | `include` | include a file | | `printenv` | print all available variables | | `set` | set a value of a variable | SSI elements may be defined by modules other than `<mod_include>`. In fact, the `[exec](#element.exec)` element is provided by `<mod_cgi>`, and will only be available if this module is loaded. ### The comment Element This command doesn't output anything. Its only use is to add comments within a file. These comments are not printed. This syntax is available in version 2.4.21 and later. ``` <!--#comment Blah Blah Blah --> or <!--#comment text="Blah Blah Blah" --> ``` ### The config Element This command controls various aspects of the parsing. The valid attributes are: `echomsg` (*Apache 2.1 and later*) The value is a message that is sent back to the client if the `[echo](#element.echo)` element attempts to echo an undefined variable. This overrides any `[SSIUndefinedEcho](#ssiundefinedecho)` directives. ``` <!--#config echomsg="[Value Undefined]" --> ``` `errmsg` The value is a message that is sent back to the client if an error occurs while parsing the document. This overrides any `[SSIErrorMsg](#ssierrormsg)` directives. ``` <!--#config errmsg="[Oops, something broke.]" --> ``` `sizefmt` The value sets the format to be used when displaying the size of a file. Valid values are `bytes` for a count in bytes, or `abbrev` for a count in Kb or Mb as appropriate, for example a size of 1024 bytes will be printed as "1K". ``` <!--#config sizefmt="abbrev" --> ``` `timefmt` The value is a string to be used by the `strftime(3)` library routine when printing dates. ``` <!--#config timefmt=""%R, %B %d, %Y"" --> ``` ### The echo Element This command prints one of the [include variables](#includevars) defined below. If the variable is unset, the result is determined by the `[SSIUndefinedEcho](#ssiundefinedecho)` directive. Any dates printed are subject to the currently configured `timefmt`. Attributes: `var` The value is the name of the variable to print. `decoding` Specifies whether Apache should strip an encoding from the variable before processing the variable further. The default is `none`, where no decoding will be done. If set to `url`, then URL decoding (also known as %-encoding; this is appropriate for use within URLs in links, etc.) will be performed. If set to `urlencoded`, application/x-www-form-urlencoded compatible encoding (found in query strings) will be stripped. If set to `base64`, base64 will be decoded, and if set to `entity`, HTML entity encoding will be stripped. Decoding is done prior to any further encoding on the variable. Multiple encodings can be stripped by specifying more than one comma separated encoding. The decoding setting will remain in effect until the next decoding attribute is encountered, or the element ends. The `decoding` attribute must *precede* the corresponding `var` attribute to be effective. `encoding` Specifies how Apache should encode special characters contained in the variable before outputting them. If set to `none`, no encoding will be done. If set to `url`, then URL encoding (also known as %-encoding; this is appropriate for use within URLs in links, etc.) will be performed. If set to `urlencoded`, application/x-www-form-urlencoded compatible encoding will be performed instead, and should be used with query strings. If set to `base64`, base64 encoding will be performed. At the start of an `echo` element, the default is set to `entity`, resulting in entity encoding (which is appropriate in the context of a block-level HTML element, *e.g.* a paragraph of text). This can be changed by adding an `encoding` attribute, which will remain in effect until the next `encoding` attribute is encountered or the element ends, whichever comes first. The `encoding` attribute must *precede* the corresponding `var` attribute to be effective. In order to avoid cross-site scripting issues, you should *always* encode user supplied data. ### Example ``` <!--#echo encoding="entity" var="QUERY_STRING" --> ``` ### The exec Element The `exec` command executes a given shell command or CGI script. It requires `<mod_cgi>` to be present in the server. If `[Options](core#options)` `IncludesNOEXEC` is set, this command is completely disabled. The valid attributes are: `cgi` The value specifies a (%-encoded) URL-path to the CGI script. If the path does not begin with a slash (/), then it is taken to be relative to the current document. The document referenced by this path is invoked as a CGI script, even if the server would not normally recognize it as such. However, the directory containing the script must be enabled for CGI scripts (with `[ScriptAlias](mod_alias#scriptalias)` or `[Options](core#options)` `ExecCGI`). The CGI script is given the `PATH_INFO` and query string (`QUERY_STRING`) of the original request from the client; these *cannot* be specified in the URL path. The include variables will be available to the script in addition to the standard [CGI](mod_cgi) environment. ### Example ``` <!--#exec cgi="/cgi-bin/example.cgi" --> ``` If the script returns a `Location:` header instead of output, then this will be translated into an HTML anchor. The `[include virtual](#includevirtual)` element should be used in preference to `exec cgi`. In particular, if you need to pass additional arguments to a CGI program, using the query string, this cannot be done with `exec cgi`, but can be done with `include virtual`, as shown here: ``` <!--#include virtual="/cgi-bin/example.cgi?argument=value" --> ``` `cmd` The server will execute the given string using `/bin/sh`. The [include variables](#includevars) are available to the command, in addition to the usual set of CGI variables. The use of `[#include virtual](#includevirtual)` is almost always preferred to using either `#exec cgi` or `#exec cmd`. The former (`#include virtual`) uses the standard Apache sub-request mechanism to include files or scripts. It is much better tested and maintained. In addition, on some platforms, like Win32, and on unix when using [suexec](../suexec), you cannot pass arguments to a command in an `exec` directive, or otherwise include spaces in the command. Thus, while the following will work under a non-suexec configuration on unix, it will not produce the desired result under Win32, or when running suexec: ``` <!--#exec cmd="perl /path/to/perlscript arg1 arg2" --> ``` ### The fsize Element This command prints the size of the specified file, subject to the `sizefmt` format specification. Attributes: `file` The value is a path relative to the directory containing the current document being parsed. ``` This file is <!--#fsize file="mod_include.html" --> bytes. ``` The value of `file` cannot start with a slash (`/`), nor can it contain `../` so as to refer to a file above the current directory or outside of the document root. Attempting to so will result in the error message: `The given path was above the root path`. `virtual` The value is a (%-encoded) URL-path. If it does not begin with a slash (/) then it is taken to be relative to the current document. Note, that this does *not* print the size of any CGI output, but the size of the CGI script itself. ``` This file is <!--#fsize virtual="/docs/mod/mod_include.html" --> bytes. ``` Note that in many cases these two are exactly the same thing. However, the `file` attribute doesn't respect URL-space aliases. ### The flastmod Element This command prints the last modification date of the specified file, subject to the `timefmt` format specification. The attributes are the same as for the `[fsize](#element.fsize)` command. ### The include Element This command inserts the text of another document or file into the parsed file. Any included file is subject to the usual access control. If the directory containing the parsed file has [Options](core#options) `IncludesNOEXEC` set, then only documents with a text [MIME-type](https://httpd.apache.org/docs/2.4/en/glossary.html#mime-type "see glossary") (`text/plain`, `text/html` etc.) will be included. Otherwise CGI scripts are invoked as normal using the complete URL given in the command, including any query string. An attribute defines the location of the document, and may appear more than once in an include element; an inclusion is done for each attribute given to the include command in turn. The valid attributes are: `file` The value is a path relative to the directory containing the current document being parsed. It cannot contain `../`, nor can it be an absolute path. Therefore, you cannot include files that are outside of the document root, or above the current document in the directory structure. The `virtual` attribute should always be used in preference to this one. `virtual` The value is a (%-encoded) URL-path. The URL cannot contain a scheme or hostname, only a path and an optional query string. If it does not begin with a slash (/) then it is taken to be relative to the current document. A URL is constructed from the attribute, and the output the server would return if the URL were accessed by the client is included in the parsed output. Thus included files can be nested. If the specified URL is a CGI program, the program will be executed and its output inserted in place of the directive in the parsed file. You may include a query string in a CGI url: ``` <!--#include virtual="/cgi-bin/example.cgi?argument=value" --> ``` `include virtual` should be used in preference to `exec cgi` to include the output of CGI programs into an HTML document. If the `[KeptBodySize](mod_request#keptbodysize)` directive is correctly configured and valid for this included file, attempts to POST requests to the enclosing HTML document will be passed through to subrequests as POST requests as well. Without the directive, all subrequests are processed as GET requests. `onerror` The value is a (%-encoded) URL-path which is shown should a previous attempt to include a file or virtual attribute failed. To be effective, this attribute must be specified after the file or virtual attributes being covered. If the attempt to include the onerror path fails, or if onerror is not specified, the default error message will be included. ``` # Simple example <!--#include virtual="/not-exist.html" onerror="/error.html" --> ``` ``` # Dedicated onerror paths <!--#include virtual="/path-a.html" onerror="/error-a.html" virtual="/path-b.html" onerror="/error-b.html" --> ``` ### The printenv Element This prints out a plain text listing of all existing variables and their values. Special characters are entity encoded (see the `[echo](#element.echo)` element for details) before being output. There are no attributes. ### Example ``` <pre> <!--#printenv --> </pre> ``` ### The set Element This sets the value of a variable. Attributes: `var` The name of the variable to set. `value` The value to give a variable. `decoding` Specifies whether Apache should strip an encoding from the variable before processing the variable further. The default is `none`, where no decoding will be done. If set to `url`, `urlencoded`, `base64` or `entity`, URL decoding, application/x-www-form-urlencoded decoding, base64 decoding or HTML entity decoding will be performed respectively. More than one decoding can be specified by separating with commas. The decoding setting will remain in effect until the next decoding attribute is encountered, or the element ends. The `decoding` attribute must *precede* the corresponding `var` attribute to be effective. `encoding` Specifies how Apache should encode special characters contained in the variable before setting them. The default is `none`, where no encoding will be done. If set to `url`, `urlencoding`, `base64` or `entity`, URL encoding, application/x-www-form-urlencoded encoding, base64 encoding or HTML entity encoding will be performed respectively. More than one encoding can be specified by separating with commas. The encoding setting will remain in effect until the next encoding attribute is encountered, or the element ends. The `encoding` attribute must *precede* the corresponding `var` attribute to be effective. Encodings are applied after all decodings have been stripped. ### Example ``` <!--#set var="category" value="help" --> ``` Include Variables ----------------- In addition to the variables in the standard CGI environment, these are available for the `echo` command, for `if` and `elif`, and to any program invoked by the document. `DATE_GMT` The current date in Greenwich Mean Time. `DATE_LOCAL` The current date in the local time zone. `DOCUMENT_ARGS` This variable contains the query string of the active SSI document, or the empty string if a query string is not included. For subrequests invoked through the `include` SSI directive, `QUERY_STRING` will represent the query string of the subrequest and `DOCUMENT_ARGS` will represent the query string of the SSI document. (Available in Apache HTTP Server 2.4.19 and later.) `DOCUMENT_NAME` The filename (excluding directories) of the document requested by the user. `DOCUMENT_PATH_INFO` The trailing pathname information. See directive `[AcceptPathInfo](core#acceptpathinfo)` for more information about `PATH_INFO`. `DOCUMENT_URI` The (%-decoded) URL path of the document requested by the user. Note that in the case of nested include files, this is *not* the URL for the current document. Note also that if the URL is modified internally (e.g. by an `[alias](mod_alias#alias)` or `[directoryindex](mod_dir#directoryindex)`), the modified URL is shown. `LAST_MODIFIED` The last modification date of the document requested by the user. `QUERY_STRING_UNESCAPED` If a query string is present in the request for the active SSI document, this variable contains the (%-decoded) query string, which is *escaped* for shell usage (special characters like `&` etc. are preceded by backslashes). It is not set if a query string is not present. Use `DOCUMENT_ARGS` if shell escaping is not desired. `USER_NAME` The user name of the owner of the file. Variable Substitution --------------------- Variable substitution is done within quoted strings in most cases where they may reasonably occur as an argument to an SSI directive. This includes the `config`, `exec`, `flastmod`, `fsize`, `include`, `echo`, and `set` directives. If `[SSILegacyExprParser](#ssilegacyexprparser)` is set to `on`, substitution also occurs in the arguments to conditional operators. You can insert a literal dollar sign into the string using backslash quoting: ``` <!--#set var="cur" value="\$test" --> ``` If a variable reference needs to be substituted in the middle of a character sequence that might otherwise be considered a valid identifier in its own right, it can be disambiguated by enclosing the reference in braces, *a la* shell substitution: ``` <!--#set var="Zed" value="${REMOTE_HOST}_${REQUEST_METHOD}" --> ``` This will result in the `Zed` variable being set to "`X_Y`" if `REMOTE_HOST` is "`X`" and `REQUEST_METHOD` is "`Y`". Flow Control Elements --------------------- The basic flow control elements are: ``` <!--#if expr="test_condition" --> <!--#elif expr="test_condition" --> <!--#else --> <!--#endif --> ``` The `if` element works like an if statement in a programming language. The test condition is evaluated and if the result is true, then the text until the next `elif`, `else` or `endif` element is included in the output stream. The `elif` or `else` statements are used to put text into the output stream if the original test\_condition was false. These elements are optional. The `endif` element ends the `if` element and is required. test\_condition is a boolean expression which follows the [ap\_expr](../expr) syntax. The syntax can be changed to be compatible with Apache HTTPD 2.2.x using `[SSILegacyExprParser](#ssilegacyexprparser)`. The SSI variables set with the `var` element are exported into the request environment and can be accessed with the `reqenv` function. As a short-cut, the function name `v` is also available inside `<mod_include>`. The below example will print "from local net" if client IP address belongs to the 10.0.0.0/8 subnet. ``` <!--#if expr='-R "10.0.0.0/8"' --> from local net <!--#else --> from somewhere else <!--#endif --> ``` The below example will print "foo is bar" if the variable `foo` is set to the value "bar". ``` <!--#if expr='v("foo") = "bar"' --> foo is bar <!--#endif --> ``` **Reference Documentation** See also: [Expressions in Apache HTTP Server](../expr), for a complete reference and examples. The *restricted* functions are not available inside `<mod_include>` Legacy expression syntax ------------------------ This section describes the syntax of the `#if expr` element if `[SSILegacyExprParser](#ssilegacyexprparser)` is set to `on`. `string` true if string is not empty `-A string` true if the URL represented by the string is accessible by configuration, false otherwise. This is useful where content on a page is to be hidden from users who are not authorized to view the URL, such as a link to that URL. Note that the URL is only tested for whether access would be granted, not whether the URL exists. ### Example ``` <!--#if expr="-A /private" --> Click <a href="/private">here</a> to access private information. <!--#endif --> ``` `string1 = string2 string1 == string2 string1 != string2` Compare string1 with string2. If string2 has the form `/string2/` then it is treated as a regular expression. Regular expressions are implemented by the [PCRE](http://www.pcre.org) engine and have the same syntax as those in [perl 5](http://www.perl.com). Note that `==` is just an alias for `=` and behaves exactly the same way. If you are matching positive (`=` or `==`), you can capture grouped parts of the regular expression. The captured parts are stored in the special variables `$1` .. `$9`. The whole string matched by the regular expression is stored in the special variable `$0` ### Example ``` <!--#if expr="$QUERY_STRING = /^sid=([a-zA-Z0-9]+)/" --> <!--#set var="session" value="$1" --> <!--#endif --> ``` `string1 < string2 string1 <= string2 string1 > string2 string1 >= string2` Compare string1 with string2. Note, that strings are compared *literally* (using `strcmp(3)`). Therefore the string "100" is less than "20". `( test_condition )` true if test\_condition is true `! test_condition` true if test\_condition is false `test_condition1 && test_condition2` true if both test\_condition1 and test\_condition2 are true `test_condition1 || test_condition2` true if either test\_condition1 or test\_condition2 is true "`=`" and "`!=`" bind more tightly than "`&&`" and "`||`". "`!`" binds most tightly. Thus, the following are equivalent: ``` <!--#if expr="$a = test1 && $b = test2" --> <!--#if expr="($a = test1) && ($b = test2)" --> ``` The boolean operators `&&` and `||` share the same priority. So if you want to bind such an operator more tightly, you should use parentheses. Anything that's not recognized as a variable or an operator is treated as a string. Strings can also be quoted: `'string'`. Unquoted strings can't contain whitespace (blanks and tabs) because it is used to separate tokens such as variables. If multiple strings are found in a row, they are concatenated using blanks. So, `string1 string2` results in `string1 string2` and `'string1 string2'` results in `string1 string2`. **Optimization of Boolean Expressions** If the expressions become more complex and slow down processing significantly, you can try to optimize them according to the evaluation rules: * Expressions are evaluated from left to right * Binary boolean operators (`&&` and `||`) are short circuited wherever possible. In conclusion with the rule above that means, `<mod_include>` evaluates at first the left expression. If the left result is sufficient to determine the end result, processing stops here. Otherwise it evaluates the right side and computes the end result from both left and right results. * Short circuit evaluation is turned off as long as there are regular expressions to deal with. These must be evaluated to fill in the backreference variables (`$1` .. `$9`). If you want to look how a particular expression is handled, you can recompile `<mod_include>` using the `-DDEBUG_INCLUDE` compiler option. This inserts for every parsed expression tokenizer information, the parse tree and how it is evaluated into the output sent to the client. **Escaping slashes in regex strings** All slashes which are not intended to act as delimiters in your regex must be escaped. This is regardless of their meaning to the regex engine. SSIEndTag Directive ------------------- | | | | --- | --- | | Description: | String that ends an include element | | Syntax: | ``` SSIEndTag tag ``` | | Default: | ``` SSIEndTag "-->" ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_include | This directive changes the string that `<mod_include>` looks for to mark the end of an include element. ``` SSIEndTag "%>" ``` ### See also * `[SSIStartTag](#ssistarttag)` SSIErrorMsg Directive --------------------- | | | | --- | --- | | Description: | Error message displayed when there is an SSI error | | Syntax: | ``` SSIErrorMsg message ``` | | Default: | ``` SSIErrorMsg "[an error occurred while processing this directive]" ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Base | | Module: | mod\_include | The `SSIErrorMsg` directive changes the error message displayed when `<mod_include>` encounters an error. For production servers you may consider changing the default error message to `"<!-- Error -->"` so that the message is not presented to the user. This directive has the same effect as the `<!--#config errmsg=message -->` element. ``` SSIErrorMsg "<!-- Error -->" ``` SSIETag Directive ----------------- | | | | --- | --- | | Description: | Controls whether ETags are generated by the server. | | Syntax: | ``` SSIETag on|off ``` | | Default: | ``` SSIETag off ``` | | Context: | directory, .htaccess | | Status: | Base | | Module: | mod\_include | | Compatibility: | Available in version 2.2.15 and later. | Under normal circumstances, a file filtered by `<mod_include>` may contain elements that are either dynamically generated, or that may have changed independently of the original file. As a result, by default the server is asked not to generate an `ETag` header for the response by adding `no-etag` to the request notes. The `SSIETag` directive suppresses this behaviour, and allows the server to generate an `ETag` header. This can be used to enable caching of the output. Note that a backend server or dynamic content generator may generate an ETag of its own, ignoring `no-etag`, and this ETag will be passed by `<mod_include>` regardless of the value of this setting. `SSIETag` can take on the following values: `off` `no-etag` will be added to the request notes, and the server is asked not to generate an ETag. Where a server ignores the value of `no-etag` and generates an ETag anyway, the ETag will be respected. `on` Existing ETags will be respected, and ETags generated by the server will be passed on in the response. SSILastModified Directive ------------------------- | | | | --- | --- | | Description: | Controls whether `Last-Modified` headers are generated by the server. | | Syntax: | ``` SSILastModified on|off ``` | | Default: | ``` SSILastModified off ``` | | Context: | directory, .htaccess | | Status: | Base | | Module: | mod\_include | | Compatibility: | Available in version 2.2.15 and later. | Under normal circumstances, a file filtered by `<mod_include>` may contain elements that are either dynamically generated, or that may have changed independently of the original file. As a result, by default the `Last-Modified` header is stripped from the response. The `SSILastModified` directive overrides this behaviour, and allows the `Last-Modified` header to be respected if already present, or set if the header is not already present. This can be used to enable caching of the output. `SSILastModified` can take on the following values: `off` The `Last-Modified` header will be stripped from responses, unless the `[XBitHack](#xbithack)` directive is set to `full` as described below. `on` The `Last-Modified` header will be respected if already present in a response, and added to the response if the response is a file and the header is missing. The `[SSILastModified](#ssilastmodified)` directive takes precedence over `[XBitHack](#xbithack)`. SSILegacyExprParser Directive ----------------------------- | | | | --- | --- | | Description: | Enable compatibility mode for conditional expressions. | | Syntax: | ``` SSILegacyExprParser on|off ``` | | Default: | ``` SSILegacyExprParser off ``` | | Context: | directory, .htaccess | | Status: | Base | | Module: | mod\_include | | Compatibility: | Available in version 2.3.13 and later. | As of version 2.3.13, `<mod_include>` has switched to the new [ap\_expr](../expr) syntax for conditional expressions in `#if` flow control elements. This directive allows to switch to the [old syntax](#legacyexpr) which is compatible with Apache HTTPD version 2.2.x and earlier. SSIStartTag Directive --------------------- | | | | --- | --- | | Description: | String that starts an include element | | Syntax: | ``` SSIStartTag tag ``` | | Default: | ``` SSIStartTag "<!--#" ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_include | This directive changes the string that `<mod_include>` looks for to mark an include element to process. You may want to use this option if you have 2 servers parsing the output of a file each processing different commands (possibly at different times). ``` SSIStartTag "<%" SSIEndTag "%>" ``` The example given above, which also specifies a matching `[SSIEndTag](#ssiendtag)`, will allow you to use SSI directives as shown in the example below: ### SSI directives with alternate start and end tags ``` <%printenv %> ``` ### See also * `[SSIEndTag](#ssiendtag)` SSITimeFormat Directive ----------------------- | | | | --- | --- | | Description: | Configures the format in which date strings are displayed | | Syntax: | ``` SSITimeFormat formatstring ``` | | Default: | ``` SSITimeFormat "%A, %d-%b-%Y %H:%M:%S %Z" ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Base | | Module: | mod\_include | This directive changes the format in which date strings are displayed when echoing `DATE` environment variables. The formatstring is as in `strftime(3)` from the C standard library. This directive has the same effect as the `<!--#config timefmt=formatstring -->` element. ``` SSITimeFormat "%R, %B %d, %Y" ``` The above directive would cause times to be displayed in the format "22:26, June 14, 2002". SSIUndefinedEcho Directive -------------------------- | | | | --- | --- | | Description: | String displayed when an unset variable is echoed | | Syntax: | ``` SSIUndefinedEcho string ``` | | Default: | ``` SSIUndefinedEcho "(none)" ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Base | | Module: | mod\_include | This directive changes the string that `<mod_include>` displays when a variable is not set and "echoed". ``` SSIUndefinedEcho "<!-- undef -->" ``` XBitHack Directive ------------------ | | | | --- | --- | | Description: | Parse SSI directives in files with the execute bit set | | Syntax: | ``` XBitHack on|off|full ``` | | Default: | ``` XBitHack off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Base | | Module: | mod\_include | The `XBitHack` directive controls the parsing of ordinary html documents. This directive only affects files associated with the [MIME-type](https://httpd.apache.org/docs/2.4/en/glossary.html#mime-type "see glossary") `text/html`. `XBitHack` can take on the following values: `off` No special treatment of executable files. `on` Any `text/html` file that has the user-execute bit set will be treated as a server-parsed html document. `full` As for `on` but also test the group-execute bit. If it is set, then set the `Last-modified` date of the returned file to be the last modified time of the file. If it is not set, then no last-modified date is sent. Setting this bit allows clients and proxies to cache the result of the request. **Note** You would not want to use the full option, unless you assure the group-execute bit is unset for every SSI script which might `#include` a CGI or otherwise produces different output on each hit (or could potentially change on subsequent requests). The `[SSILastModified](#ssilastmodified)` directive takes precedence over the `[XBitHack](#xbithack)` directive when `[SSILastModified](#ssilastmodified)` is set to `on`.
programming_docs
apache_http_server Apache Module mod_remoteip Apache Module mod\_remoteip =========================== | | | | --- | --- | | Description: | Replaces the original client IP address for the connection with the useragent IP address list presented by a proxies or a load balancer via the request headers. | | Status: | Base | | Module Identifier: | remoteip\_module | | Source File: | mod\_remoteip.c | ### Summary This module is used to treat the useragent which initiated the request as the originating useragent as identified by httpd for the purposes of authorization and logging, even where that useragent is behind a load balancer, front end server, or proxy server. The module overrides the client IP address for the connection with the useragent IP address reported in the request header configured with the `[RemoteIPHeader](#remoteipheader)` directive. Additionally, this module implements the server side of HAProxy's [PROXY Protocol](http://blog.haproxy.com/haproxy/proxy-protocol/) when using the `[RemoteIPProxyProtocol](#remoteipproxyprotocol)` directive. Once replaced as instructed, this overridden useragent IP address is then used for the `<mod_authz_host>` `[Require ip](mod_authz_core#require)` feature, is reported by `<mod_status>`, and is recorded by `<mod_log_config>` `%a` and `<core>` `%a` format strings. The underlying client IP of the connection is available in the `%{c}a` format string. It is critical to only enable this behavior from intermediate hosts (proxies, etc) which are trusted by this server, since it is trivial for the remote useragent to impersonate another useragent. Remote IP Processing -------------------- Apache by default identifies the useragent with the connection's client\_ip value, and the connection remote\_host and remote\_logname are derived from this value. These fields play a role in authentication, authorization and logging and other purposes by other loadable modules. mod\_remoteip overrides the client IP of the connection with the advertised useragent IP as provided by a proxy or load balancer, for the duration of the request. A load balancer might establish a long lived keepalive connection with the server, and each request will have the correct useragent IP, even though the underlying client IP address of the load balancer remains unchanged. When multiple, comma delimited useragent IP addresses are listed in the header value, they are processed in Right-to-Left order. Processing halts when a given useragent IP address is not trusted to present the preceding IP address. The header field is updated to this remaining list of unconfirmed IP addresses, or if all IP addresses were trusted, this header is removed from the request altogether. In overriding the client IP, the module stores the list of intermediate hosts in a remoteip-proxy-ip-list note, which `<mod_log_config>` can record using the `%{remoteip-proxy-ip-list}n` format token. If the administrator needs to store this as an additional header, this same value can also be recording as a header using the directive `[RemoteIPProxiesHeader](#remoteipproxiesheader)`. **IPv4-over-IPv6 Mapped Addresses** As with httpd in general, any IPv4-over-IPv6 mapped addresses are recorded in their IPv4 representation. **Internal (Private) Addresses** All internal addresses 10/8, 172.16/12, 192.168/16, 169.254/16 and 127/8 blocks (and IPv6 addresses outside of the public 2000::/3 block) are only evaluated by mod\_remoteip when `[RemoteIPInternalProxy](#remoteipinternalproxy)` internal (intranet) proxies are registered. RemoteIPHeader Directive ------------------------ | | | | --- | --- | | Description: | Declare the header field which should be parsed for useragent IP addresses | | Syntax: | ``` RemoteIPHeader header-field ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_remoteip | The `[RemoteIPHeader](#remoteipheader)` directive triggers `<mod_remoteip>` to treat the value of the specified header-field header as the useragent IP address, or list of intermediate useragent IP addresses, subject to further configuration of the `[RemoteIPInternalProxy](#remoteipinternalproxy)` and `[RemoteIPTrustedProxy](#remoteiptrustedproxy)` directives. Unless these other directives are used, `<mod_remoteip>` will trust all hosts presenting a `[RemoteIPHeader](#remoteipheader)` IP value. ### Internal (Load Balancer) Example ``` RemoteIPHeader X-Client-IP ``` ### Proxy Example ``` RemoteIPHeader X-Forwarded-For ``` RemoteIPInternalProxy Directive ------------------------------- | | | | --- | --- | | Description: | Declare client intranet IP addresses trusted to present the RemoteIPHeader value | | Syntax: | ``` RemoteIPInternalProxy proxy-ip|proxy-ip/subnet|hostname ... ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_remoteip | The `[RemoteIPInternalProxy](#remoteipinternalproxy)` directive adds one or more addresses (or address blocks) to trust as presenting a valid RemoteIPHeader value of the useragent IP. Unlike the `[RemoteIPTrustedProxy](#remoteiptrustedproxy)` directive, any IP address presented in this header, including private intranet addresses, are trusted when passed from these proxies. ### Internal (Load Balancer) Example ``` RemoteIPHeader X-Client-IP RemoteIPInternalProxy 10.0.2.0/24 RemoteIPInternalProxy gateway.localdomain ``` RemoteIPInternalProxyList Directive ----------------------------------- | | | | --- | --- | | Description: | Declare client intranet IP addresses trusted to present the RemoteIPHeader value | | Syntax: | ``` RemoteIPInternalProxyList filename ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_remoteip | The `[RemoteIPInternalProxyList](#remoteipinternalproxylist)` directive specifies a file parsed at startup, and builds a list of addresses (or address blocks) to trust as presenting a valid RemoteIPHeader value of the useragent IP. The '`#`' hash character designates a comment line, otherwise each whitespace or newline separated entry is processed identically to the `[RemoteIPInternalProxy](#remoteipinternalproxy)` directive. ### Internal (Load Balancer) Example ``` RemoteIPHeader X-Client-IP RemoteIPInternalProxyList conf/trusted-proxies.lst ``` ### conf/trusted-proxies.lst contents ``` # Our internally trusted proxies; 10.0.2.0/24 #Everyone in the testing group gateway.localdomain #The front end balancer ``` RemoteIPProxiesHeader Directive ------------------------------- | | | | --- | --- | | Description: | Declare the header field which will record all intermediate IP addresses | | Syntax: | ``` RemoteIPProxiesHeader HeaderFieldName ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_remoteip | The `[RemoteIPProxiesHeader](#remoteipproxiesheader)` directive specifies a header into which `<mod_remoteip>` will collect a list of all of the intermediate client IP addresses trusted to resolve the useragent IP of the request. Note that intermediate `[RemoteIPTrustedProxy](#remoteiptrustedproxy)` addresses are recorded in this header, while any intermediate `[RemoteIPInternalProxy](#remoteipinternalproxy)` addresses are discarded. ### Example ``` RemoteIPHeader X-Forwarded-For RemoteIPProxiesHeader X-Forwarded-By ``` RemoteIPProxyProtocol Directive ------------------------------- | | | | --- | --- | | Description: | Enable or disable PROXY protocol handling | | Syntax: | ``` RemoteIPProxyProtocol On|Off ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_remoteip | | Compatibility: | RemoteIPProxyProtocol is only available in httpd 2.4.31 and newer | The `RemoteIPProxyProtocol` directive enables or disables the reading and handling of the PROXY protocol connection header. If enabled with the `On` flag, the upstream client *must* send the header every time it opens a connection or the connection will be aborted unless it is in the list of disabled hosts provided by the `[RemoteIPProxyProtocolExceptions](#remoteipproxyprotocolexceptions)` directive. While this directive may be specified in any virtual host, it is important to understand that because the PROXY protocol is connection based and protocol agnostic, the enabling and disabling is actually based on IP address and port. This means that if you have multiple name-based virtual hosts for the same host and port, and you enable it for any one of them, then it is enabled for all of them (with that host and port). It also means that if you attempt to enable the PROXY protocol in one and disable in the other, that won't work; in such a case, the last one wins and a notice will be logged indicating which setting was being overridden. ``` Listen 80 <VirtualHost *:80> ServerName www.example.com RemoteIPProxyProtocol On #Requests to this virtual host must have a PROXY protocol # header provided. If it is missing, the connection will # be aborted </VirtualHost> Listen 8080 <VirtualHost *:8080> ServerName www.example.com RemoteIPProxyProtocol On RemoteIPProxyProtocolExceptions 127.0.0.1 10.0.0.0/8 #Requests to this virtual host must have a PROXY protocol # header provided. If it is missing, the connection will # be aborted except when coming from localhost or the # 10.x.x.x RFC1918 range </VirtualHost> ``` RemoteIPProxyProtocolExceptions Directive ----------------------------------------- | | | | --- | --- | | Description: | Disable processing of PROXY header for certain hosts or networks | | Syntax: | ``` RemoteIPProxyProtocolExceptions host|range [host|range] [host|range] ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_remoteip | | Compatibility: | RemoteIPProxyProtocolExceptions is only available in httpd 2.4.31 and newer | The `RemoteIPProxyProtocol` directive enables or disables the reading and handling of the PROXY protocol connection header. Sometimes it is desirable to require clients to provide the PROXY header, but permit other clients to connect without it. This directive allows a server administrator to configure a single host or CIDR range of hosts that may do so. This is generally useful for monitoring and administrative traffic to a virtual host direct to the server behind the upstream load balancer. RemoteIPTrustedProxy Directive ------------------------------ | | | | --- | --- | | Description: | Declare client intranet IP addresses trusted to present the RemoteIPHeader value | | Syntax: | ``` RemoteIPTrustedProxy proxy-ip|proxy-ip/subnet|hostname ... ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_remoteip | The `[RemoteIPTrustedProxy](#remoteiptrustedproxy)` directive adds one or more addresses (or address blocks) to trust as presenting a valid RemoteIPHeader value of the useragent IP. Unlike the `[RemoteIPInternalProxy](#remoteipinternalproxy)` directive, any intranet or private IP address reported by such proxies, including the 10/8, 172.16/12, 192.168/16, 169.254/16 and 127/8 blocks (or outside of the IPv6 public 2000::/3 block) are not trusted as the useragent IP, and are left in the `[RemoteIPHeader](#remoteipheader)` header's value. ### Trusted (Load Balancer) Example ``` RemoteIPHeader X-Forwarded-For RemoteIPTrustedProxy 10.0.2.16/28 RemoteIPTrustedProxy proxy.example.com ``` RemoteIPTrustedProxyList Directive ---------------------------------- | | | | --- | --- | | Description: | Declare client intranet IP addresses trusted to present the RemoteIPHeader value | | Syntax: | ``` RemoteIPTrustedProxyList filename ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_remoteip | The `[RemoteIPTrustedProxyList](#remoteiptrustedproxylist)` directive specifies a file parsed at startup, and builds a list of addresses (or address blocks) to trust as presenting a valid RemoteIPHeader value of the useragent IP. The '`#`' hash character designates a comment line, otherwise each whitespace or newline separated entry is processed identically to the `[RemoteIPTrustedProxy](#remoteiptrustedproxy)` directive. ### Trusted (Load Balancer) Example ``` RemoteIPHeader X-Forwarded-For RemoteIPTrustedProxyList conf/trusted-proxies.lst ``` ### conf/trusted-proxies.lst contents ``` # Identified external proxies; 192.0.2.16/28 #wap phone group of proxies proxy.isp.example.com #some well known ISP ``` apache_http_server Apache Module mod_setenvif Apache Module mod\_setenvif =========================== | | | | --- | --- | | Description: | Allows the setting of environment variables based on characteristics of the request | | Status: | Base | | Module Identifier: | setenvif\_module | | Source File: | mod\_setenvif.c | ### Summary The `<mod_setenvif>` module allows you to set internal environment variables according to whether different aspects of the request match regular expressions you specify. These environment variables can be used by other parts of the server to make decisions about actions to be taken, as well as becoming available to CGI scripts and SSI pages. The directives are considered in the order they appear in the configuration files. So more complex sequences can be used, such as this example, which sets `netscape` if the browser is mozilla but not MSIE. ``` BrowserMatch ^Mozilla netscape BrowserMatch MSIE !netscape ``` When the server looks up a path via an internal [subrequest](https://httpd.apache.org/docs/2.4/en/glossary.html#subrequest "see glossary") such as looking for a `[DirectoryIndex](mod_dir#directoryindex)` or generating a directory listing with `<mod_autoindex>`, per-request environment variables are *not* inherited in the subrequest. Additionally, `[SetEnvIf](#setenvif)` directives are not separately evaluated in the subrequest due to the API phases `<mod_setenvif>` takes action in. BrowserMatch Directive ---------------------- | | | | --- | --- | | Description: | Sets environment variables conditional on HTTP User-Agent | | Syntax: | ``` BrowserMatch regex [!]env-variable[=value] [[!]env-variable[=value]] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_setenvif | The `BrowserMatch` is a special cases of the `[SetEnvIf](#setenvif)` directive that sets environment variables conditional on the `User-Agent` HTTP request header. The following two lines have the same effect: ``` BrowserMatch Robot is_a_robot SetEnvIf User-Agent Robot is_a_robot ``` Some additional examples: ``` BrowserMatch ^Mozilla forms jpeg=yes browser=netscape BrowserMatch "^Mozilla/[2-3]" tables agif frames javascript BrowserMatch MSIE !javascript ``` BrowserMatchNoCase Directive ---------------------------- | | | | --- | --- | | Description: | Sets environment variables conditional on User-Agent without respect to case | | Syntax: | ``` BrowserMatchNoCase regex [!]env-variable[=value] [[!]env-variable[=value]] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_setenvif | The `BrowserMatchNoCase` directive is semantically identical to the `[BrowserMatch](#browsermatch)` directive. However, it provides for case-insensitive matching. For example: ``` BrowserMatchNoCase mac platform=macintosh BrowserMatchNoCase win platform=windows ``` The `BrowserMatch` and `BrowserMatchNoCase` directives are special cases of the `[SetEnvIf](#setenvif)` and `[SetEnvIfNoCase](#setenvifnocase)` directives. The following two lines have the same effect: ``` BrowserMatchNoCase Robot is_a_robot SetEnvIfNoCase User-Agent Robot is_a_robot ``` SetEnvIf Directive ------------------ | | | | --- | --- | | Description: | Sets environment variables based on attributes of the request | | Syntax: | ``` SetEnvIf attribute regex [!]env-variable[=value] [[!]env-variable[=value]] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_setenvif | The `SetEnvIf` directive defines environment variables based on attributes of the request. The *attribute* specified in the first argument can be one of four things: 1. An HTTP request header field (see [RFC2616](http://www.rfc-editor.org/rfc/rfc2616.txt) for more information about these); for example: `Host`, `User-Agent`, `Referer`, and `Accept-Language`. A regular expression may be used to specify a set of request headers. 2. One of the following aspects of the request: * `Remote_Host` - the hostname (if available) of the client making the request * `Remote_Addr` - the IP address of the client making the request * `Server_Addr` - the IP address of the server on which the request was received (only with versions later than 2.0.43) * `Request_Method` - the name of the method being used (`GET`, `POST`, *et cetera*) * `Request_Protocol` - the name and version of the protocol with which the request was made (*e.g.*, "HTTP/0.9", "HTTP/1.1", *etc.*) * `Request_URI` - the resource requested on the HTTP request line -- generally the portion of the URL following the scheme and host portion without the query string. See the `[RewriteCond](mod_rewrite#rewritecond)` directive of `<mod_rewrite>` for extra information on how to match your query string. 3. The name of an environment variable in the list of those associated with the request. This allows `SetEnvIf` directives to test against the result of prior matches. Only those environment variables defined by earlier `SetEnvIf[NoCase]` directives are available for testing in this manner. 'Earlier' means that they were defined at a broader scope (such as server-wide) or previously in the current directive's scope. Environment variables will be considered only if there was no match among request characteristics and a regular expression was not used for the *attribute*. The second argument (*regex*) is a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"). If the *regex* matches against the *attribute*, then the remainder of the arguments are evaluated. The rest of the arguments give the names of variables to set, and optionally values to which they should be set. These take the form of 1. `*varname*`, or 2. `!*varname*`, or 3. `*varname*=*value*` In the first form, the value will be set to "1". The second will remove the given variable if already defined, and the third will set the variable to the literal value given by `*value*`. Since version 2.0.51, Apache httpd will recognize occurrences of `$1`..`$9` within value and replace them by parenthesized subexpressions of regex. `$0` provides access to the whole string matched by that pattern. ``` SetEnvIf Request_URI "\.gif$" object_is_image=gif SetEnvIf Request_URI "\.jpg$" object_is_image=jpg SetEnvIf Request_URI "\.xbm$" object_is_image=xbm SetEnvIf Referer www\.mydomain\.example\.com intra_site_referral SetEnvIf object_is_image xbm XBIT_PROCESSING=1 SetEnvIf Request_URI "\.(.*)$" EXTENSION=$1 SetEnvIf ^TS ^[a-z] HAVE_TS ``` The first three will set the environment variable `object_is_image` if the request was for an image file, and the fourth sets `intra_site_referral` if the referring page was somewhere on the `www.mydomain.example.com` Web site. The last example will set environment variable `HAVE_TS` if the request contains any headers that begin with "TS" whose values begins with any character in the set [a-z]. ### See also * [Environment Variables in Apache HTTP Server](../env), for additional examples. SetEnvIfExpr Directive ---------------------- | | | | --- | --- | | Description: | Sets environment variables based on an ap\_expr expression | | Syntax: | ``` SetEnvIfExpr expr [!]env-variable[=value] [[!]env-variable[=value]] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_setenvif | The `SetEnvIfExpr` directive defines environment variables based on an `[<If>](core#if)` `ap_expr`. These expressions will be evaluated at runtime, and applied *env-variable* in the same fashion as `SetEnvIf`. ``` SetEnvIfExpr "tolower(req('X-Sendfile')) == 'd:\images\very_big.iso')" iso_delivered ``` This would set the environment variable `iso_delivered` every time our application attempts to send it via `X-Sendfile` A more useful example would be to set the variable rfc1918 if the remote IP address is a private address according to RFC 1918: ``` SetEnvIfExpr "-R '10.0.0.0/8' || -R '172.16.0.0/12' || -R '192.168.0.0/16'" rfc1918 ``` ### See also * [Expressions in Apache HTTP Server](../expr), for a complete reference and more examples. * `[<If>](core#if)` can be used to achieve similar results. * `<mod_filter>` SetEnvIfNoCase Directive ------------------------ | | | | --- | --- | | Description: | Sets environment variables based on attributes of the request without respect to case | | Syntax: | ``` SetEnvIfNoCase attribute regex [!]env-variable[=value] [[!]env-variable[=value]] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_setenvif | The `SetEnvIfNoCase` is semantically identical to the `[SetEnvIf](#setenvif)` directive, and differs only in that the regular expression matching is performed in a case-insensitive manner. For example: ``` SetEnvIfNoCase Host Example\.Org site=example ``` This will cause the `site` environment variable to be set to "`example`" if the HTTP request header field `Host:` was included and contained `Example.Org`, `example.org`, or any other combination.
programming_docs
apache_http_server Apache Module mod_heartmonitor Apache Module mod\_heartmonitor =============================== | | | | --- | --- | | Description: | Centralized monitor for mod\_heartbeat origin servers | | Status: | Experimental | | Module Identifier: | heartmonitor\_module | | Source File: | mod\_heartmonitor.c | | Compatibility: | Available in Apache 2.3 and later | ### Summary `<mod_heartmonitor>` listens for server status messages generated by `<mod_heartbeat>` enabled origin servers and makes their status available to `<mod_lbmethod_heartbeat>`. This allows `[ProxyPass](mod_proxy#proxypass)` to use the "heartbeat" *lbmethod* inside of `[ProxyPass](mod_proxy#proxypass)`. This module uses the services of `<mod_slotmem_shm>` when available instead of flat-file storage. No configuration is required to use `<mod_slotmem_shm>`. To use `<mod_heartmonitor>`, `<mod_status>` and `<mod_watchdog>` must be either a static modules or, if a dynamic module, it must be loaded before `<mod_heartmonitor>`. HeartbeatListen Directive ------------------------- | | | | --- | --- | | Description: | multicast address to listen for incoming heartbeat requests | | Syntax: | ``` HeartbeatListen addr:port ``` | | Default: | `disabled` | | Context: | server config | | Status: | Experimental | | Module: | mod\_heartmonitor | The `HeartbeatListen` directive specifies the multicast address on which the server will listen for status information from `<mod_heartbeat>`-enabled servers. This address will usually correspond to a configured `[HeartbeatAddress](mod_heartbeat#heartbeataddress)` on an origin server. ``` HeartbeatListen 239.0.0.1:27999 ``` This module is inactive until this directive is used. HeartbeatMaxServers Directive ----------------------------- | | | | --- | --- | | Description: | Specifies the maximum number of servers that will be sending heartbeat requests to this server | | Syntax: | ``` HeartbeatMaxServers number-of-servers ``` | | Default: | ``` HeartbeatMaxServers 10 ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_heartmonitor | The `HeartbeatMaxServers` directive specifies the maximum number of servers that will be sending requests to this monitor server. It is used to control the size of the shared memory allocated to store the heartbeat info when `<mod_slotmem_shm>` is in use. HeartbeatStorage Directive -------------------------- | | | | --- | --- | | Description: | Path to store heartbeat data | | Syntax: | ``` HeartbeatStorage file-path ``` | | Default: | ``` HeartbeatStorage logs/hb.dat ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_heartmonitor | The `HeartbeatStorage` directive specifies the path to store heartbeat data. This flat-file is used only when `<mod_slotmem_shm>` is not loaded. apache_http_server Apache Module mod_deflate Apache Module mod\_deflate ========================== | | | | --- | --- | | Description: | Compress content before it is delivered to the client | | Status: | Extension | | Module Identifier: | deflate\_module | | Source File: | mod\_deflate.c | ### Summary The `<mod_deflate>` module provides the `DEFLATE` output filter that allows output from your server to be compressed before being sent to the client over the network. Supported Encodings ------------------- The `gzip` encoding is the only one supported to ensure complete compatibility with old browser implementations. The `deflate` encoding is not supported, please check the [zlib's documentation](https://zlib.net/zlib_faq.html#faq39) for a complete explanation. Sample Configurations --------------------- **Compression and TLS** Some web applications are vulnerable to an information disclosure attack when a TLS connection carries deflate compressed data. For more information, review the details of the "BREACH" family of attacks. This is a simple configuration that compresses common text-based content types. ### Compress only a few types ``` AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript ``` Enabling Compression -------------------- **Compression and TLS** Some web applications are vulnerable to an information disclosure attack when a TLS connection carries deflate compressed data. For more information, review the details of the "BREACH" family of attacks. ### Output Compression Compression is implemented by the `DEFLATE` [filter](../filter). The following directive will enable compression for documents in the container where it is placed: ``` SetOutputFilter DEFLATE SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip ``` If you want to restrict the compression to particular MIME types in general, you may use the `[AddOutputFilterByType](mod_filter#addoutputfilterbytype)` directive. Here is an example of enabling compression only for the html files of the Apache documentation: ``` <Directory "/your-server-root/manual"> AddOutputFilterByType DEFLATE text/html </Directory> ``` **Note** The `DEFLATE` filter is always inserted after RESOURCE filters like PHP or SSI. It never touches internal subrequests. **Note** There is an environment variable `force-gzip`, set via `[SetEnv](mod_env#setenv)`, which will ignore the accept-encoding setting of your browser and will send compressed output. ### Output Decompression The `<mod_deflate>` module also provides a filter for inflating/uncompressing a gzip compressed response body. In order to activate this feature you have to insert the `INFLATE` filter into the output filter chain using `[SetOutputFilter](core#setoutputfilter)` or `[AddOutputFilter](mod_mime#addoutputfilter)`, for example: ``` <Location "/dav-area"> ProxyPass "http://example.com/" SetOutputFilter INFLATE </Location> ``` This Example will uncompress gzip'ed output from example.com, so other filters can do further processing with it. ### Input Decompression The `<mod_deflate>` module also provides a filter for decompressing a gzip compressed request body . In order to activate this feature you have to insert the `DEFLATE` filter into the input filter chain using `[SetInputFilter](core#setinputfilter)` or `[AddInputFilter](mod_mime#addinputfilter)`, for example: ``` <Location "/dav-area"> SetInputFilter DEFLATE </Location> ``` Now if a request contains a `Content-Encoding: gzip` header, the body will be automatically decompressed. Few browsers have the ability to gzip request bodies. However, some special applications actually do support request compression, for instance some [WebDAV](http://www.webdav.org) clients. **Note on Content-Length** If you evaluate the request body yourself, *don't trust the `Content-Length` header!* The Content-Length header reflects the length of the incoming data from the client and *not* the byte count of the decompressed data stream. Dealing with proxy servers -------------------------- The `<mod_deflate>` module sends a `Vary: Accept-Encoding` HTTP response header to alert proxies that a cached response should be sent only to clients that send the appropriate `Accept-Encoding` request header. This prevents compressed content from being sent to a client that will not understand it. If you use some special exclusions dependent on, for example, the `User-Agent` header, you must manually configure an addition to the `Vary` header to alert proxies of the additional restrictions. For example, in a typical configuration where the addition of the `DEFLATE` filter depends on the `User-Agent`, you should add: ``` Header append Vary User-Agent ``` If your decision about compression depends on other information than request headers (*e.g.* HTTP version), you have to set the `Vary` header to the value `*`. This prevents compliant proxies from caching entirely. ### Example ``` Header set Vary * ``` Serving pre-compressed content ------------------------------ Since `<mod_deflate>` re-compresses content each time a request is made, some performance benefit can be derived by pre-compressing the content and telling `<mod_deflate>` to serve them without re-compressing them. This may be accomplished using a configuration like the following: ``` <IfModule mod_headers.c> # Serve gzip compressed CSS and JS files if they exist # and the client accepts gzip. RewriteCond "%{HTTP:Accept-encoding}" "gzip" RewriteCond "%{REQUEST_FILENAME}\.gz" -s RewriteRule "^(.*)\.(css|js)" "$1\.$2\.gz" [QSA] # Serve correct content types, and prevent mod_deflate double gzip. RewriteRule "\.css\.gz$" "-" [T=text/css,E=no-gzip:1] RewriteRule "\.js\.gz$" "-" [T=text/javascript,E=no-gzip:1] <FilesMatch "(\.js\.gz|\.css\.gz)$"> # Serve correct encoding type. Header append Content-Encoding gzip # Force proxies to cache gzipped & # non-gzipped css/js files separately. Header append Vary Accept-Encoding </FilesMatch> </IfModule> ``` DeflateBufferSize Directive --------------------------- | | | | --- | --- | | Description: | Fragment size to be compressed at one time by zlib | | Syntax: | ``` DeflateBufferSize value ``` | | Default: | ``` DeflateBufferSize 8096 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_deflate | The `DeflateBufferSize` directive specifies the size in bytes of the fragments that zlib should compress at one time. If the compressed response size is bigger than the one specified by this directive then httpd will switch to chunked encoding (HTTP header `Transfer-Encoding` set to `Chunked`), with the side effect of not setting any `Content-Length` HTTP header. This is particularly important when httpd works behind reverse caching proxies or when httpd is configured with `<mod_cache>` and `<mod_cache_disk>` because HTTP responses without any `Content-Length` header might not be cached. DeflateCompressionLevel Directive --------------------------------- | | | | --- | --- | | Description: | How much compression do we apply to the output | | Syntax: | ``` DeflateCompressionLevel value ``` | | Default: | ``` Zlib's default ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_deflate | The `DeflateCompressionLevel` directive specifies what level of compression should be used, the higher the value, the better the compression, but the more CPU time is required to achieve this. The value must between 1 (less compression) and 9 (more compression). DeflateFilterNote Directive --------------------------- | | | | --- | --- | | Description: | Places the compression ratio in a note for logging | | Syntax: | ``` DeflateFilterNote [type] notename ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_deflate | The `DeflateFilterNote` directive specifies that a note about compression ratios should be attached to the request. The name of the note is the value specified for the directive. You can use that note for statistical purposes by adding the value to your [access log](../logs#accesslog). ### Example ``` DeflateFilterNote ratio LogFormat '"%r" %b (%{ratio}n) "%{User-agent}i"' deflate CustomLog "logs/deflate_log" deflate ``` If you want to extract more accurate values from your logs, you can use the type argument to specify the type of data left as a note for logging. type can be one of: `Input` Store the byte count of the filter's input stream in the note. `Output` Store the byte count of the filter's output stream in the note. `Ratio` Store the compression ratio (`output/input * 100`) in the note. This is the default, if the type argument is omitted. Thus you may log it this way: ### Accurate Logging ``` DeflateFilterNote Input instream DeflateFilterNote Output outstream DeflateFilterNote Ratio ratio LogFormat '"%r" %{outstream}n/%{instream}n (%{ratio}n%%)' deflate CustomLog "logs/deflate_log" deflate ``` ### See also * `<mod_log_config>` DeflateInflateLimitRequestBody Directive ---------------------------------------- | | | | --- | --- | | Description: | Maximum size of inflated request bodies | | Syntax: | ``` DeflateInflateLimitRequestBody value ``` | | Default: | ``` None, but LimitRequestBody applies after deflation ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_deflate | | Compatibility: | 2.4.10 and later | The `DeflateInflateLimitRequestBody` directive specifies the maximum size of an inflated request body. If it is unset, `[LimitRequestBody](core#limitrequestbody)` is applied to the inflated body. DeflateInflateRatioBurst Directive ---------------------------------- | | | | --- | --- | | Description: | Maximum number of times the inflation ratio for request bodies can be crossed | | Syntax: | ``` DeflateInflateRatioBurst value ``` | | Default: | ``` DeflateInflateRatioBurst 3 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_deflate | | Compatibility: | 2.4.10 and later | The `DeflateInflateRatioBurst` directive specifies the maximum number of times the `[DeflateInflateRatioLimit](#deflateinflateratiolimit)` can be crossed before terminating the request. DeflateInflateRatioLimit Directive ---------------------------------- | | | | --- | --- | | Description: | Maximum inflation ratio for request bodies | | Syntax: | ``` DeflateInflateRatioLimit value ``` | | Default: | ``` DeflateInflateRatioLimit 200 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_deflate | | Compatibility: | 2.4.10 and later | The `DeflateInflateRatioLimit` directive specifies the maximum ratio of deflated to inflated size of an inflated request body. This ratio is checked as the body is streamed in, and if crossed more than `[DeflateInflateRatioBurst](#deflateinflateratioburst)` times, the request will be terminated. DeflateMemLevel Directive ------------------------- | | | | --- | --- | | Description: | How much memory should be used by zlib for compression | | Syntax: | ``` DeflateMemLevel value ``` | | Default: | ``` DeflateMemLevel 9 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_deflate | The `DeflateMemLevel` directive specifies how much memory should be used by zlib for compression (a value between 1 and 9). DeflateWindowSize Directive --------------------------- | | | | --- | --- | | Description: | Zlib compression window size | | Syntax: | ``` DeflateWindowSize value ``` | | Default: | ``` DeflateWindowSize 15 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_deflate | The `DeflateWindowSize` directive specifies the zlib compression window size (a value between 1 and 15). Generally, the higher the window size, the higher can the compression ratio be expected. apache_http_server Apache Module mod_ratelimit Apache Module mod\_ratelimit ============================ | | | | --- | --- | | Description: | Bandwidth Rate Limiting for Clients | | Status: | Extension | | Module Identifier: | ratelimit\_module | | Source File: | mod\_ratelimit.c | | Compatibility: | `rate-initial-burst` available in httpd 2.4.24 and later. Rate limiting proxied content does not work correctly up to httpd 2.4.33. | ### Summary Provides a filter named `RATE_LIMIT` to limit client bandwidth. The throttling is applied to each HTTP response while it is transferred to the client, and not aggregated at IP/client level. The connection speed to be simulated is specified, in KiB/s, using the environment variable `rate-limit`. Optionally, an initial amount of burst data, in KiB, may be configured to be passed at full speed before throttling to the specified rate limit. This value is optional, and is set using the environment variable `rate-initial-burst`. ### Example Configuration ``` <Location "/downloads"> SetOutputFilter RATE_LIMIT SetEnv rate-limit 400 SetEnv rate-initial-burst 512 </Location> ``` If the value specified for `rate-limit` causes integer overflow, the rate-limited will be disabled. If the value specified for `rate-limit-burst` causes integer overflow, the burst will be disabled. apache_http_server Apache Module mod_lbmethod_byrequests Apache Module mod\_lbmethod\_byrequests ======================================= | | | | --- | --- | | Description: | Request Counting load balancer scheduler algorithm for `<mod_proxy_balancer>` | | Status: | Extension | | Module Identifier: | lbmethod\_byrequests\_module | | Source File: | mod\_lbmethod\_byrequests.c | | Compatibility: | Split off from `<mod_proxy_balancer>` in 2.3 | ### Summary This module does not provide any configuration directives of its own. It requires the services of `<mod_proxy_balancer>`, and provides the `byrequests` load balancing method. Request Counting Algorithm -------------------------- Enabled via `lbmethod=byrequests`, the idea behind this scheduler is that we distribute the requests among the various workers to ensure that each gets their configured share of the number of requests. It works as follows: lbfactor is *how much we expect this worker to work*, or *the workers' work quota*. This is a normalized value representing their "share" of the amount of work to be done. lbstatus is *how urgent this worker has to work to fulfill its quota of work*. The worker is a member of the load balancer, usually a remote host serving one of the supported protocols. We distribute each worker's work quota to the worker, and then look which of them needs to work most urgently (biggest lbstatus). This worker is then selected for work, and its lbstatus reduced by the total work quota we distributed to all workers. Thus the sum of all lbstatus does not change(\*) and we distribute the requests as desired. If some workers are disabled, the others will still be scheduled correctly. ``` for each worker in workers worker lbstatus += worker lbfactor total factor += worker lbfactor if worker lbstatus > candidate lbstatus candidate = worker candidate lbstatus -= total factor ``` If a balancer is configured as follows: | worker | a | b | c | d | | --- | --- | --- | --- | --- | | lbfactor | 25 | 25 | 25 | 25 | | lbstatus | 0 | 0 | 0 | 0 | And b gets disabled, the following schedule is produced: | worker | a | b | c | d | | --- | --- | --- | --- | --- | | lbstatus | *-50* | 0 | 25 | 25 | | lbstatus | -25 | 0 | *-25* | 50 | | lbstatus | 0 | 0 | 0 | *0* | | (repeat) | That is it schedules: a c d a c d a c d ... Please note that: | worker | a | b | c | d | | --- | --- | --- | --- | --- | | lbfactor | 25 | 25 | 25 | 25 | Has the exact same behavior as: | worker | a | b | c | d | | --- | --- | --- | --- | --- | | lbfactor | 1 | 1 | 1 | 1 | This is because all values of lbfactor are normalized with respect to the others. For: | worker | a | b | c | | --- | --- | --- | --- | | lbfactor | 1 | 4 | 1 | worker b will, on average, get 4 times the requests that a and c will. The following asymmetric configuration works as one would expect: | worker | a | b | | --- | --- | --- | | lbfactor | 70 | 30 | | | | lbstatus | *-30* | 30 | | lbstatus | 40 | *-40* | | lbstatus | *10* | -10 | | lbstatus | *-20* | 20 | | lbstatus | *-50* | 50 | | lbstatus | 20 | *-20* | | lbstatus | *-10* | 10 | | lbstatus | *-40* | 40 | | lbstatus | 30 | *-30* | | lbstatus | *0* | 0 | | (repeat) | That is after 10 schedules, the schedule repeats and 7 a are selected with 3 b interspersed. apache_http_server Apache Module mod_allowmethods Apache Module mod\_allowmethods =============================== | | | | --- | --- | | Description: | Easily restrict what HTTP methods can be used on the server | | Status: | Experimental | | Module Identifier: | allowmethods\_module | | Source File: | mod\_allowmethods.c | | Compatibility: | Available in Apache 2.3 and later | ### Summary This module makes it easy to restrict what HTTP methods can be used on a server. The most common configuration would be: ``` <Location "/"> AllowMethods GET POST OPTIONS </Location> ``` AllowMethods Directive ---------------------- | | | | --- | --- | | Description: | Restrict access to the listed HTTP methods | | Syntax: | ``` AllowMethods reset|HTTP-method [HTTP-method]... ``` | | Default: | ``` AllowMethods reset ``` | | Context: | directory | | Status: | Experimental | | Module: | mod\_allowmethods | The HTTP-methods are case sensitive and are generally, as per RFC, given in upper case. The GET and HEAD methods are treated as equivalent. The `reset` keyword can be used to turn off `<mod_allowmethods>` in a deeper nested context: ``` <Location "/svn"> AllowMethods reset </Location> ``` **Caution** The TRACE method cannot be denied by this module; use `[TraceEnable](core#traceenable)` instead. `<mod_allowmethods>` was written to replace the rather kludgy implementation of `[Limit](core#limit)` and `[LimitExcept](core#limitexcept)`.
programming_docs
apache_http_server Apache Module mod_usertrack Apache Module mod\_usertrack ============================ | | | | --- | --- | | Description: | *Clickstream* logging of user activity on a site | | Status: | Extension | | Module Identifier: | usertrack\_module | | Source File: | mod\_usertrack.c | ### Summary Provides tracking of a user through your website via browser cookies. Logging ------- `<mod_usertrack>` sets a cookie which can be logged via `<mod_log_config>` configurable logging formats: ``` LogFormat "%{Apache}n %r %t" usertrack CustomLog "logs/clickstream.log" usertrack ``` CookieDomain Directive ---------------------- | | | | --- | --- | | Description: | The domain to which the tracking cookie applies | | Syntax: | ``` CookieDomain domain ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_usertrack | This directive controls the setting of the domain to which the tracking cookie applies. If not present, no domain is included in the cookie header field. The domain string **must** begin with a dot, and **must** include at least one embedded dot. That is, `.example.com` is legal, but `www.example.com` and `.com` are not. Most browsers in use today will not allow cookies to be set for a two-part top level domain, such as `.co.uk`, although such a domain ostensibly fulfills the requirements above. These domains are equivalent to top level domains such as `.com`, and allowing such cookies may be a security risk. Thus, if you are under a two-part top level domain, you should still use your actual domain, as you would with any other top level domain (for example `.example.co.uk`). ``` CookieDomain .example.com ``` CookieExpires Directive ----------------------- | | | | --- | --- | | Description: | Expiry time for the tracking cookie | | Syntax: | ``` CookieExpires expiry-period ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_usertrack | When used, this directive sets an expiry time on the cookie generated by the usertrack module. The *expiry-period* can be given either as a number of seconds, or in the format such as "2 weeks 3 days 7 hours". Valid denominations are: years, months, weeks, days, hours, minutes and seconds. If the expiry time is in any format other than one number indicating the number of seconds, it must be enclosed by double quotes. If this directive is not used, cookies last only for the current browser session. ``` CookieExpires "3 weeks" ``` CookieHTTPOnly Directive ------------------------ | | | | --- | --- | | Description: | Adds the 'HTTPOnly' attribute to the cookie | | Syntax: | ``` CookieHTTPOnly on|off ``` | | Default: | ``` CookieHTTPOnly off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_usertrack | | Compatibility: | 2.4.42 and later | When set to 'ON', the 'HTTPOnly' cookie attribute is added to this modules tracking cookie. This attribute instructs browsers to block javascript from reading the value of the cookie. CookieName Directive -------------------- | | | | --- | --- | | Description: | Name of the tracking cookie | | Syntax: | ``` CookieName token ``` | | Default: | ``` CookieName Apache ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_usertrack | This directive allows you to change the name of the cookie this module uses for its tracking purposes. By default the cookie is named "`Apache`". You must specify a valid cookie name; results are unpredictable if you use a name containing unusual characters. Valid characters include A-Z, a-z, 0-9, "\_", and "-". ``` CookieName clicktrack ``` CookieSameSite Directive ------------------------ | | | | --- | --- | | Description: | Adds the 'SameSite' attribute to the cookie | | Syntax: | ``` CookieSameSite None|Lax|Strict ``` | | Default: | `unset` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_usertrack | | Compatibility: | 2.4.42 and later | When set to 'None', 'Lax', or 'Strict', the 'SameSite' cookie attribute is added to this modules tracking cookie with the corresponding value. This attribute instructs browser on how to treat the cookie when it is requested in a cross-site context. A value of 'None' sets 'SameSite=None', which is the most liberal setting. To omit this attribute, omit the directive entirely. CookieSecure Directive ---------------------- | | | | --- | --- | | Description: | Adds the 'Secure' attribute to the cookie | | Syntax: | ``` CookieSecure on|off ``` | | Default: | ``` CookieSecure off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_usertrack | | Compatibility: | 2.4.42 and later | When set to 'ON', the 'Secure' cookie attribute is added to this modules tracking cookie. This attribute instructs browsers to only transmit the cookie over HTTPS. CookieStyle Directive --------------------- | | | | --- | --- | | Description: | Format of the cookie header field | | Syntax: | ``` CookieStyle Netscape|Cookie|Cookie2|RFC2109|RFC2965 ``` | | Default: | ``` CookieStyle Netscape ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_usertrack | This directive controls the format of the cookie header field. The three formats allowed are: * **Netscape**, which is the original but now deprecated syntax. This is the default, and the syntax Apache has historically used. * **Cookie** or **RFC2109**, which is the syntax that superseded the Netscape syntax. * **Cookie2** or **RFC2965**, which is the most current cookie syntax. Not all clients can understand all of these formats, but you should use the newest one that is generally acceptable to your users' browsers. At the time of writing, most browsers support all three of these formats, with `Cookie2` being the preferred format. ``` CookieStyle Cookie2 ``` CookieTracking Directive ------------------------ | | | | --- | --- | | Description: | Enables tracking cookie | | Syntax: | ``` CookieTracking on|off ``` | | Default: | ``` CookieTracking off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_usertrack | When `<mod_usertrack>` is loaded, and `CookieTracking on` is set, Apache will send a user-tracking cookie for all new requests. This directive can be used to turn this behavior on or off on a per-server or per-directory basis. By default, enabling `<mod_usertrack>` will **not** activate cookies. ``` CookieTracking on ``` apache_http_server Apache Module mod_socache_memcache Apache Module mod\_socache\_memcache ==================================== | | | | --- | --- | | Description: | Memcache based shared object cache provider. | | Status: | Extension | | Module Identifier: | socache\_memcache\_module | | Source File: | mod\_socache\_memcache.c | ### Summary `mod_socache_memcache` is a shared object cache provider which provides for creation and access to a cache backed by the [memcached](http://memcached.org/) high-performance, distributed memory object caching system. This shared object cache provider's "create" method requires a comma separated list of memcached host/port specifications. If using this provider via another modules configuration (such as `[SSLSessionCache](mod_ssl#sslsessioncache)`), provide the list of servers as the optional "arg" parameter. ``` SSLSessionCache memcache:memcache.example.com:12345,memcache2.example.com:12345 ``` Details of other shared object cache providers can be found [here](../socache). MemcacheConnTTL Directive ------------------------- | | | | --- | --- | | Description: | Keepalive time for idle connections | | Syntax: | ``` MemcacheConnTTL num[units] ``` | | Default: | ``` MemcacheConnTTL 15s ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_socache\_memcache | | Compatibility: | Available in Apache 2.4.17 and later | Set the time to keep idle connections with the memcache server(s) alive (threaded platforms only). Valid values for `MemcacheConnTTL` are times up to one hour. 0 means no timeout. This timeout defaults to units of seconds, but accepts suffixes for milliseconds (ms), seconds (s), minutes (min), and hours (h). Before Apache 2.4.17, this timeout was hardcoded and its value was 600 usec. So, the closest configuration to match the legacy behaviour is to set `MemcacheConnTTL` to 1ms. ``` # Set a timeout of 10 minutes MemcacheConnTTL 10min # Set a timeout of 60 seconds MemcacheConnTTL 60 ``` apache_http_server Apache Module mod_access_compat Apache Module mod\_access\_compat ================================= | | | | --- | --- | | Description: | Group authorizations based on host (name or IP address) | | Status: | Extension | | Module Identifier: | access\_compat\_module | | Source File: | mod\_access\_compat.c | | Compatibility: | Available in Apache HTTP Server 2.3 as a compatibility module with previous versions of Apache httpd 2.x. The directives provided by this module have been deprecated by the new authz refactoring. Please see `<mod_authz_host>` | ### Summary The directives provided by `<mod_access_compat>` are used in `[<Directory>](core#directory)`, `[<Files>](core#files)`, and `[<Location>](core#location)` sections as well as `[.htaccess](core#accessfilename)` files to control access to particular parts of the server. Access can be controlled based on the client hostname, IP address, or other characteristics of the client request, as captured in [environment variables](../env). The `[Allow](#allow)` and `[Deny](#deny)` directives are used to specify which clients are or are not allowed access to the server, while the `[Order](#order)` directive sets the default access state, and configures how the `[Allow](#allow)` and `[Deny](#deny)` directives interact with each other. Both host-based access restrictions and password-based authentication may be implemented simultaneously. In that case, the `[Satisfy](#satisfy)` directive is used to determine how the two sets of restrictions interact. **Note** The directives provided by `<mod_access_compat>` have been deprecated by `<mod_authz_host>`. Mixing old directives like `[Order](#order)`, `[Allow](#allow)` or `[Deny](#deny)` with new ones like `[Require](mod_authz_core#require)` is technically possible but discouraged. This module was created to support configurations containing only old directives to facilitate the 2.4 upgrade. Please check the [upgrading](https://httpd.apache.org/docs/2.4/en/upgrading.html) guide for more information. In general, access restriction directives apply to all access methods (`GET`, `PUT`, `POST`, etc). This is the desired behavior in most cases. However, it is possible to restrict some methods, while leaving other methods unrestricted, by enclosing the directives in a `[<Limit>](core#limit)` section. **Merging of configuration sections** When any directive provided by this module is used in a new configuration section, no directives provided by this module are inherited from previous configuration sections. Allow Directive --------------- | | | | --- | --- | | Description: | Controls which hosts can access an area of the server | | Syntax: | ``` Allow from all|host|env=[!]env-variable [host|env=[!]env-variable] ... ``` | | Context: | directory, .htaccess | | Override: | Limit | | Status: | Extension | | Module: | mod\_access\_compat | The `Allow` directive affects which hosts can access an area of the server. Access can be controlled by hostname, IP address, IP address range, or by other characteristics of the client request captured in environment variables. The first argument to this directive is always `from`. The subsequent arguments can take three different forms. If `Allow from all` is specified, then all hosts are allowed access, subject to the configuration of the `[Deny](#deny)` and `[Order](#order)` directives as discussed below. To allow only particular hosts or groups of hosts to access the server, the *host* can be specified in any of the following formats: A (partial) domain-name ``` Allow from example.org Allow from .net example.edu ``` Hosts whose names match, or end in, this string are allowed access. Only complete components are matched, so the above example will match `foo.example.org` but it will not match `fooexample.org`. This configuration will cause Apache httpd to perform a double DNS lookup on the client IP address, regardless of the setting of the `[HostnameLookups](core#hostnamelookups)` directive. It will do a reverse DNS lookup on the IP address to find the associated hostname, and then do a forward lookup on the hostname to assure that it matches the original IP address. Only if the forward and reverse DNS are consistent and the hostname matches will access be allowed. A full IP address ``` Allow from 10.1.2.3 Allow from 192.168.1.104 192.168.1.205 ``` An IP address of a host allowed access A partial IP address ``` Allow from 10.1 Allow from 10 172.20 192.168.2 ``` The first 1 to 3 bytes of an IP address, for subnet restriction. A network/netmask pair ``` Allow from 10.1.0.0/255.255.0.0 ``` A network a.b.c.d, and a netmask w.x.y.z. For more fine-grained subnet restriction. A network/nnn CIDR specification ``` Allow from 10.1.0.0/16 ``` Similar to the previous case, except the netmask consists of nnn high-order 1 bits. Note that the last three examples above match exactly the same set of hosts. IPv6 addresses and IPv6 subnets can be specified as shown below: ``` Allow from 2001:db8::a00:20ff:fea7:ccea Allow from 2001:db8::a00:20ff:fea7:ccea/10 ``` The third format of the arguments to the `Allow` directive allows access to the server to be controlled based on the existence of an [environment variable](../env). When `Allow from env=env-variable` is specified, then the request is allowed access if the environment variable env-variable exists. When `Allow from env=!env-variable` is specified, then the request is allowed access if the environment variable env-variable doesn't exist. The server provides the ability to set environment variables in a flexible way based on characteristics of the client request using the directives provided by `<mod_setenvif>`. Therefore, this directive can be used to allow access based on such factors as the clients `User-Agent` (browser type), `Referer`, or other HTTP request header fields. ``` SetEnvIf User-Agent ^KnockKnock/2\.0 let_me_in <Directory "/docroot"> Order Deny,Allow Deny from all Allow from env=let_me_in </Directory> ``` In this case, browsers with a user-agent string beginning with `KnockKnock/2.0` will be allowed access, and all others will be denied. **Merging of configuration sections** When any directive provided by this module is used in a new configuration section, no directives provided by this module are inherited from previous configuration sections. Deny Directive -------------- | | | | --- | --- | | Description: | Controls which hosts are denied access to the server | | Syntax: | ``` Deny from all|host|env=[!]env-variable [host|env=[!]env-variable] ... ``` | | Context: | directory, .htaccess | | Override: | Limit | | Status: | Extension | | Module: | mod\_access\_compat | This directive allows access to the server to be restricted based on hostname, IP address, or environment variables. The arguments for the `Deny` directive are identical to the arguments for the `[Allow](#allow)` directive. Order Directive --------------- | | | | --- | --- | | Description: | Controls the default access state and the order in which `Allow` and `Deny` are evaluated. | | Syntax: | ``` Order ordering ``` | | Default: | ``` Order Deny,Allow ``` | | Context: | directory, .htaccess | | Override: | Limit | | Status: | Extension | | Module: | mod\_access\_compat | The `Order` directive, along with the `[Allow](#allow)` and `[Deny](#deny)` directives, controls a three-pass access control system. The first pass processes either all `[Allow](#allow)` or all `[Deny](#deny)` directives, as specified by the `[Order](#order)` directive. The second pass parses the rest of the directives (`[Deny](#deny)` or `[Allow](#allow)`). The third pass applies to all requests which do not match either of the first two. Note that all `[Allow](#allow)` and `[Deny](#deny)` directives are processed, unlike a typical firewall, where only the first match is used. The last match is effective (also unlike a typical firewall). Additionally, the order in which lines appear in the configuration files is not significant -- all `[Allow](#allow)` lines are processed as one group, all `[Deny](#deny)` lines are considered as another, and the default state is considered by itself. *Ordering* is one of: `Allow,Deny` First, all `[Allow](#allow)` directives are evaluated; at least one must match, or the request is rejected. Next, all `[Deny](#deny)` directives are evaluated. If any matches, the request is rejected. Last, any requests which do not match an `[Allow](#allow)` or a `[Deny](#deny)` directive are denied by default. `Deny,Allow` First, all `[Deny](#deny)` directives are evaluated; if any match, the request is denied **unless** it also matches an `[Allow](#allow)` directive. Any requests which do not match any `[Allow](#allow)` or `[Deny](#deny)` directives are permitted. `Mutual-failure` This order has the same effect as `Order Allow,Deny` and is deprecated in its favor. Keywords may only be separated by a comma; *no whitespace* is allowed between them. | Match | Allow,Deny result | Deny,Allow result | | --- | --- | --- | | Match Allow only | Request allowed | Request allowed | | Match Deny only | Request denied | Request denied | | No match | Default to second directive: Denied | Default to second directive: Allowed | | Match both Allow & Deny | Final match controls: Denied | Final match controls: Allowed | In the following example, all hosts in the example.org domain are allowed access; all other hosts are denied access. ``` Order Deny,Allow Deny from all Allow from example.org ``` In the next example, all hosts in the example.org domain are allowed access, except for the hosts which are in the foo.example.org subdomain, who are denied access. All hosts not in the example.org domain are denied access because the default state is to `[Deny](#deny)` access to the server. ``` Order Allow,Deny Allow from example.org Deny from foo.example.org ``` On the other hand, if the `Order` in the last example is changed to `Deny,Allow`, all hosts will be allowed access. This happens because, regardless of the actual ordering of the directives in the configuration file, the `Allow from example.org` will be evaluated last and will override the `Deny from foo.example.org`. All hosts not in the `example.org` domain will also be allowed access because the default state is `[Allow](#allow)`. The presence of an `Order` directive can affect access to a part of the server even in the absence of accompanying `[Allow](#allow)` and `[Deny](#deny)` directives because of its effect on the default access state. For example, ``` <Directory "/www"> Order Allow,Deny </Directory> ``` will Deny all access to the `/www` directory because the default access state is set to `[Deny](#deny)`. The `Order` directive controls the order of access directive processing only within each phase of the server's configuration processing. This implies, for example, that an `[Allow](#allow)` or `[Deny](#deny)` directive occurring in a `[<Location>](core#location)` section will always be evaluated after an `[Allow](#allow)` or `[Deny](#deny)` directive occurring in a `[<Directory>](core#directory)` section or `.htaccess` file, regardless of the setting of the `Order` directive. For details on the merging of configuration sections, see the documentation on [How Directory, Location and Files sections work](../sections). **Merging of configuration sections** When any directive provided by this module is used in a new configuration section, no directives provided by this module are inherited from previous configuration sections. Satisfy Directive ----------------- | | | | --- | --- | | Description: | Interaction between host-level access control and user authentication | | Syntax: | ``` Satisfy Any|All ``` | | Default: | ``` Satisfy All ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_access\_compat | | Compatibility: | Influenced by `[<Limit>](core#limit)` and `[<LimitExcept>](core#limitexcept)` in version 2.0.51 and later | Access policy if both `[Allow](#allow)` and `[Require](mod_authz_core#require)` used. The parameter can be either `All` or `Any`. This directive is only useful if access to a particular area is being restricted by both username/password *and* client host address. In this case the default behavior (`All`) is to require that the client passes the address access restriction *and* enters a valid username and password. With the `Any` option the client will be granted access if they either pass the host restriction or enter a valid username and password. This can be used to password restrict an area, but to let clients from particular addresses in without prompting for a password. For example, if you wanted to let people on your network have unrestricted access to a portion of your website, but require that people outside of your network provide a password, you could use a configuration similar to the following: ``` Require valid-user Allow from 192.168.1 Satisfy Any ``` Another frequent use of the `Satisfy` directive is to relax access restrictions for a subdirectory: ``` <Directory "/var/www/private"> Require valid-user </Directory> <Directory "/var/www/private/public"> Allow from all Satisfy Any </Directory> ``` In the above example, authentication will be required for the `/var/www/private` directory, but will not be required for the `/var/www/private/public` directory. Since version 2.0.51 `Satisfy` directives can be restricted to particular methods by `[<Limit>](core#limit)` and `[<LimitExcept>](core#limitexcept)` sections. **Merging of configuration sections** When any directive provided by this module is used in a new configuration section, no directives provided by this module are inherited from previous configuration sections. ### See also * `[Allow](#allow)` * `[Require](mod_authz_core#require)`
programming_docs
apache_http_server Apache Module mod_dbd Apache Module mod\_dbd ====================== | | | | --- | --- | | Description: | Manages SQL database connections | | Status: | Extension | | Module Identifier: | dbd\_module | | Source File: | mod\_dbd.c | | Compatibility: | Version 2.1 and later | ### Summary `<mod_dbd>` manages SQL database connections using [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary"). It provides database connections on request to modules requiring SQL database functions, and takes care of managing databases with optimal efficiency and scalability for both threaded and non-threaded MPMs. For details, see the [APR](http://apr.apache.org/) website and this overview of the [Apache DBD Framework](http://people.apache.org/~niq/dbd.html) by its original developer. Connection Pooling ------------------ This module manages database connections, in a manner optimised for the platform. On non-threaded platforms, it provides a persistent connection in the manner of classic LAMP (Linux, Apache, Mysql, Perl/PHP/Python). On threaded platform, it provides an altogether more scalable and efficient *connection pool*, as described in [this article at ApacheTutor](http://www.apachetutor.org/dev/reslist). Note that `<mod_dbd>` supersedes the modules presented in that article. Connecting ---------- To connect to your database, you'll need to specify a driver, and connection parameters. These vary from one database engine to another. For example, to connect to mysql, do the following: ``` DBDriver mysql DBDParams host=localhost,dbname=pony,user=shetland,pass=appaloosa ``` You can then use this connection in a variety of other modules, including `<mod_rewrite>`, `<mod_authn_dbd>`, and `<mod_lua>`. Further usage examples appear in each of those modules' documentation. See `DBDParams` for connection string information for each of the supported database drivers. Apache DBD API -------------- `<mod_dbd>` exports five functions for other modules to use. The API is as follows: ``` typedef struct { apr_dbd_t *handle; apr_dbd_driver_t *driver; apr_hash_t *prepared; } ap_dbd_t; /* Export functions to access the database */ /* acquire a connection that MUST be explicitly closed. * Returns NULL on error */ AP_DECLARE(ap_dbd_t*) ap_dbd_open(apr_pool_t*, server_rec*); /* release a connection acquired with ap_dbd_open */ AP_DECLARE(void) ap_dbd_close(server_rec*, ap_dbd_t*); /* acquire a connection that will have the lifetime of a request * and MUST NOT be explicitly closed. Return NULL on error. * This is the preferred function for most applications. */ AP_DECLARE(ap_dbd_t*) ap_dbd_acquire(request_rec*); /* acquire a connection that will have the lifetime of a connection * and MUST NOT be explicitly closed. Return NULL on error. */ AP_DECLARE(ap_dbd_t*) ap_dbd_cacquire(conn_rec*); /* Prepare a statement for use by a client module */ AP_DECLARE(void) ap_dbd_prepare(server_rec*, const char*, const char*); /* Also export them as optional functions for modules that prefer it */ APR_DECLARE_OPTIONAL_FN(ap_dbd_t*, ap_dbd_open, (apr_pool_t*, server_rec*)); APR_DECLARE_OPTIONAL_FN(void, ap_dbd_close, (server_rec*, ap_dbd_t*)); APR_DECLARE_OPTIONAL_FN(ap_dbd_t*, ap_dbd_acquire, (request_rec*)); APR_DECLARE_OPTIONAL_FN(ap_dbd_t*, ap_dbd_cacquire, (conn_rec*)); APR_DECLARE_OPTIONAL_FN(void, ap_dbd_prepare, (server_rec*, const char*, const char*)); ``` SQL Prepared Statements ----------------------- `<mod_dbd>` supports SQL prepared statements on behalf of modules that may wish to use them. Each prepared statement must be assigned a name (label), and they are stored in a hash: the `prepared` field of an `ap_dbd_t`. Hash entries are of type `apr_dbd_prepared_t` and can be used in any of the apr\_dbd prepared statement SQL query or select commands. It is up to dbd user modules to use the prepared statements and document what statements can be specified in httpd.conf, or to provide their own directives and use `ap_dbd_prepare`. **Caveat** When using prepared statements with a MySQL database, it is preferred to set `reconnect` to 0 in the connection string as to avoid errors that arise from the MySQL client reconnecting without properly resetting the prepared statements. If set to 1, any broken connections will be attempted fixed, but as mod\_dbd is not informed, the prepared statements will be invalidated. SECURITY WARNING ---------------- Any web/database application needs to secure itself against SQL injection attacks. In most cases, Apache DBD is safe, because applications use prepared statements, and untrusted inputs are only ever used as data. Of course, if you use it via third-party modules, you should ascertain what precautions they may require. However, the FreeTDS driver is inherently **unsafe**. The underlying library doesn't support prepared statements, so the driver emulates them, and the untrusted input is merged into the SQL statement. It can be made safe by *untainting* all inputs: a process inspired by Perl's taint checking. Each input is matched against a regexp, and only the match is used, according to the Perl idiom: ``` $untrusted =~ /([a-z]+)/; $trusted = $1; ``` To use this, the untainting regexps must be included in the prepared statements configured. The regexp follows immediately after the % in the prepared statement, and is enclosed in curly brackets {}. For example, if your application expects alphanumeric input, you can use: ``` "SELECT foo FROM bar WHERE input = %s" ``` with other drivers, and suffer nothing worse than a failed query. But with FreeTDS you'd need: ``` "SELECT foo FROM bar WHERE input = %{([A-Za-z0-9]+)}s" ``` Now anything that doesn't match the regexp's $1 match is discarded, so the statement is safe. An alternative to this may be the third-party ODBC driver, which offers the security of genuine prepared statements. DBDExptime Directive -------------------- | | | | --- | --- | | Description: | Keepalive time for idle connections | | Syntax: | ``` DBDExptime time-in-seconds ``` | | Default: | ``` DBDExptime 300 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_dbd | Set the time to keep idle connections alive when the number of connections specified in DBDKeep has been exceeded (threaded platforms only). DBDInitSQL Directive -------------------- | | | | --- | --- | | Description: | Execute an SQL statement after connecting to a database | | Syntax: | ``` DBDInitSQL "SQL statement" ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_dbd | Modules, that wish it, can have one or more SQL statements executed when a connection to a database is created. Example usage could be initializing certain values or adding a log entry when a new connection is made to the database. DBDKeep Directive ----------------- | | | | --- | --- | | Description: | Maximum sustained number of connections | | Syntax: | ``` DBDKeep number ``` | | Default: | ``` DBDKeep 2 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_dbd | Set the maximum number of connections per process to be sustained, other than for handling peak demand (threaded platforms only). DBDMax Directive ---------------- | | | | --- | --- | | Description: | Maximum number of connections | | Syntax: | ``` DBDMax number ``` | | Default: | ``` DBDMax 10 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_dbd | Set the hard maximum number of connections per process (threaded platforms only). DBDMin Directive ---------------- | | | | --- | --- | | Description: | Minimum number of connections | | Syntax: | ``` DBDMin number ``` | | Default: | ``` DBDMin 1 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_dbd | Set the minimum number of connections per process (threaded platforms only). DBDParams Directive ------------------- | | | | --- | --- | | Description: | Parameters for database connection | | Syntax: | ``` DBDParams param1=value1[,param2=value2] ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_dbd | As required by the underlying driver. Typically this will be used to pass whatever cannot be defaulted amongst username, password, database name, hostname and port number for connection. Connection string parameters for current drivers include: FreeTDS (for MSSQL and SyBase) username, password, appname, dbname, host, charset, lang, server MySQL host, port, user, pass, dbname, sock, flags, fldsz, group, reconnect Oracle user, pass, dbname, server PostgreSQL The connection string is passed straight through to `PQconnectdb` SQLite2 The connection string is split on a colon, and `part1:part2` is used as `sqlite_open(part1, atoi(part2), NULL)` SQLite3 The connection string is passed straight through to `sqlite3_open` ODBC datasource, user, password, connect, ctimeout, stimeout, access, txmode, bufsize DBDPersist Directive -------------------- | | | | --- | --- | | Description: | Whether to use persistent connections | | Syntax: | ``` DBDPersist On|Off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_dbd | If set to Off, persistent and pooled connections are disabled. A new database connection is opened when requested by a client, and closed immediately on release. This option is for debugging and low-usage servers. The default is to enable a pool of persistent connections (or a single LAMP-style persistent connection in the case of a non-threaded server), and should almost always be used in operation. Prior to version 2.2.2, this directive accepted only the values `0` and `1` instead of `Off` and `On`, respectively. DBDPrepareSQL Directive ----------------------- | | | | --- | --- | | Description: | Define an SQL prepared statement | | Syntax: | ``` DBDPrepareSQL "SQL statement" label ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_dbd | For modules such as authentication that repeatedly use a single SQL statement, optimum performance is achieved by preparing the statement at startup rather than every time it is used. This directive prepares an SQL statement and assigns it a label. DBDriver Directive ------------------ | | | | --- | --- | | Description: | Specify an SQL driver | | Syntax: | ``` DBDriver name ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_dbd | Selects an apr\_dbd driver by name. The driver must be installed on your system (on most systems, it will be a shared object or dll). For example, `DBDriver mysql` will select the MySQL driver in apr\_dbd\_mysql.so. apache_http_server Apache Module mod_substitute Apache Module mod\_substitute ============================= | | | | --- | --- | | Description: | Perform search and replace operations on response bodies | | Status: | Extension | | Module Identifier: | substitute\_module | | Source File: | mod\_substitute.c | | Compatibility: | Available in Apache HTTP Server 2.2.7 and later | ### Summary `<mod_substitute>` provides a mechanism to perform both regular expression and fixed string substitutions on response bodies. Substitute Directive -------------------- | | | | --- | --- | | Description: | Pattern to filter the response content | | Syntax: | ``` Substitute s/pattern/substitution/[infq] ``` | | Context: | directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_substitute | The `Substitute` directive specifies a search and replace pattern to apply to the response body. The meaning of the pattern can be modified by using any combination of these flags: `i` Perform a case-insensitive match. `n` By default the pattern is treated as a regular expression. Using the `n` flag forces the pattern to be treated as a fixed string. `f` The `f` flag causes `mod_substitute` to flatten the result of a substitution allowing for later substitutions to take place on the boundary of this one. This is the default. `q` The `q` flag causes `mod_substitute` to not flatten the buckets after each substitution. This can result in much faster response and a decrease in memory utilization, but should only be used if there is no possibility that the result of one substitution will ever match a pattern or regex of a subsequent one. The substitution may contain literal text and regular expression backreferences ### Example ``` <Location "/"> AddOutputFilterByType SUBSTITUTE text/html Substitute "s/foo/bar/ni" </Location> ``` The character which is used to separate (or "delimit") the various parts of the substitution string is referred to as the "delimiter", and it is most common to use a slash for this purpose. If either the pattern or the substitution contain a slash character then an alternative delimiter may be used to make the directive more readable: ### Example of using an alternate delimiter ``` <Location "/"> AddOutputFilterByType SUBSTITUTE text/html Substitute "s|<BR */?>|<br />|i" </Location> ``` Backreferences can be used in the comparison and in the substitution, when regular expressions are used, as illustrated in the following example: ### Example of using backreferences and captures ``` <Location "/"> AddOutputFilterByType SUBSTITUTE text/html # "foo=k,bar=k" -> "foo/bar=k" Substitute "s|foo=(\w+),bar=\1|foo/bar=$1|" </Location> ``` A common use scenario for `mod_substitute` is the situation in which a front-end server proxies requests to a back-end server which returns HTML with hard-coded embedded URLs that refer to the back-end server. These URLs don't work for the end-user, since the back-end server is unreachable. In this case, `mod_substitute` can be used to rewrite those URLs into something that will work from the front end: ### Rewriting URLs embedded in proxied content ``` ProxyPass "/blog/" "http://internal.blog.example.com/" ProxyPassReverse "/blog/" "http://internal.blog.example.com/" Substitute "s|http://internal.blog.example.com/|http://www.example.com/blog/|i" ``` `[ProxyPassReverse](mod_proxy#proxypassreverse)` modifies any `Location` (redirect) headers that are sent by the back-end server, and, in this example, `Substitute` takes care of the rest of the problem by fixing up the HTML response as well. SubstituteInheritBefore Directive --------------------------------- | | | | --- | --- | | Description: | Change the merge order of inherited patterns | | Syntax: | ``` SubstituteInheritBefore on|off ``` | | Default: | ``` SubstituteInheritBefore off ``` | | Context: | directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_substitute | | Compatibility: | Available in httpd 2.4.17 and later | Whether to apply the inherited `[Substitute](#substitute)` patterns first (`on`), or after the ones of the current context (`off`). `SubstituteInheritBefore` is itself inherited, hence contexts that inherit it (those that don't specify their own `SubstituteInheritBefore` value) will apply the closest defined merge order. SubstituteMaxLineLength Directive --------------------------------- | | | | --- | --- | | Description: | Set the maximum line size | | Syntax: | ``` SubstituteMaxLineLength bytes(b|B|k|K|m|M|g|G) ``` | | Default: | ``` SubstituteMaxLineLength 1m ``` | | Context: | directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_substitute | | Compatibility: | Available in httpd 2.4.11 and later | The maximum line size handled by `<mod_substitute>` is limited to restrict memory use. The limit can be configured using `SubstituteMaxLineLength`. The value can be given as the number of bytes and can be suffixed with a single letter `b`, `B`, `k`, `K`, `m`, `M`, `g`, `G` to provide the size in bytes, kilobytes, megabytes or gigabytes respectively. ### Example ``` <Location "/"> AddOutputFilterByType SUBSTITUTE text/html SubstituteMaxLineLength 10m Substitute "s/foo/bar/ni" </Location> ``` apache_http_server Apache Module mod_auth_form Apache Module mod\_auth\_form ============================= | | | | --- | --- | | Description: | Form authentication | | Status: | Base | | Module Identifier: | auth\_form\_module | | Source File: | mod\_auth\_form.c | | Compatibility: | Available in Apache 2.3 and later | ### Summary **Warning** Form authentication depends on the `<mod_session>` modules, and these modules make use of HTTP cookies, and as such can fall victim to Cross Site Scripting attacks, or expose potentially private information to clients. Please ensure that the relevant risks have been taken into account before enabling the session functionality on your server. This module allows the use of an HTML login form to restrict access by looking up users in the given providers. HTML forms require significantly more configuration than the alternatives, however an HTML login form can provide a much friendlier experience for end users. HTTP basic authentication is provided by `<mod_auth_basic>`, and HTTP digest authentication is provided by `<mod_auth_digest>`. This module should be combined with at least one authentication module such as `<mod_authn_file>` and one authorization module such as `<mod_authz_user>`. Once the user has been successfully authenticated, the user's login details will be stored in a session provided by `<mod_session>`. Basic Configuration ------------------- To protect a particular URL with `<mod_auth_form>`, you need to decide where you will store your session, and you will need to decide what method you will use to authenticate. In this simple example, the login details will be stored in a session based on `<mod_session_cookie>`, and authentication will be attempted against a file using `<mod_authn_file>`. If authentication is unsuccessful, the user will be redirected to the form login page. ### Basic example ``` <Location "/admin"> AuthFormProvider file AuthUserFile "conf/passwd" AuthType form AuthName "/admin" AuthFormLoginRequiredLocation "http://example.com/login.html" Session On SessionCookieName session path=/ Require valid-user </Location> ``` The directive `[AuthType](mod_authn_core#authtype)` will enable the `<mod_auth_form>` authentication when set to the value form. The directives `[AuthFormProvider](#authformprovider)` and `[AuthUserFile](mod_authn_file#authuserfile)` specify that usernames and passwords should be checked against the chosen file. The directives `[Session](mod_session#session)` and `[SessionCookieName](mod_session_cookie#sessioncookiename)` session stored within an HTTP cookie on the browser. For more information on the different options for configuring a session, read the documentation for `<mod_session>`. You can optionally add a `[SessionCryptoPassphrase](mod_session_crypto#sessioncryptopassphrase)` to create an encrypted session cookie. This required the additional module `<mod_session_crypto>` be loaded. In the simple example above, a URL has been protected by `<mod_auth_form>`, but the user has yet to be given an opportunity to enter their username and password. Options for doing so include providing a dedicated standalone login page for this purpose, or for providing the login page inline. Standalone Login ---------------- The login form can be hosted as a standalone page, or can be provided inline on the same page. When configuring the login as a standalone page, unsuccessful authentication attempts should be redirected to a login form created by the website for this purpose, using the `[AuthFormLoginRequiredLocation](#authformloginrequiredlocation)` directive. Typically this login page will contain an HTML form, asking the user to provide their usename and password. ### Example login form ``` <form method="POST" action="/dologin.html"> Username: <input type="text" name="httpd_username" value="" /> Password: <input type="password" name="httpd_password" value="" /> <input type="submit" name="login" value="Login" /> </form> ``` The part that does the actual login is handled by the form-login-handler. The action of the form should point at this handler, which is configured within Apache httpd as follows: ### Form login handler example ``` <Location "/dologin.html"> SetHandler form-login-handler AuthFormLoginRequiredLocation "http://example.com/login.html" AuthFormLoginSuccessLocation "http://example.com/admin/index.html" AuthFormProvider file AuthUserFile "conf/passwd" AuthType form AuthName /admin Session On SessionCookieName session path=/ </Location> ``` The URLs specified by the `[AuthFormLoginRequiredLocation](#authformloginrequiredlocation)` directive will typically point to a page explaining to the user that their login attempt was unsuccessful, and they should try again. The `[AuthFormLoginSuccessLocation](#authformloginsuccesslocation)` directive specifies the URL the user should be redirected to upon successful login. Alternatively, the URL to redirect the user to on success can be embedded within the login form, as in the example below. As a result, the same form-login-handler can be reused for different areas of a website. ### Example login form with location ``` <form method="POST" action="/dologin.html"> Username: <input type="text" name="httpd_username" value="" /> Password: <input type="password" name="httpd_password" value="" /> <input type="submit" name="login" value="Login" /> <input type="hidden" name="httpd_location" value="http://example.com/success.html" /> </form> ``` Inline Login ------------ **Warning** A risk exists that under certain circumstances, the login form configured using inline login may be submitted more than once, revealing login credentials to the application running underneath. The administrator must ensure that the underlying application is properly secured to prevent abuse. If in doubt, use the standalone login configuration. As an alternative to having a dedicated login page for a website, it is possible to configure `<mod_auth_form>` to authenticate users inline, without being redirected to another page. This allows the state of the current page to be preserved during the login attempt. This can be useful in a situation where a time limited session is in force, and the session times out in the middle of the user request. The user can be re-authenticated in place, and they can continue where they left off. If a non-authenticated user attempts to access a page protected by `<mod_auth_form>` that isn't configured with a `[AuthFormLoginRequiredLocation](#authformloginrequiredlocation)` directive, a HTTP\_UNAUTHORIZED status code is returned to the browser indicating to the user that they are not authorized to view the page. To configure inline authentication, the administrator overrides the error document returned by the HTTP\_UNAUTHORIZED status code with a custom error document containing the login form, as follows: ### Basic inline example ``` AuthFormProvider file ErrorDocument 401 "/login.shtml" AuthUserFile "conf/passwd" AuthType form AuthName realm AuthFormLoginRequiredLocation "http://example.com/login.html" Session On SessionCookieName session path=/ ``` The error document page should contain a login form with an empty action property, as per the example below. This has the effect of submitting the form to the original protected URL, without the page having to know what that URL is. ### Example inline login form ``` <form method="POST" **action=""**> Username: <input type="text" name="httpd_username" value="" /> Password: <input type="password" name="httpd_password" value="" /> <input type="submit" name="login" value="Login" /> </form> ``` When the end user has filled in their login details, the form will make an HTTP POST request to the original password protected URL. `<mod_auth_form>` will intercept this POST request, and if HTML fields are found present for the username and password, the user will be logged in, and the original password protected URL will be returned to the user as a GET request. Inline Login with Body Preservation ----------------------------------- A limitation of the inline login technique described above is that should an HTML form POST have resulted in the request to authenticate or reauthenticate, the contents of the original form posted by the browser will be lost. Depending on the function of the website, this could present significant inconvenience for the end user. `<mod_auth_form>` addresses this by allowing the method and body of the original request to be embedded in the login form. If authentication is successful, the original method and body will be retried by Apache httpd, preserving the state of the original request. To enable body preservation, add three additional fields to the login form as per the example below. ### Example with body preservation ``` <form method="POST" action=""> Username: <input type="text" name="httpd_username" value="" /> Password: <input type="password" name="httpd_password" value="" /> <input type="submit" name="login" value="Login" /> **<input type="hidden" name="httpd\_method" value="POST" /> <input type="hidden" name="httpd\_mimetype" value="application/x-www-form-urlencoded" /> <input type="hidden" name="httpd\_body" value="name1=value1&name2=value2" />** </form> ``` How the method, mimetype and body of the original request are embedded within the login form will depend on the platform and technology being used within the website. One option is to use the `<mod_include>` module along with the `[KeptBodySize](mod_request#keptbodysize)` directive, along with a suitable CGI script to embed the variables in the form. Another option is to render the login form using a CGI script or other dynamic technology. ### CGI example ``` AuthFormProvider file ErrorDocument 401 "/cgi-bin/login.cgi" ... ``` Logging Out ----------- To enable a user to log out of a particular session, configure a page to be handled by the form-logout-handler. Any attempt to access this URL will cause the username and password to be removed from the current session, effectively logging the user out. By setting the `[AuthFormLogoutLocation](#authformlogoutlocation)` directive, a URL can be specified that the browser will be redirected to on successful logout. This URL might explain to the user that they have been logged out, and give the user the option to log in again. ### Basic logout example ``` SetHandler form-logout-handler AuthName realm AuthFormLogoutLocation "http://example.com/loggedout.html" Session On SessionCookieName session path=/ ``` Note that logging a user out does not delete the session; it merely removes the username and password from the session. If this results in an empty session, the net effect will be the removal of that session, but this is not guaranteed. If you want to guarantee the removal of a session, set the `[SessionMaxAge](mod_session#sessionmaxage)` directive to a small value, like 1 (setting the directive to zero would mean no session age limit). ### Basic session expiry example ``` SetHandler form-logout-handler AuthFormLogoutLocation "http://example.com/loggedout.html" Session On SessionMaxAge 1 SessionCookieName session path=/ ``` Usernames and Passwords ----------------------- Note that form submission involves URLEncoding the form data: in this case the username and password. You should therefore pick usernames and passwords that avoid characters that are URLencoded in form submission, or you may get unexpected results. AuthFormAuthoritative Directive ------------------------------- | | | | --- | --- | | Description: | Sets whether authorization and authentication are passed to lower level modules | | Syntax: | ``` AuthFormAuthoritative On|Off ``` | | Default: | ``` AuthFormAuthoritative On ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_auth\_form | Normally, each authorization module listed in `[AuthFormProvider](#authformprovider)` will attempt to verify the user, and if the user is not found in any provider, access will be denied. Setting the `AuthFormAuthoritative` directive explicitly to `Off` allows for both authentication and authorization to be passed on to other non-provider-based modules if there is **no userID** or **rule** matching the supplied userID. This should only be necessary when combining `<mod_auth_form>` with third-party modules that are not configured with the `[AuthFormProvider](#authformprovider)` directive. When using such modules, the order of processing is determined in the modules' source code and is not configurable. AuthFormBody Directive ---------------------- | | | | --- | --- | | Description: | The name of a form field carrying the body of the request to attempt on successful login | | Syntax: | ``` AuthFormBody fieldname ``` | | Default: | ``` AuthFormBody httpd_body ``` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later | The `[AuthFormBody](#authformbody)` directive specifies the name of an HTML field which, if present, will contain the body of the request to submit should login be successful. By populating the form with fields described by `[AuthFormMethod](#authformmethod)`, `[AuthFormMimetype](#authformmimetype)` and `[AuthFormBody](#authformbody)`, a website can retry a request that may have been interrupted by the login screen, or by a session timeout. AuthFormDisableNoStore Directive -------------------------------- | | | | --- | --- | | Description: | Disable the CacheControl no-store header on the login page | | Syntax: | ``` AuthFormDisableNoStore On|Off ``` | | Default: | ``` AuthFormDisableNoStore Off ``` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later | The `[AuthFormDisableNoStore](#authformdisablenostore)` flag disables the sending of a `Cache-Control no-store` header with the error 401 page returned when the user is not yet logged in. The purpose of the header is to make it difficult for an `ecmascript` application to attempt to resubmit the login form, and reveal the username and password to the backend application. Disable at your own risk. AuthFormFakeBasicAuth Directive ------------------------------- | | | | --- | --- | | Description: | Fake a Basic Authentication header | | Syntax: | ``` AuthFormFakeBasicAuth On|Off ``` | | Default: | ``` AuthFormFakeBasicAuth Off ``` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later | The `[AuthFormFakeBasicAuth](#authformfakebasicauth)` flag determines whether a `Basic Authentication` header will be added to the request headers. This can be used to expose the username and password to an underlying application, without the underlying application having to be aware of how the login was achieved. AuthFormLocation Directive -------------------------- | | | | --- | --- | | Description: | The name of a form field carrying a URL to redirect to on successful login | | Syntax: | ``` AuthFormLocation fieldname ``` | | Default: | ``` AuthFormLocation httpd_location ``` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later | The `[AuthFormLocation](#authformlocation)` directive specifies the name of an HTML field which, if present, will contain a URL to redirect the browser to should login be successful. AuthFormLoginRequiredLocation Directive --------------------------------------- | | | | --- | --- | | Description: | The URL of the page to be redirected to should login be required | | Syntax: | ``` AuthFormLoginRequiredLocation url ``` | | Default: | `none` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later. The use of the expression parser has been added in 2.4.4. | The `[AuthFormLoginRequiredLocation](#authformloginrequiredlocation)` directive specifies the URL to redirect to should the user not be authorised to view a page. The value is parsed using the [ap\_expr](../expr) parser before being sent to the client. By default, if a user is not authorised to view a page, the HTTP response code `HTTP_UNAUTHORIZED` will be returned with the page specified by the `[ErrorDocument](core#errordocument)` directive. This directive overrides this default. Use this directive if you have a dedicated login page to redirect users to. AuthFormLoginSuccessLocation Directive -------------------------------------- | | | | --- | --- | | Description: | The URL of the page to be redirected to should login be successful | | Syntax: | ``` AuthFormLoginSuccessLocation url ``` | | Default: | `none` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later. The use of the expression parser has been added in 2.4.4. | The `[AuthFormLoginSuccessLocation](#authformloginsuccesslocation)` directive specifies the URL to redirect to should the user have logged in successfully. The value is parsed using the [ap\_expr](../expr) parser before being sent to the client. This directive can be overridden if a form field has been defined containing another URL using the `[AuthFormLocation](#authformlocation)` directive. Use this directive if you have a dedicated login URL, and you have not embedded the destination page in the login form. AuthFormLogoutLocation Directive -------------------------------- | | | | --- | --- | | Description: | The URL to redirect to after a user has logged out | | Syntax: | ``` AuthFormLogoutLocation uri ``` | | Default: | `none` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later. The use of the expression parser has been added in 2.4.4. | The `[AuthFormLogoutLocation](#authformlogoutlocation)` directive specifies the URL of a page on the server to redirect to should the user attempt to log out. The value is parsed using the [ap\_expr](../expr) parser before being sent to the client. When a URI is accessed that is served by the handler `form-logout-handler`, the page specified by this directive will be shown to the end user. For example: ### Example ``` <Location "/logout"> SetHandler form-logout-handler AuthFormLogoutLocation "http://example.com/loggedout.html" Session on #... </Location> ``` An attempt to access the URI /logout/ will result in the user being logged out, and the page /loggedout.html will be displayed. Make sure that the page loggedout.html is not password protected, otherwise the page will not be displayed. AuthFormMethod Directive ------------------------ | | | | --- | --- | | Description: | The name of a form field carrying the method of the request to attempt on successful login | | Syntax: | ``` AuthFormMethod fieldname ``` | | Default: | ``` AuthFormMethod httpd_method ``` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later | The `[AuthFormMethod](#authformmethod)` directive specifies the name of an HTML field which, if present, will contain the method of the request to submit should login be successful. By populating the form with fields described by `[AuthFormMethod](#authformmethod)`, `[AuthFormMimetype](#authformmimetype)` and `[AuthFormBody](#authformbody)`, a website can retry a request that may have been interrupted by the login screen, or by a session timeout. AuthFormMimetype Directive -------------------------- | | | | --- | --- | | Description: | The name of a form field carrying the mimetype of the body of the request to attempt on successful login | | Syntax: | ``` AuthFormMimetype fieldname ``` | | Default: | ``` AuthFormMimetype httpd_mimetype ``` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later | The `[AuthFormMimetype](#authformmimetype)` directive specifies the name of an HTML field which, if present, will contain the mimetype of the request to submit should login be successful. By populating the form with fields described by `[AuthFormMethod](#authformmethod)`, `[AuthFormMimetype](#authformmimetype)` and `[AuthFormBody](#authformbody)`, a website can retry a request that may have been interrupted by the login screen, or by a session timeout. AuthFormPassword Directive -------------------------- | | | | --- | --- | | Description: | The name of a form field carrying the login password | | Syntax: | ``` AuthFormPassword fieldname ``` | | Default: | ``` AuthFormPassword httpd_password ``` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later | The `[AuthFormPassword](#authformpassword)` directive specifies the name of an HTML field which, if present, will contain the password to be used to log in. AuthFormProvider Directive -------------------------- | | | | --- | --- | | Description: | Sets the authentication provider(s) for this location | | Syntax: | ``` AuthFormProvider provider-name [provider-name] ... ``` | | Default: | ``` AuthFormProvider file ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_auth\_form | The `AuthFormProvider` directive sets which provider is used to authenticate the users for this location. The default `file` provider is implemented by the `<mod_authn_file>` module. Make sure that the chosen provider module is present in the server. ### Example ``` <Location "/secure"> AuthType form AuthName "private area" AuthFormProvider dbm AuthDBMType SDBM AuthDBMUserFile "/www/etc/dbmpasswd" Require valid-user #... </Location> ``` Providers are implemented by `<mod_authn_dbm>`, `<mod_authn_file>`, `<mod_authn_dbd>`, `<mod_authnz_ldap>` and `<mod_authn_socache>`. AuthFormSitePassphrase Directive -------------------------------- | | | | --- | --- | | Description: | Bypass authentication checks for high traffic sites | | Syntax: | ``` AuthFormSitePassphrase secret ``` | | Default: | `none` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later | The `[AuthFormSitePassphrase](#authformsitepassphrase)` directive specifies a passphrase which, if present in the user session, causes Apache httpd to bypass authentication checks for the given URL. It can be used on high traffic websites to reduce the load induced on authentication infrastructure. The passphrase can be inserted into a user session by adding this directive to the configuration for the form-login-handler. The form-login-handler itself will always run the authentication checks, regardless of whether a passphrase is specified or not. **Warning** If the session is exposed to the user through the use of `<mod_session_cookie>`, and the session is not protected with `<mod_session_crypto>`, the passphrase is open to potential exposure through a dictionary attack. Regardless of how the session is configured, ensure that this directive is not used within URL spaces where private user data could be exposed, or sensitive transactions can be conducted. Use at own risk. AuthFormSize Directive ---------------------- | | | | --- | --- | | Description: | The largest size of the form in bytes that will be parsed for the login details | | Syntax: | ``` AuthFormSize size ``` | | Default: | ``` AuthFormSize 8192 ``` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later | The `[AuthFormSize](#authformsize)` directive specifies the maximum size of the body of the request that will be parsed to find the login form. If a login request arrives that exceeds this size, the whole request will be aborted with the HTTP response code `HTTP_REQUEST_TOO_LARGE`. If you have populated the form with fields described by `[AuthFormMethod](#authformmethod)`, `[AuthFormMimetype](#authformmimetype)` and `[AuthFormBody](#authformbody)`, you probably want to set this field to a similar size as the `[KeptBodySize](mod_request#keptbodysize)` directive. AuthFormUsername Directive -------------------------- | | | | --- | --- | | Description: | The name of a form field carrying the login username | | Syntax: | ``` AuthFormUsername fieldname ``` | | Default: | ``` AuthFormUsername httpd_username ``` | | Context: | directory | | Status: | Base | | Module: | mod\_auth\_form | | Compatibility: | Available in Apache HTTP Server 2.3.0 and later | The `[AuthFormUsername](#authformusername)` directive specifies the name of an HTML field which, if present, will contain the username to be used to log in.
programming_docs
apache_http_server Apache Module mod_info Apache Module mod\_info ======================= | | | | --- | --- | | Description: | Provides a comprehensive overview of the server configuration | | Status: | Extension | | Module Identifier: | info\_module | | Source File: | mod\_info.c | ### Summary To configure `<mod_info>`, add the following to your `httpd.conf` file. ``` <Location "/server-info"> SetHandler server-info </Location> ``` You may wish to use `<mod_authz_host>` inside the `[<Location>](core#location)` directive to limit access to your server configuration information: ``` <Location "/server-info"> SetHandler server-info Require host example.com </Location> ``` Once configured, the server information is obtained by accessing `http://your.host.example.com/server-info` Security Issues --------------- Once `<mod_info>` is loaded into the server, its handler capability is available in *all* configuration files, including per-directory files (*e.g.*, `.htaccess`). This may have security-related ramifications for your site. In particular, this module can leak sensitive information from the configuration directives of other Apache modules such as system paths, usernames/passwords, database names, etc. Therefore, this module should **only** be used in a controlled environment and always with caution. You will probably want to use `<mod_authz_host>` to limit access to your server configuration information. ### Access control ``` <Location "/server-info"> SetHandler server-info # Allow access from server itself Require ip 127.0.0.1 # Additionally, allow access from local workstation Require ip 192.168.1.17 </Location> ``` Selecting the information shown ------------------------------- By default, the server information includes a list of all enabled modules, and for each module, a description of the directives understood by that module, the hooks implemented by that module, and the relevant directives from the current configuration. Other views of the configuration information are available by appending a query to the `server-info` request. For example, `http://your.host.example.com/server-info?config` will show all configuration directives. `?<module-name>` Only information relevant to the named module `?config` Just the configuration directives, not sorted by module `?hooks` Only the list of Hooks each module is attached to `?list` Only a simple list of enabled modules `?server` Only the basic server information `?providers` List the providers that are available on your server Dumping the configuration on startup ------------------------------------ If the config define `-DDUMP_CONFIG` is set, `<mod_info>` will dump the pre-parsed configuration to `stdout` during server startup. ``` httpd -DDUMP_CONFIG -k start ``` Pre-parsed means that directives like `[<IfDefine>](core#ifdefine)` and `[<IfModule>](core#ifmodule)` are evaluated and environment variables are replaced. However it does not represent the final state of the configuration. In particular, it does not represent the merging or overriding that may happen for repeated directives. This is roughly equivalent to the `?config` query. Known Limitations ----------------- `<mod_info>` provides its information by reading the parsed configuration, rather than reading the original configuration file. There are a few limitations as a result of the way the parsed configuration tree is created: * Directives which are executed immediately rather than being stored in the parsed configuration are not listed. These include `[ServerRoot](core#serverroot)`, `[LoadModule](mod_so#loadmodule)`, and `[LoadFile](mod_so#loadfile)`. * Directives which control the configuration file itself, such as `[Include](core#include)`, `[<IfModule>](core#ifmodule)` and `[<IfDefine>](core#ifdefine)` are not listed, but the included configuration directives are. * Comments are not listed. (This may be considered a feature.) * Configuration directives from `.htaccess` files are not listed (since they do not form part of the permanent server configuration). * Container directives such as `[<Directory>](core#directory)` are listed normally, but `<mod_info>` cannot figure out the line number for the closing `[</Directory>](core#directory)`. * Directives generated by third party modules such as [mod\_perl](http://perl.apache.org) might not be listed. AddModuleInfo Directive ----------------------- | | | | --- | --- | | Description: | Adds additional information to the module information displayed by the server-info handler | | Syntax: | ``` AddModuleInfo module-name string ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_info | This allows the content of string to be shown as HTML interpreted, **Additional Information** for the module module-name. Example: ``` AddModuleInfo mod_deflate.c 'See <a \ href="http://httpd.apache.org/docs/2.4/mod/mod_deflate.html">\ http://httpd.apache.org/docs/2.4/mod/mod_deflate.html</a>' ``` apache_http_server Apache Module mod_env Apache Module mod\_env ====================== | | | | --- | --- | | Description: | Modifies the environment which is passed to CGI scripts and SSI pages | | Status: | Base | | Module Identifier: | env\_module | | Source File: | mod\_env.c | ### Summary This module allows for control of internal environment variables that are used by various Apache HTTP Server modules. These variables are also provided to CGI scripts as native system environment variables, and available for use in SSI pages. Environment variables may be passed from the shell which invoked the `[httpd](../programs/httpd)` process. Alternatively, environment variables may be set or unset within the configuration process. PassEnv Directive ----------------- | | | | --- | --- | | Description: | Passes environment variables from the shell | | Syntax: | ``` PassEnv env-variable [env-variable] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_env | Specifies one or more native system environment variables to make available as internal environment variables, which are available to Apache HTTP Server modules as well as propagated to CGI scripts and SSI pages. Values come from the native OS environment of the shell which invoked the `[httpd](../programs/httpd)` process. ### Example ``` PassEnv LD_LIBRARY_PATH ``` SetEnv Directive ---------------- | | | | --- | --- | | Description: | Sets environment variables | | Syntax: | ``` SetEnv env-variable [value] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_env | Sets an internal environment variable, which is then available to Apache HTTP Server modules, and passed on to CGI scripts and SSI pages. ### Example ``` SetEnv SPECIAL_PATH /foo/bin ``` If you omit the value argument, the variable is set to an empty string. The internal environment variables set by this directive are set *after* most early request processing directives are run, such as access control and URI-to-filename mapping. If the environment variable you're setting is meant as input into this early phase of processing such as the `[RewriteRule](mod_rewrite#rewriterule)` directive, you should instead set the environment variable with `[SetEnvIf](mod_setenvif#setenvif)`. ### See also * [Environment Variables](../env) UnsetEnv Directive ------------------ | | | | --- | --- | | Description: | Removes variables from the environment | | Syntax: | ``` UnsetEnv env-variable [env-variable] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_env | Removes one or more internal environment variables from those passed on to CGI scripts and SSI pages. ### Example ``` UnsetEnv LD_LIBRARY_PATH ``` apache_http_server Apache Module mod_authz_groupfile Apache Module mod\_authz\_groupfile =================================== | | | | --- | --- | | Description: | Group authorization using plaintext files | | Status: | Base | | Module Identifier: | authz\_groupfile\_module | | Source File: | mod\_authz\_groupfile.c | | Compatibility: | Available in Apache 2.1 and later | ### Summary This module provides authorization capabilities so that authenticated users can be allowed or denied access to portions of the web site by group membership. Similar functionality is provided by `<mod_authz_dbm>`. The Require Directives ---------------------- Apache's `[Require](mod_authz_core#require)` directives are used during the authorization phase to ensure that a user is allowed to access a resource. mod\_authz\_groupfile extends the authorization types with `group` and `group-file`. Since v2.4.8, [expressions](../expr) are supported within the groupfile require directives. ### Require group This directive specifies group membership that is required for the user to gain access. ``` Require group admin ``` ### Require file-group When this directive is specified, the filesystem permissions on the file being accessed are consulted. The user must be a member of a group with the same name as the group that owns the file. See `<mod_authz_owner>` for more details. ``` Require file-group ``` AuthGroupFile Directive ----------------------- | | | | --- | --- | | Description: | Sets the name of a text file containing the list of user groups for authorization | | Syntax: | ``` AuthGroupFile file-path ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_authz\_groupfile | The `AuthGroupFile` directive sets the name of a textual file containing the list of user groups for user authorization. File-path is the path to the group file. If it is not absolute, it is treated as relative to the `[ServerRoot](core#serverroot)`. Each line of the group file contains a groupname followed by a colon, followed by the member usernames separated by spaces. ### Example: ``` mygroup: bob joe anne ``` Note that searching large text files is *very* inefficient; `[AuthDBMGroupFile](mod_authz_dbm#authdbmgroupfile)` provides a much better performance. **Security** Make sure that the `AuthGroupFile` is stored outside the document tree of the web-server; do *not* put it in the directory that it protects. Otherwise, clients may be able to download the `AuthGroupFile`. apache_http_server Apache Module mod_dav_lock Apache Module mod\_dav\_lock ============================ | | | | --- | --- | | Description: | Generic locking module for `<mod_dav>` | | Status: | Extension | | Module Identifier: | dav\_lock\_module | | Source File: | mod\_dav\_lock.c | | Compatibility: | Available in version 2.1 and later | ### Summary This module implements a generic locking API which can be used by any backend provider of `<mod_dav>`. It *requires* at least the service of `<mod_dav>`. But without a backend provider which makes use of it, it's useless and should not be loaded into the server. A sample backend module which actually utilizes `<mod_dav_lock>` is [mod\_dav\_svn](http://subversion.apache.org/), the subversion provider module. Note that `<mod_dav_fs>` does *not* need this generic locking module, because it uses its own more specialized version. In order to make `<mod_dav_lock>` functional, you just have to specify the location of the lock database using the `[DavGenericLockDB](#davgenericlockdb)` directive described below. **Developer's Note** In order to retrieve the pointer to the locking provider function, you have to use the `ap_lookup_provider` API with the arguments `dav-lock`, `generic`, and `0`. DavGenericLockDB Directive -------------------------- | | | | --- | --- | | Description: | Location of the DAV lock database | | Syntax: | ``` DavGenericLockDB file-path ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_dav\_lock | Use the `DavGenericLockDB` directive to specify the full path to the lock database, excluding an extension. If the path is not absolute, it will be interpreted relative to `[ServerRoot](core#serverroot)`. The implementation of `<mod_dav_lock>` uses a SDBM database to track user locks. ### Example ``` DavGenericLockDB var/DavLock ``` The directory containing the lock database file must be writable by the `[User](mod_unixd#user)` and `[Group](mod_unixd#group)` under which Apache is running. For security reasons, you should create a directory for this purpose rather than changing the permissions on an existing directory. In the above example, Apache will create files in the `var/` directory under the `[ServerRoot](core#serverroot)` with the base filename `DavLock` and an extension added by the server. apache_http_server Apache Module mod_socache_dbm Apache Module mod\_socache\_dbm =============================== | | | | --- | --- | | Description: | DBM based shared object cache provider. | | Status: | Extension | | Module Identifier: | socache\_dbm\_module | | Source File: | mod\_socache\_dbm.c | ### Summary `mod_socache_dbm` is a shared object cache provider which provides for creation and access to a cache backed by a DBM database. `dbm:/path/to/datafile` Details of other shared object cache providers can be found [here](../socache). apache_http_server Apache Module mod_log_config Apache Module mod\_log\_config ============================== | | | | --- | --- | | Description: | Logging of the requests made to the server | | Status: | Base | | Module Identifier: | log\_config\_module | | Source File: | mod\_log\_config.c | ### Summary This module provides for flexible logging of client requests. Logs are written in a customizable format, and may be written directly to a file, or to an external program. Conditional logging is provided so that individual requests may be included or excluded from the logs based on characteristics of the request. Three directives are provided by this module: `[TransferLog](#transferlog)` to create a log file, `[LogFormat](#logformat)` to set a custom format, and `[CustomLog](#customlog)` to define a log file and format in one step. The `TransferLog` and `CustomLog` directives can be used multiple times in each server to cause each request to be logged to multiple files. Custom Log Formats ------------------ The format argument to the `[LogFormat](#logformat)` and `[CustomLog](#customlog)` directives is a string. This string is used to log each request to the log file. It can contain literal characters copied into the log files and the C-style control characters "\n" and "\t" to represent new-lines and tabs. Literal quotes and backslashes should be escaped with backslashes. The characteristics of the request itself are logged by placing "`%`" directives in the format string, which are replaced in the log file by the values as follows: | Format String | Description | | --- | --- | | `%%` | The percent sign. | | `%a` | Client IP address of the request (see the `<mod_remoteip>` module). | | `%{c}a` | Underlying peer IP address of the connection (see the `<mod_remoteip>` module). | | `%A` | Local IP-address. | | `%B` | Size of response in bytes, excluding HTTP headers. | | `%b` | Size of response in bytes, excluding HTTP headers. In CLF format, *i.e.* a '`-`' rather than a 0 when no bytes are sent. | | `%{VARNAME}C` | The contents of cookie VARNAME in the request sent to the server. Only version 0 cookies are fully supported. | | `%D` | The time taken to serve the request, in microseconds. | | `%{VARNAME}e` | The contents of the environment variable VARNAME. | | `%f` | Filename. | | `%h` | Remote hostname. Will log the IP address if `[HostnameLookups](core#hostnamelookups)` is set to `Off`, which is the default. If it logs the hostname for only a few hosts, you probably have access control directives mentioning them by name. See [the Require host documentation](mod_authz_host#reqhost). | | `%{c}h` | Like `%h`, but always reports on the hostname of the underlying TCP connection and not any modifications to the remote hostname by modules like `<mod_remoteip>`. | | `%H` | The request protocol. | | `%{VARNAME}i` | The contents of `VARNAME:` header line(s) in the request sent to the server. Changes made by other modules (e.g. `<mod_headers>`) affect this. If you're interested in what the request header was prior to when most modules would have modified it, use `<mod_setenvif>` to copy the header into an internal environment variable and log that value with the `%{VARNAME}e` described above. | | `%k` | Number of keepalive requests handled on this connection. Interesting if `[KeepAlive](core#keepalive)` is being used, so that, for example, a '1' means the first keepalive request after the initial one, '2' the second, etc...; otherwise this is always 0 (indicating the initial request). | | `%l` | Remote logname (from identd, if supplied). This will return a dash unless `<mod_ident>` is present and `[IdentityCheck](mod_ident#identitycheck)` is set `On`. | | `%L` | The request log ID from the error log (or '-' if nothing has been logged to the error log for this request). Look for the matching error log line to see what request caused what error. | | `%m` | The request method. | | `%{VARNAME}n` | The contents of note VARNAME from another module. | | `%{VARNAME}o` | The contents of `VARNAME:` header line(s) in the reply. | | `%p` | The canonical port of the server serving the request. | | `%{format}p` | The canonical port of the server serving the request, or the server's actual port, or the client's actual port. Valid formats are `canonical`, `local`, or `remote`. | | `%P` | The process ID of the child that serviced the request. | | `%{format}P` | The process ID or thread ID of the child that serviced the request. Valid formats are `pid`, `tid`, and `hextid`. `hextid` requires APR 1.2.0 or higher. | | `%q` | The query string (prepended with a `?` if a query string exists, otherwise an empty string). | | `%r` | First line of request. | | `%R` | The handler generating the response (if any). | | `%s` | Status. For requests that have been internally redirected, this is the status of the *original* request. Use `%>s` for the final status. | | `%t` | Time the request was received, in the format `[18/Sep/2011:19:18:28 -0400]`. The last number indicates the timezone offset from GMT | | `%{format}t` | The time, in the form given by format, which should be in an extended `strftime(3)` format (potentially localized). If the format starts with `begin:` (default) the time is taken at the beginning of the request processing. If it starts with `end:` it is the time when the log entry gets written, close to the end of the request processing. In addition to the formats supported by `strftime(3)`, the following format tokens are supported: | | | | --- | --- | | `sec` | number of seconds since the Epoch | | `msec` | number of milliseconds since the Epoch | | `usec` | number of microseconds since the Epoch | | `msec_frac` | millisecond fraction | | `usec_frac` | microsecond fraction | These tokens can not be combined with each other or `strftime(3)` formatting in the same format string. You can use multiple `%{format}t` tokens instead. | | `%T` | The time taken to serve the request, in seconds. | | `%{UNIT}T` | The time taken to serve the request, in a time unit given by `UNIT`. Valid units are `ms` for milliseconds, `us` for microseconds, and `s` for seconds. Using `s` gives the same result as `%T` without any format; using `us` gives the same result as `%D`. Combining `%T` with a unit is available in 2.4.13 and later. | | `%u` | Remote user if the request was authenticated. May be bogus if return status (`%s`) is 401 (unauthorized). | | `%U` | The URL path requested, not including any query string. | | `%v` | The canonical `[ServerName](core#servername)` of the server serving the request. | | `%V` | The server name according to the `[UseCanonicalName](core#usecanonicalname)` setting. | | `%X` | Connection status when response is completed: | | | | --- | --- | | `X` = | Connection aborted before the response completed. | | `+` = | Connection may be kept alive after the response is sent. | | `-` = | Connection will be closed after the response is sent. | | | `%I` | Bytes received, including request and headers. Cannot be zero. You need to enable `<mod_logio>` to use this. | | `%O` | Bytes sent, including headers. May be zero in rare cases such as when a request is aborted before a response is sent. You need to enable `<mod_logio>` to use this. | | `%S` | Bytes transferred (received and sent), including request and headers, cannot be zero. This is the combination of %I and %O. You need to enable `<mod_logio>` to use this. | | `%{VARNAME}^ti` | The contents of `VARNAME:` trailer line(s) in the request sent to the server. | | `%{VARNAME}^to` | The contents of `VARNAME:` trailer line(s) in the response sent from the server. | ### Modifiers Particular items can be restricted to print only for responses with specific HTTP status codes by placing a comma-separated list of status codes immediately following the "%". The status code list may be preceded by a "`!`" to indicate negation. | Format String | Meaning | | --- | --- | | `%400,501{User-agent}i` | Logs `User-agent` on 400 errors and 501 errors only. For other status codes, the literal string `"-"` will be logged. | | `%!200,304,302{Referer}i` | Logs `Referer` on all requests that do *not* return one of the three specified codes, "`-`" otherwise. | The modifiers "<" and ">" can be used for requests that have been internally redirected to choose whether the original or final (respectively) request should be consulted. By default, the `%` directives `%s, %U, %T, %D,` and `%r` look at the original request while all others look at the final request. So for example, `%>s` can be used to record the final status of the request and `%<u` can be used to record the original authenticated user on a request that is internally redirected to an unauthenticated resource. ### Format Notes For security reasons, starting with version 2.0.46, non-printable and other special characters in `%r`, `%i` and `%o` are escaped using `\xhh` sequences, where hh stands for the hexadecimal representation of the raw byte. Exceptions from this rule are `"` and `\`, which are escaped by prepending a backslash, and all whitespace characters, which are written in their C-style notation (`\n`, `\t`, etc). In versions prior to 2.0.46, no escaping was performed on these strings so you had to be quite careful when dealing with raw log files. Since httpd 2.0, unlike 1.3, the `%b` and `%B` format strings do not represent the number of bytes sent to the client, but simply the size in bytes of the HTTP response (which will differ, for instance, if the connection is aborted, or if SSL is used). The `%O` format provided by `<mod_logio>` will log the actual number of bytes sent over the network. Note: `<mod_cache>` is implemented as a quick-handler and not as a standard handler. Therefore, the `%R` format string will not return any handler information when content caching is involved. ### Examples Some commonly used log format strings are: Common Log Format (CLF) `"%h %l %u %t \"%r\" %>s %b"` Common Log Format with Virtual Host `"%v %h %l %u %t \"%r\" %>s %b"` NCSA extended/combined log format `"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""` Referer log format `"%{Referer}i -> %U"` Agent (Browser) log format `"%{User-agent}i"` You can use the `%{format}t` directive multiple times to build up a time format using the extended format tokens like `msec_frac`: Timestamp including milliseconds `"%{%d/%b/%Y %T}t.%{msec_frac}t %{%z}t"` Security Considerations ----------------------- See the [security tips](../misc/security_tips#serverroot) document for details on why your security could be compromised if the directory where logfiles are stored is writable by anyone other than the user that starts the server. BufferedLogs Directive ---------------------- | | | | --- | --- | | Description: | Buffer log entries in memory before writing to disk | | Syntax: | ``` BufferedLogs On|Off ``` | | Default: | ``` BufferedLogs Off ``` | | Context: | server config | | Status: | Base | | Module: | mod\_log\_config | The `BufferedLogs` directive causes `<mod_log_config>` to store several log entries in memory and write them together to disk, rather than writing them after each request. On some systems, this may result in more efficient disk access and hence higher performance. It may be set only once for the entire server; it cannot be configured per virtual-host. This directive should be used with caution as a crash might cause loss of logging data. CustomLog Directive ------------------- | | | | --- | --- | | Description: | Sets filename and format of log file | | Syntax: | ``` CustomLog file|pipe format|nickname [env=[!]environment-variable| expr=expression] ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_log\_config | The `CustomLog` directive is used to log requests to the server. A log format is specified, and the logging can optionally be made conditional on request characteristics using environment variables. The first argument, which specifies the location to which the logs will be written, can take one of the following two types of values: file A filename, relative to the `[ServerRoot](core#serverroot)`. pipe The pipe character "`|`", followed by the path to a program to receive the log information on its standard input. See the notes on [piped logs](../logs#piped) for more information. **Security:** If a program is used, then it will be run as the user who started `[httpd](../programs/httpd)`. This will be root if the server was started by root; be sure that the program is secure. **Note** When entering a file path on non-Unix platforms, care should be taken to make sure that only forward slashed are used even though the platform may allow the use of back slashes. In general it is a good idea to always use forward slashes throughout the configuration files. The second argument specifies what will be written to the log file. It can specify either a nickname defined by a previous `[LogFormat](#logformat)` directive, or it can be an explicit format string as described in the [log formats](#formats) section. For example, the following two sets of directives have exactly the same effect: ``` # CustomLog with format nickname LogFormat "%h %l %u %t \"%r\" %>s %b" common CustomLog "logs/access_log" common # CustomLog with explicit format string CustomLog "logs/access_log" "%h %l %u %t \"%r\" %>s %b" ``` The third argument is optional and controls whether or not to log a particular request. The condition can be the presence or absence (in the case of a '`env=!name`' clause) of a particular variable in the server [environment](../env). Alternatively, the condition can be expressed as arbitrary boolean [expression](../expr). If the condition is not satisfied, the request will not be logged. References to HTTP headers in the expression will not cause the header names to be added to the Vary header. Environment variables can be set on a per-request basis using the `<mod_setenvif>` and/or `<mod_rewrite>` modules. For example, if you want to record requests for all GIF images on your server in a separate logfile but not in your main log, you can use: ``` SetEnvIf Request_URI \.gif$ gif-image CustomLog "gif-requests.log" common env=gif-image CustomLog "nongif-requests.log" common env=!gif-image ``` Or, to reproduce the behavior of the old RefererIgnore directive, you might use the following: ``` SetEnvIf Referer example\.com localreferer CustomLog "referer.log" referer env=!localreferer ``` GlobalLog Directive ------------------- | | | | --- | --- | | Description: | Sets filename and format of log file | | Syntax: | ``` GlobalLogfile|pipe format|nickname [env=[!]environment-variable| expr=expression] ``` | | Context: | server config | | Status: | Base | | Module: | mod\_log\_config | | Compatibility: | Available in Apache HTTP Server 2.4.19 and later | The `GlobalLog` directive defines a log shared by the main server configuration and all defined virtual hosts. The `GlobalLog` directive is identical to the `CustomLog` directive, apart from the following differences: * `GlobalLog` is not valid in virtual host context. * `GlobalLog` is used by virtual hosts that define their own `CustomLog`, unlike a globally specified `CustomLog`. LogFormat Directive ------------------- | | | | --- | --- | | Description: | Describes a format for use in a log file | | Syntax: | ``` LogFormat format|nickname [nickname] ``` | | Default: | ``` LogFormat "%h %l %u %t \"%r\" %>s %b" ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_log\_config | This directive specifies the format of the access log file. The `LogFormat` directive can take one of two forms. In the first form, where only one argument is specified, this directive sets the log format which will be used by logs specified in subsequent `TransferLog` directives. The single argument can specify an explicit format as discussed in the [custom log formats](#formats) section above. Alternatively, it can use a nickname to refer to a log format defined in a previous `LogFormat` directive as described below. The second form of the `LogFormat` directive associates an explicit format with a nickname. This nickname can then be used in subsequent `LogFormat` or `[CustomLog](#customlog)` directives rather than repeating the entire format string. A `LogFormat` directive that defines a nickname **does nothing else** -- that is, it *only* defines the nickname, it doesn't actually apply the format and make it the default. Therefore, it will not affect subsequent `[TransferLog](#transferlog)` directives. In addition, `LogFormat` cannot use one nickname to define another nickname. Note that the nickname should not contain percent signs (`%`). ### Example ``` LogFormat "%v %h %l %u %t \"%r\" %>s %b" vhost_common ``` TransferLog Directive --------------------- | | | | --- | --- | | Description: | Specify location of a log file | | Syntax: | ``` TransferLog file|pipe ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_log\_config | This directive has exactly the same arguments and effect as the `[CustomLog](#customlog)` directive, with the exception that it does not allow the log format to be specified explicitly or for conditional logging of requests. Instead, the log format is determined by the most recently specified `[LogFormat](#logformat)` directive which does not define a nickname. Common Log Format is used if no other format has been specified. ### Example ``` LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" TransferLog logs/access_log ```
programming_docs
apache_http_server Apache Module mod_brotli Apache Module mod\_brotli ========================= | | | | --- | --- | | Description: | Compress content via Brotli before it is delivered to the client | | Status: | Extension | | Module Identifier: | brotli\_module | | Source File: | mod\_brotli.c | | Compatibility: | Available in version 2.4.26 and later. | ### Summary The `<mod_brotli>` module provides the `BROTLI_COMPRESS` output filter that allows output from your server to be compressed using the brotli compression format before being sent to the client over the network. This module uses the Brotli library found at <https://github.com/google/brotli>. Sample Configurations --------------------- **Compression and TLS** Some web applications are vulnerable to an information disclosure attack when a TLS connection carries compressed data. For more information, review the details of the "BREACH" family of attacks. This is a simple configuration that compresses common text-based content types. ### Compress only a few types ``` AddOutputFilterByType BROTLI_COMPRESS text/html text/plain text/xml text/css text/javascript application/javascript ``` Enabling Compression -------------------- **Compression and TLS** Some web applications are vulnerable to an information disclosure attack when a TLS connection carries compressed data. For more information, review the details of the "BREACH" family of attacks. ### Output Compression Compression is implemented by the `BROTLI_COMPRESS` [filter](../filter). The following directive will enable compression for documents in the container where it is placed: ``` SetOutputFilter BROTLI_COMPRESS SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-brotli ``` If you want to restrict the compression to particular MIME types in general, you may use the `[AddOutputFilterByType](mod_filter#addoutputfilterbytype)` directive. Here is an example of enabling compression only for the html files of the Apache documentation: ``` <Directory "/your-server-root/manual"> AddOutputFilterByType BROTLI_COMPRESS text/html </Directory> ``` **Note** The `BROTLI_COMPRESS` filter is always inserted after RESOURCE filters like PHP or SSI. It never touches internal subrequests. **Note** There is an environment variable `no-brotli`, set via `[SetEnv](mod_env#setenv)`, which will disable brotli compression for a particular request, even if it is supported by the client. Dealing with proxy servers -------------------------- The `<mod_brotli>` module sends a `Vary: Accept-Encoding` HTTP response header to alert proxies that a cached response should be sent only to clients that send the appropriate `Accept-Encoding` request header. This prevents compressed content from being sent to a client that will not understand it. If you use some special exclusions dependent on, for example, the `User-Agent` header, you must manually configure an addition to the `Vary` header to alert proxies of the additional restrictions. For example, in a typical configuration where the addition of the `BROTLI_COMPRESS` filter depends on the `User-Agent`, you should add: ``` Header append Vary User-Agent ``` If your decision about compression depends on other information than request headers (*e.g.* HTTP version), you have to set the `Vary` header to the value `*`. This prevents compliant proxies from caching entirely. ### Example ``` Header set Vary * ``` Serving pre-compressed content ------------------------------ Since `<mod_brotli>` re-compresses content each time a request is made, some performance benefit can be derived by pre-compressing the content and telling mod\_brotli to serve them without re-compressing them. This may be accomplished using a configuration like the following: ``` <IfModule mod_headers.c> # Serve brotli compressed CSS files if they exist # and the client accepts brotli. RewriteCond "%{HTTP:Accept-encoding}" "br" RewriteCond "%{REQUEST_FILENAME}\.br" "-s" RewriteRule "^(.*)\.css" "$1\.css\.br" [QSA] # Serve brotli compressed JS files if they exist # and the client accepts brotli. RewriteCond "%{HTTP:Accept-encoding}" "br" RewriteCond "%{REQUEST_FILENAME}\.br" "-s" RewriteRule "^(.*)\.js" "$1\.js\.br" [QSA] # Serve correct content types, and prevent double compression. RewriteRule "\.css\.br$" "-" [T=text/css,E=no-brotli:1] RewriteRule "\.js\.br$" "-" [T=text/javascript,E=no-brotli:1] <FilesMatch "(\.js\.br|\.css\.br)$"> # Serve correct encoding type. Header append Content-Encoding br # Force proxies to cache brotli & # non-brotli css/js files separately. Header append Vary Accept-Encoding </FilesMatch> </IfModule> ``` BrotliAlterETag Directive ------------------------- | | | | --- | --- | | Description: | How the outgoing ETag header should be modified during compression | | Syntax: | ``` BrotliAlterETag AddSuffix|NoChange|Remove ``` | | Default: | ``` BrotliAlterETag AddSuffix ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_brotli | The `BrotliAlterETag` directive specifies how the ETag hader should be altered when a response is compressed. AddSuffix Append the compression method onto the end of the ETag, causing compressed and uncompressed representations to have unique ETags. In another dynamic compression module, mod\_deflate, this has been the default since 2.4.0. This setting prevents serving "HTTP Not Modified" (304) responses to conditional requests for compressed content. NoChange Don't change the ETag on a compressed response. In another dynamic compression module, mod\_deflate, this has been the default prior to 2.4.0. This setting does not satisfy the HTTP/1.1 property that all representations of the same resource have unique ETags. Remove Remove the ETag header from compressed responses. This prevents some conditional requests from being possible, but avoids the shortcomings of the preceding options. BrotliCompressionMaxInputBlock Directive ---------------------------------------- | | | | --- | --- | | Description: | Maximum input block size | | Syntax: | ``` BrotliCompressionMaxInputBlock value ``` | | Default: | `(automatic)` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_brotli | The `BrotliCompressionMaxInputBlock` directive specifies the maximum input block size between 16 and 24, with the caveat that larger block sizes require more memory. BrotliCompressionQuality Directive ---------------------------------- | | | | --- | --- | | Description: | Compression quality | | Syntax: | ``` BrotliCompressionQuality value ``` | | Default: | ``` BrotliCompressionQuality 5 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_brotli | The `BrotliCompressionQuality` directive specifies the compression quality (a value between 0 and 11). Higher quality values result in better, but also slower compression. BrotliCompressionWindow Directive --------------------------------- | | | | --- | --- | | Description: | Brotli sliding compression window size | | Syntax: | ``` BrotliCompressionWindow value ``` | | Default: | ``` BrotliCompressionWindow 18 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_brotli | The `BrotliCompressionWindow` directive specifies the brotli sliding compression window size (a value between 10 and 24). Larger window sizes can improve compression quality, but require more memory. BrotliFilterNote Directive -------------------------- | | | | --- | --- | | Description: | Places the compression ratio in a note for logging | | Syntax: | ``` BrotliFilterNote [type] notename ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_brotli | The `BrotliFilterNote` directive specifies that a note about compression ratios should be attached to the request. The name of the note is the value specified for the directive. You can use that note for statistical purposes by adding the value to your [access log](../logs#accesslog). ### Example ``` BrotliFilterNote ratio LogFormat '"%r" %b (%{ratio}n) "%{User-agent}i"' brotli CustomLog "logs/brotli_log" brotli ``` If you want to extract more accurate values from your logs, you can use the type argument to specify the type of data left as a note for logging. type can be one of: `Input` Store the byte count of the filter's input stream in the note. `Output` Store the byte count of the filter's output stream in the note. `Ratio` Store the compression ratio (`output/input * 100`) in the note. This is the default, if the type argument is omitted. Thus you may log it this way: ### Accurate Logging ``` BrotliFilterNote Input instream BrotliFilterNote Output outstream BrotliFilterNote Ratio ratio LogFormat '"%r" %{outstream}n/%{instream}n (%{ratio}n%%)' brotli CustomLog "logs/brotli_log" brotli ``` ### See also * `<mod_log_config>` apache_http_server Apache Module mod_lua Apache Module mod\_lua ====================== | | | | --- | --- | | Description: | Provides Lua hooks into various portions of the httpd request processing | | Status: | Extension | | Module Identifier: | lua\_module | | Source File: | mod\_lua.c | | Compatibility: | 2.3 and later | ### Summary This module allows the server to be extended with scripts written in the Lua programming language. The extension points (hooks) available with `<mod_lua>` include many of the hooks available to natively compiled Apache HTTP Server modules, such as mapping requests to files, generating dynamic responses, access control, authentication, and authorization More information on the Lua programming language can be found at the [the Lua website](http://www.lua.org/). **Warning** This module holds a great deal of power over httpd, which is both a strength and a potential security risk. It is **not** recommended that you use this module on a server that is shared with users you do not trust, as it can be abused to change the internal workings of httpd. Basic Configuration ------------------- The basic module loading directive is ``` LoadModule lua_module modules/mod_lua.so ``` `mod_lua` provides a handler named `lua-script`, which can be used with a `[SetHandler](core#sethandler)` or `[AddHandler](mod_mime#addhandler)` directive: ``` <Files "*.lua"> SetHandler lua-script </Files> ``` This will cause `mod_lua` to handle requests for files ending in `.lua` by invoking that file's `handle` function. For more flexibility, see `LuaMapHandler`. Writing Handlers ---------------- In the Apache HTTP Server API, the handler is a specific kind of hook responsible for generating the response. Examples of modules that include a handler are `<mod_proxy>`, `<mod_cgi>`, and `<mod_status>`. `mod_lua` always looks to invoke a Lua function for the handler, rather than just evaluating a script body CGI style. A handler function looks something like this: ``` **example.lua** -- example handler require "string" --[[ This is the default method name for Lua handlers, see the optional function-name in the LuaMapHandler directive to choose a different entry point. --]] function handle(r) r.content_type = "text/plain" if r.method == 'GET' then r:puts("Hello Lua World!\n") for k, v in pairs( r:parseargs() ) do r:puts( string.format("%s: %s\n", k, v) ) end elseif r.method == 'POST' then r:puts("Hello Lua World!\n") for k, v in pairs( r:parsebody() ) do r:puts( string.format("%s: %s\n", k, v) ) end elseif r.method == 'PUT' then -- use our own Error contents r:puts("Unsupported HTTP method " .. r.method) r.status = 405 return apache2.OK else -- use the ErrorDocument return 501 end return apache2.OK end ``` This handler function just prints out the uri or form encoded arguments to a plaintext page. This means (and in fact encourages) that you can have multiple handlers (or hooks, or filters) in the same script. Writing Authorization Providers ------------------------------- `<mod_authz_core>` provides a high-level interface to authorization that is much easier to use than using into the relevant hooks directly. The first argument to the `[Require](mod_authz_core#require)` directive gives the name of the responsible authorization provider. For any `[Require](mod_authz_core#require)` line, `<mod_authz_core>` will call the authorization provider of the given name, passing the rest of the line as parameters. The provider will then check authorization and pass the result as return value. The authz provider is normally called before authentication. If it needs to know the authenticated user name (or if the user will be authenticated at all), the provider must return `apache2.AUTHZ_DENIED_NO_USER`. This will cause authentication to proceed and the authz provider to be called a second time. The following authz provider function takes two arguments, one ip address and one user name. It will allow access from the given ip address without authentication, or if the authenticated user matches the second argument: ``` **authz\_provider.lua** require 'apache2' function authz_check_foo(r, ip, user) if r.useragent_ip == ip then return apache2.AUTHZ_GRANTED elseif r.user == nil then return apache2.AUTHZ_DENIED_NO_USER elseif r.user == user then return apache2.AUTHZ_GRANTED else return apache2.AUTHZ_DENIED end end ``` The following configuration registers this function as provider `foo` and configures it for URL `/`: ``` LuaAuthzProvider foo authz_provider.lua authz_check_foo <Location "/"> Require foo 10.1.2.3 john_doe </Location> ``` Writing Hooks ------------- Hook functions are how modules (and Lua scripts) participate in the processing of requests. Each type of hook exposed by the server exists for a specific purpose, such as mapping requests to the file system, performing access control, or setting mime types: | Hook phase | mod\_lua directive | Description | | --- | --- | --- | | Quick handler | `LuaQuickHandler` | This is the first hook that will be called after a request has been mapped to a host or virtual host | | Pre-Translate name | `LuaHookPreTranslateName` | This phase translates the requested URI into a filename on the system, before decoding occurs. Modules such as `<mod_proxy>` can operate in this phase. | | Translate name | `LuaHookTranslateName` | This phase translates the requested URI into a filename on the system. Modules such as `<mod_alias>` and `<mod_rewrite>` operate in this phase. | | Map to storage | `LuaHookMapToStorage` | This phase maps files to their physical, cached or external/proxied storage. It can be used by proxy or caching modules | | Check Access | `LuaHookAccessChecker` | This phase checks whether a client has access to a resource. This phase is run before the user is authenticated, so beware. | | Check User ID | `LuaHookCheckUserID` | This phase it used to check the negotiated user ID | | Check Authorization | `[LuaHookAuthChecker](#luahookauthchecker)` or `[LuaAuthzProvider](#luaauthzprovider)` | This phase authorizes a user based on the negotiated credentials, such as user ID, client certificate etc. | | Check Type | `LuaHookTypeChecker` | This phase checks the requested file and assigns a content type and a handler to it | | Fixups | `LuaHookFixups` | This is the final "fix anything" phase before the content handlers are run. Any last-minute changes to the request should be made here. | | Content handler | fx. `.lua` files or through `[LuaMapHandler](#luamaphandler)` | This is where the content is handled. Files are read, parsed, some are run, and the result is sent to the client | | Logging | `LuaHookLog` | Once a request has been handled, it enters several logging phases, which logs the request in either the error or access log. Mod\_lua is able to hook into the start of this and control logging output. | Hook functions are passed the request object as their only argument (except for LuaAuthzProvider, which also gets passed the arguments from the Require directive). They can return any value, depending on the hook, but most commonly they'll return OK, DONE, or DECLINED, which you can write in Lua as `apache2.OK`, `apache2.DONE`, or `apache2.DECLINED`, or else an HTTP status code. ``` **translate\_name.lua** -- example hook that rewrites the URI to a filesystem path. require 'apache2' function translate_name(r) if r.uri == "/translate-name" then r.filename = r.document_root .. "/find_me.txt" return apache2.OK end -- we don't care about this URL, give another module a chance return apache2.DECLINED end ``` ``` **translate\_name2.lua** --[[ example hook that rewrites one URI to another URI. It returns a apache2.DECLINED to give other URL mappers a chance to work on the substitution, including the core translate_name hook which maps based on the DocumentRoot. Note: Use the early/late flags in the directive to make it run before or after mod_alias. --]] require 'apache2' function translate_name(r) if r.uri == "/translate-name" then r.uri = "/find_me.txt" return apache2.DECLINED end return apache2.DECLINED end ``` Data Structures --------------- request\_rec The request\_rec is mapped in as a userdata. It has a metatable which lets you do useful things with it. For the most part it has the same fields as the request\_rec struct, many of which are writable as well as readable. (The table fields' content can be changed, but the fields themselves cannot be set to different tables.) | **Name** | **Lua type** | **Writable** | **Description** | | --- | --- | --- | --- | | `allowoverrides` | string | no | The AllowOverride options applied to the current request. | | `ap_auth_type` | string | no | If an authentication check was made, this is set to the type of authentication (f.x. `basic`) | | `args` | string | yes | The query string arguments extracted from the request (f.x. `foo=bar&name=johnsmith`) | | `assbackwards` | boolean | no | Set to true if this is an HTTP/0.9 style request (e.g. `GET /foo` (with no headers) ) | | `auth_name` | string | no | The realm name used for authorization (if applicable). | | `banner` | string | no | The server banner, f.x. `Apache HTTP Server/2.4.3 openssl/0.9.8c` | | `basic_auth_pw` | string | no | The basic auth password sent with this request, if any | | `canonical_filename` | string | no | The canonical filename of the request | | `content_encoding` | string | no | The content encoding of the current request | | `content_type` | string | yes | The content type of the current request, as determined in the type\_check phase (f.x. `image/gif` or `text/html`) | | `context_prefix` | string | no | | | `context_document_root` | string | no | | | `document_root` | string | no | The document root of the host | | `err_headers_out` | table | no | MIME header environment for the response, printed even on errors and persist across internal redirects. A read-only lua table suitable for iteration is available as r:err\_headers\_out\_table(). | | `filename` | string | yes | The file name that the request maps to, f.x. /www/example.com/foo.txt. This can be changed in the pre-translate-name, translate-name or map-to-storage phases of a request to allow the default handler (or script handlers) to serve a different file than what was requested. | | `handler` | string | yes | The name of the [handler](../handler) that should serve this request, f.x. `lua-script` if it is to be served by mod\_lua. This is typically set by the `[AddHandler](mod_mime#addhandler)` or `[SetHandler](core#sethandler)` directives, but could also be set via mod\_lua to allow another handler to serve up a specific request that would otherwise not be served by it. | | `headers_in` | table | yes | MIME header environment from the request. This contains headers such as `Host, User-Agent, Referer` and so on. A read-only lua table suitable for iteration is available as r:headers\_in\_table(). | | `headers_out` | table | yes | MIME header environment for the response. A read-only lua table suitable for iteration is available as r:headers\_out\_table(). | | `hostname` | string | no | The host name, as set by the `Host:` header or by a full URI. | | `is_https` | boolean | no | Whether or not this request is done via HTTPS | | `is_initial_req` | boolean | no | Whether this request is the initial request or a sub-request | | `limit_req_body` | number | no | The size limit of the request body for this request, or 0 if no limit. | | `log_id` | string | no | The ID to identify request in access and error log. | | `method` | string | no | The request method, f.x. `GET` or `POST`. | | `notes` | table | yes | A list of notes that can be passed on from one module to another. A read-only lua table suitable for iteration is available as r:notes\_table(). | | `options` | string | no | The Options directive applied to the current request. | | `path_info` | string | no | The PATH\_INFO extracted from this request. | | `port` | number | no | The server port used by the request. | | `protocol` | string | no | The protocol used, f.x. `HTTP/1.1` | | `proxyreq` | string | yes | Denotes whether this is a proxy request or not. This value is generally set in the post\_read\_request/pre\_translate\_name/translate\_name phase of a request. | | `range` | string | no | The contents of the `Range:` header. | | `remaining` | number | no | The number of bytes remaining to be read from the request body. | | `server_built` | string | no | The time the server executable was built. | | `server_name` | string | no | The server name for this request. | | `some_auth_required` | boolean | no | Whether some authorization is/was required for this request. | | `subprocess_env` | table | yes | The environment variables set for this request. A read-only lua table suitable for iteration is available as r:subprocess\_env\_table(). | | `started` | number | no | The time the server was (re)started, in seconds since the epoch (Jan 1st, 1970) | | `status` | number | yes | The (current) HTTP return code for this request, f.x. `200` or `404`. | | `the_request` | string | no | The request string as sent by the client, f.x. `GET /foo/bar HTTP/1.1`. | | `unparsed_uri` | string | no | The unparsed URI of the request | | `uri` | string | yes | The URI after it has been parsed by httpd | | `user` | string | yes | If an authentication check has been made, this is set to the name of the authenticated user. | | `useragent_ip` | string | no | The IP of the user agent making the request | Built in functions ------------------ The request\_rec object has (at least) the following methods: ``` r:flush() -- flushes the output buffer. -- Returns true if the flush was successful, false otherwise. while we_have_stuff_to_send do r:puts("Bla bla bla\n") -- print something to client r:flush() -- flush the buffer (send to client) r.usleep(500000) -- fake processing time for 0.5 sec. and repeat end ``` ``` r:add_output_filter(filter_name) -- add an output filter: r:add_output_filter("fooFilter") -- add the fooFilter to the output stream ``` ``` r:sendfile(filename) -- sends an entire file to the client, using sendfile if supported by the current platform: if use_sendfile_thing then r:sendfile("/var/www/large_file.img") end ``` ``` r:parseargs() -- returns two tables; one standard key/value table for regular GET data, -- and one for multi-value data (fx. foo=1&foo=2&foo=3): local GET, GETMULTI = r:parseargs() r:puts("Your name is: " .. GET['name'] or "Unknown") ``` ``` r:parsebody([sizeLimit]) -- parse the request body as a POST and return two lua tables, -- just like r:parseargs(). -- An optional number may be passed to specify the maximum number -- of bytes to parse. Default is 8192 bytes: local POST, POSTMULTI = r:parsebody(1024*1024) r:puts("Your name is: " .. POST['name'] or "Unknown") ``` ``` r:puts("hello", " world", "!") -- print to response body, self explanatory ``` ``` r:write("a single string") -- print to response body, self explanatory ``` ``` r:escape_html("<html>test</html>") -- Escapes HTML code and returns the escaped result ``` ``` r:base64_encode(string) -- Encodes a string using the Base64 encoding standard: local encoded = r:base64_encode("This is a test") -- returns VGhpcyBpcyBhIHRlc3Q= ``` ``` r:base64_decode(string) -- Decodes a Base64-encoded string: local decoded = r:base64_decode("VGhpcyBpcyBhIHRlc3Q=") -- returns 'This is a test' ``` ``` r:md5(string) -- Calculates and returns the MD5 digest of a string (binary safe): local hash = r:md5("This is a test") -- returns ce114e4501d2f4e2dcea3e17b546f339 ``` ``` r:sha1(string) -- Calculates and returns the SHA1 digest of a string (binary safe): local hash = r:sha1("This is a test") -- returns a54d88e06612d820bc3be72877c74f257b561b19 ``` ``` r:escape(string) -- URL-Escapes a string: local url = "http://foo.bar/1 2 3 & 4 + 5" local escaped = r:escape(url) -- returns 'http%3a%2f%2ffoo.bar%2f1+2+3+%26+4+%2b+5' ``` ``` r:unescape(string) -- Unescapes an URL-escaped string: local url = "http%3a%2f%2ffoo.bar%2f1+2+3+%26+4+%2b+5" local unescaped = r:unescape(url) -- returns 'http://foo.bar/1 2 3 & 4 + 5' ``` ``` r:construct_url(string) -- Constructs an URL from an URI local url = r:construct_url(r.uri) ``` ``` r.mpm_query(number) -- Queries the server for MPM information using ap_mpm_query: local mpm = r.mpm_query(14) if mpm == 1 then r:puts("This server uses the Event MPM") end ``` ``` r:expr(string) -- Evaluates an [expr](../expr) string. if r:expr("%{HTTP_HOST} =~ /^www/") then r:puts("This host name starts with www") end ``` ``` r:scoreboard_process(a) -- Queries the server for information about the process at position a: local process = r:scoreboard_process(1) r:puts("Server 1 has PID " .. process.pid) ``` ``` r:scoreboard_worker(a, b) -- Queries for information about the worker thread, b, in process a: local thread = r:scoreboard_worker(1, 1) r:puts("Server 1's thread 1 has thread ID " .. thread.tid .. " and is in " .. thread.status .. " status") ``` ``` r:clock() -- Returns the current time with microsecond precision ``` ``` r:requestbody(filename) -- Reads and returns the request body of a request. -- If 'filename' is specified, it instead saves the -- contents to that file: local input = r:requestbody() r:puts("You sent the following request body to me:\n") r:puts(input) ``` ``` r:add_input_filter(filter_name) -- Adds 'filter_name' as an input filter ``` ``` r.module_info(module_name) -- Queries the server for information about a module local mod = r.module_info("mod_lua.c") if mod then for k, v in pairs(mod.commands) do r:puts( ("%s: %s\n"):format(k,v)) -- print out all directives accepted by this module end end ``` ``` r:loaded_modules() -- Returns a list of modules loaded by httpd: for k, module in pairs(r:loaded_modules()) do r:puts("I have loaded module " .. module .. "\n") end ``` ``` r:runtime_dir_relative(filename) -- Compute the name of a run-time file (e.g., shared memory "file") -- relative to the appropriate run-time directory. ``` ``` r:server_info() -- Returns a table containing server information, such as -- the name of the httpd executable file, mpm used etc. ``` ``` r:set_document_root(file_path) -- Sets the document root for the request to file_path ``` ``` r:set_context_info(prefix, docroot) -- Sets the context prefix and context document root for a request ``` ``` r:os_escape_path(file_path) -- Converts an OS path to a URL in an OS dependent way ``` ``` r:escape_logitem(string) -- Escapes a string for logging ``` ``` r.strcmp_match(string, pattern) -- Checks if 'string' matches 'pattern' using strcmp_match (globs). -- fx. whether 'www.example.com' matches '*.example.com': local match = r.strcmp_match("foobar.com", "foo*.com") if match then r:puts("foobar.com matches foo*.com") end ``` ``` r:set_keepalive() -- Sets the keepalive status for a request. Returns true if possible, false otherwise. ``` ``` r:make_etag() -- Constructs and returns the etag for the current request. ``` ``` r:send_interim_response(clear) -- Sends an interim (1xx) response to the client. -- if 'clear' is true, available headers will be sent and cleared. ``` ``` r:custom_response(status_code, string) -- Construct and set a custom response for a given status code. -- This works much like the ErrorDocument directive: r:custom_response(404, "Baleted!") ``` ``` r.exists_config_define(string) -- Checks whether a configuration definition exists or not: if r.exists_config_define("FOO") then r:puts("httpd was probably run with -DFOO, or it was defined in the configuration") end ``` ``` r:state_query(string) -- Queries the server for state information ``` ``` r:stat(filename [,wanted]) -- Runs stat() on a file, and returns a table with file information: local info = r:stat("/var/www/foo.txt") if info then r:puts("This file exists and was last modified at: " .. info.modified) end ``` ``` r:regex(string, pattern [,flags]) -- Runs a regular expression match on a string, returning captures if matched: local matches = r:regex("foo bar baz", [[foo (\w+) (\S*)]]) if matches then r:puts("The regex matched, and the last word captured ($2) was: " .. matches[2]) end -- Example ignoring case sensitivity: local matches = r:regex("FOO bar BAz", [[(foo) bar]], 1) -- Flags can be a bitwise combination of: -- 0x01: Ignore case -- 0x02: Multiline search ``` ``` r.usleep(number_of_microseconds) -- Puts the script to sleep for a given number of microseconds. ``` ``` r:dbacquire(dbType[, dbParams]) -- Acquires a connection to a database and returns a database class. -- See '[Database connectivity](#databases)' for details. ``` ``` r:ivm_set("key", value) -- Set an Inter-VM variable to hold a specific value. -- These values persist even though the VM is gone or not being used, -- and so should only be used if MaxConnectionsPerChild is > 0 -- Values can be numbers, strings and booleans, and are stored on a -- per process basis (so they won't do much good with a prefork mpm) r:ivm_get("key") -- Fetches a variable set by ivm_set. Returns the contents of the variable -- if it exists or nil if no such variable exists. -- An example getter/setter that saves a global variable outside the VM: function handle(r) -- First VM to call this will get no value, and will have to create it local foo = r:ivm_get("cached_data") if not foo then foo = do_some_calcs() -- fake some return value r:ivm_set("cached_data", foo) -- set it globally end r:puts("Cached data is: ", foo) end ``` ``` r:htpassword(string [,algorithm [,cost]]) -- Creates a password hash from a string. -- algorithm: 0 = APMD5 (default), 1 = SHA, 2 = BCRYPT, 3 = CRYPT. -- cost: only valid with BCRYPT algorithm (default = 5). ``` ``` r:mkdir(dir [,mode]) -- Creates a directory and sets mode to optional mode parameter. ``` ``` r:mkrdir(dir [,mode]) -- Creates directories recursive and sets mode to optional mode parameter. ``` ``` r:rmdir(dir) -- Removes a directory. ``` ``` r:touch(file [,mtime]) -- Sets the file modification time to current time or to optional mtime msec value. ``` ``` r:get_direntries(dir) -- Returns a table with all directory entries. function handle(r) local dir = r.context_document_root for _, f in ipairs(r:get_direntries(dir)) do local info = r:stat(dir .. "/" .. f) if info then local mtime = os.date(fmt, info.mtime / 1000000) local ftype = (info.filetype == 2) and "[dir] " or "[file]" r:puts( ("%s %s %10i %s\n"):format(ftype, mtime, info.size, f) ) end end end ``` ``` r.date_parse_rfc(string) -- Parses a date/time string and returns seconds since epoche. ``` ``` r:getcookie(key) -- Gets a HTTP cookie ``` ``` r:setcookie{ key = [key], value = [value], expires = [expiry], secure = [boolean], httponly = [boolean], path = [path], domain = [domain] } -- Sets a HTTP cookie, for instance: r:setcookie{ key = "cookie1", value = "HDHfa9eyffh396rt", expires = os.time() + 86400, secure = true } ``` ``` r:wsupgrade() -- Upgrades a connection to WebSockets if possible (and requested): if r:wsupgrade() then -- if we can upgrade: r:wswrite("Welcome to websockets!") -- write something to the client r:wsclose() -- goodbye! end ``` ``` r:wsread() -- Reads a WebSocket frame from a WebSocket upgraded connection (see above): local line, isFinal = r:wsread() -- isFinal denotes whether this is the final frame. -- If it isn't, then more frames can be read r:wswrite("You wrote: " .. line) ``` ``` r:wswrite(line) -- Writes a frame to a WebSocket client: r:wswrite("Hello, world!") ``` ``` r:wsclose() -- Closes a WebSocket request and terminates it for httpd: if r:wsupgrade() then r:wswrite("Write something: ") local line = r:wsread() or "nothing" r:wswrite("You wrote: " .. line); r:wswrite("Goodbye!") r:wsclose() end ``` Logging Functions ----------------- ``` -- examples of logging messages r:trace1("This is a trace log message") -- trace1 through trace8 can be used r:debug("This is a debug log message") r:info("This is an info log message") r:notice("This is a notice log message") r:warn("This is a warn log message") r:err("This is an err log message") r:alert("This is an alert log message") r:crit("This is a crit log message") r:emerg("This is an emerg log message") ``` apache2 Package --------------- A package named `apache2` is available with (at least) the following contents. apache2.OK internal constant OK. Handlers should return this if they've handled the request. apache2.DECLINED internal constant DECLINED. Handlers should return this if they are not going to handle the request. apache2.DONE internal constant DONE. apache2.version Apache HTTP server version string apache2.HTTP\_MOVED\_TEMPORARILY HTTP status code apache2.PROXYREQ\_NONE, apache2.PROXYREQ\_PROXY, apache2.PROXYREQ\_REVERSE, apache2.PROXYREQ\_RESPONSE internal constants used by `<mod_proxy>` apache2.AUTHZ\_DENIED, apache2.AUTHZ\_GRANTED, apache2.AUTHZ\_NEUTRAL, apache2.AUTHZ\_GENERAL\_ERROR, apache2.AUTHZ\_DENIED\_NO\_USER internal constants used by `<mod_authz_core>` (Other HTTP status codes are not yet implemented.) Modifying contents with Lua filters ----------------------------------- Filter functions implemented via `[LuaInputFilter](#luainputfilter)` or `[LuaOutputFilter](#luaoutputfilter)` are designed as three-stage non-blocking functions using coroutines to suspend and resume a function as buckets are sent down the filter chain. The core structure of such a function is: ``` function filter(r) -- Our first yield is to signal that we are ready to receive buckets. -- Before this yield, we can set up our environment, check for conditions, -- and, if we deem it necessary, decline filtering a request altogether: if something_bad then return -- This would skip this filter. end -- Regardless of whether we have data to prepend, a yield MUST be called here. -- Note that only output filters can prepend data. Input filters must use the -- final stage to append data to the content. coroutine.yield([optional header to be prepended to the content]) -- After we have yielded, buckets will be sent to us, one by one, and we can -- do whatever we want with them and then pass on the result. -- Buckets are stored in the global variable 'bucket', so we create a loop -- that checks if 'bucket' is not nil: while bucket ~= nil do local output = mangle(bucket) -- Do some stuff to the content coroutine.yield(output) -- Return our new content to the filter chain end -- Once the buckets are gone, 'bucket' is set to nil, which will exit the -- loop and land us here. Anything extra we want to append to the content -- can be done by doing a final yield here. Both input and output filters -- can append data to the content in this phase. coroutine.yield([optional footer to be appended to the content]) end ``` Database connectivity --------------------- Mod\_lua implements a simple database feature for querying and running commands on the most popular database engines (mySQL, PostgreSQL, FreeTDS, ODBC, SQLite, Oracle) as well as mod\_dbd. The example below shows how to acquire a database handle and return information from a table: ``` function handle(r) -- Acquire a database handle local database, err = r:dbacquire("mysql", "server=localhost,user=someuser,pass=somepass,dbname=mydb") if not err then -- Select some information from it local results, err = database:select(r, "SELECT `name`, `age` FROM `people` WHERE 1") if not err then local rows = results(0) -- fetch all rows synchronously for k, row in pairs(rows) do r:puts( string.format("Name: %s, Age: %s<br/>", row[1], row[2]) ) end else r:puts("Database query error: " .. err) end database:close() else r:puts("Could not connect to the database: " .. err) end end ``` To utilize `<mod_dbd>`, specify `mod_dbd` as the database type, or leave the field blank: ``` local database = r:dbacquire("mod_dbd") ``` ### Database object and contained functions The database object returned by `dbacquire` has the following methods: **Normal select and query from a database:** ``` -- Run a statement and return the number of rows affected: local affected, errmsg = database:query(r, "DELETE FROM `tbl` WHERE 1") -- Run a statement and return a result set that can be used synchronously or async: local result, errmsg = database:select(r, "SELECT * FROM `people` WHERE 1") ``` **Using prepared statements (recommended):** ``` -- Create and run a prepared statement: local statement, errmsg = database:prepare(r, "DELETE FROM `tbl` WHERE `age` > %u") if not errmsg then local result, errmsg = statement:query(20) -- run the statement with age > 20 end -- Fetch a prepared statement from a DBDPrepareSQL directive: local statement, errmsg = database:prepared(r, "someTag") if not errmsg then local result, errmsg = statement:select("John Doe", 123) -- inject the values "John Doe" and 123 into the statement end ``` **Escaping values, closing databases etc:** ``` -- Escape a value for use in a statement: local escaped = database:escape(r, [["'|blabla]]) -- Close a database connection and free up handles: database:close() -- Check whether a database connection is up and running: local connected = database:active() ``` ### Working with result sets The result set returned by `db:select` or by the prepared statement functions created through `db:prepare` can be used to fetch rows synchronously or asynchronously, depending on the row number specified: `result(0)` fetches all rows in a synchronous manner, returning a table of rows. `result(-1)` fetches the next available row in the set, asynchronously. `result(N)` fetches row number `N`, asynchronously: ``` -- fetch a result set using a regular query: local result, err = db:select(r, "SELECT * FROM `tbl` WHERE 1") local rows = result(0) -- Fetch ALL rows synchronously local row = result(-1) -- Fetch the next available row, asynchronously local row = result(1234) -- Fetch row number 1234, asynchronously local row = result(-1, true) -- Fetch the next available row, using row names as key indexes. ``` One can construct a function that returns an iterative function to iterate over all rows in a synchronous or asynchronous way, depending on the async argument: ``` function rows(resultset, async) local a = 0 local function getnext() a = a + 1 local row = resultset(-1) return row and a or nil, row end if not async then return pairs(resultset(0)) else return getnext, self end end local statement, err = db:prepare(r, "SELECT * FROM `tbl` WHERE `age` > %u") if not err then -- fetch rows asynchronously: local result, err = statement:select(20) if not err then for index, row in rows(result, true) do .... end end -- fetch rows synchronously: local result, err = statement:select(20) if not err then for index, row in rows(result, false) do .... end end end ``` ### Closing a database connection Database handles should be closed using `database:close()` when they are no longer needed. If you do not close them manually, they will eventually be garbage collected and closed by mod\_lua, but you may end up having too many unused connections to the database if you leave the closing up to mod\_lua. Essentially, the following two measures are the same: ``` -- Method 1: Manually close a handle local database = r:dbacquire("mod_dbd") database:close() -- All done -- Method 2: Letting the garbage collector close it local database = r:dbacquire("mod_dbd") database = nil -- throw away the reference collectgarbage() -- close the handle via GC ``` ### Precautions when working with databases Although the standard `query` and `run` functions are freely available, it is recommended that you use prepared statements whenever possible, to both optimize performance (if your db handle lives on for a long time) and to minimize the risk of SQL injection attacks. `run` and `query` should only be used when there are no variables inserted into a statement (a static statement). When using dynamic statements, use `db:prepare` or `db:prepared`. LuaAuthzProvider Directive -------------------------- | | | | --- | --- | | Description: | Plug an authorization provider function into `<mod_authz_core>` | | Syntax: | ``` LuaAuthzProvider provider_name /path/to/lua/script.lua function_name ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_lua | | Compatibility: | 2.4.3 and later | After a lua function has been registered as authorization provider, it can be used with the `[Require](mod_authz_core#require)` directive: ``` LuaRoot "/usr/local/apache2/lua" LuaAuthzProvider foo authz.lua authz_check_foo <Location "/"> Require foo johndoe </Location> ``` ``` require "apache2" function authz_check_foo(r, who) if r.user ~= who then return apache2.AUTHZ_DENIED return apache2.AUTHZ_GRANTED end ``` LuaCodeCache Directive ---------------------- | | | | --- | --- | | Description: | Configure the compiled code cache. | | Syntax: | ``` LuaCodeCache stat|forever|never ``` | | Default: | ``` LuaCodeCache stat ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | Specify the behavior of the in-memory code cache. The default is stat, which stats the top level script (not any included ones) each time that file is needed, and reloads it if the modified time indicates it is newer than the one it has already loaded. The other values cause it to keep the file cached forever (don't stat and replace) or to never cache the file. In general stat or forever is good for production, and stat or never for development. ### Examples: ``` LuaCodeCache stat LuaCodeCache forever LuaCodeCache never ``` LuaHookAccessChecker Directive ------------------------------ | | | | --- | --- | | Description: | Provide a hook for the access\_checker phase of request processing | | Syntax: | ``` LuaHookAccessChecker /path/to/lua/script.lua hook_function_name [early|late] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | | Compatibility: | The optional third argument is supported in 2.3.15 and later | Add your hook to the access\_checker phase. An access checker hook function usually returns OK, DECLINED, or HTTP\_FORBIDDEN. **Ordering** The optional arguments "early" or "late" control when this script runs relative to other modules. LuaHookAuthChecker Directive ---------------------------- | | | | --- | --- | | Description: | Provide a hook for the auth\_checker phase of request processing | | Syntax: | ``` LuaHookAuthChecker /path/to/lua/script.lua hook_function_name [early|late] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | | Compatibility: | The optional third argument is supported in 2.3.15 and later | Invoke a lua function in the auth\_checker phase of processing a request. This can be used to implement arbitrary authentication and authorization checking. A very simple example: ``` require 'apache2' -- fake authcheck hook -- If request has no auth info, set the response header and -- return a 401 to ask the browser for basic auth info. -- If request has auth info, don't actually look at it, just -- pretend we got userid 'foo' and validated it. -- Then check if the userid is 'foo' and accept the request. function authcheck_hook(r) -- look for auth info auth = r.headers_in['Authorization'] if auth ~= nil then -- fake the user r.user = 'foo' end if r.user == nil then r:debug("authcheck: user is nil, returning 401") r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"' return 401 elseif r.user == "foo" then r:debug('user foo: OK') else r:debug("authcheck: user='" .. r.user .. "'") r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"' return 401 end return apache2.OK end ``` **Ordering** The optional arguments "early" or "late" control when this script runs relative to other modules. LuaHookCheckUserID Directive ---------------------------- | | | | --- | --- | | Description: | Provide a hook for the check\_user\_id phase of request processing | | Syntax: | ``` LuaHookCheckUserID /path/to/lua/script.lua hook_function_name [early|late] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | | Compatibility: | The optional third argument is supported in 2.3.15 and later | ... **Ordering** The optional arguments "early" or "late" control when this script runs relative to other modules. LuaHookFixups Directive ----------------------- | | | | --- | --- | | Description: | Provide a hook for the fixups phase of a request processing | | Syntax: | ``` LuaHookFixups /path/to/lua/script.lua hook_function_name ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | Just like LuaHookTranslateName, but executed at the fixups phase LuaHookInsertFilter Directive ----------------------------- | | | | --- | --- | | Description: | Provide a hook for the insert\_filter phase of request processing | | Syntax: | ``` LuaHookInsertFilter /path/to/lua/script.lua hook_function_name ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | Not Yet Implemented LuaHookLog Directive -------------------- | | | | --- | --- | | Description: | Provide a hook for the access log phase of a request processing | | Syntax: | ``` LuaHookLog /path/to/lua/script.lua log_function_name ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | This simple logging hook allows you to run a function when httpd enters the logging phase of a request. With it, you can append data to your own logs, manipulate data before the regular log is written, or prevent a log entry from being created. To prevent the usual logging from happening, simply return `apache2.DONE` in your logging handler, otherwise return `apache2.OK` to tell httpd to log as normal. Example: ``` LuaHookLog "/path/to/script.lua" logger ``` ``` -- /path/to/script.lua -- function logger(r) -- flip a coin: -- If 1, then we write to our own Lua log and tell httpd not to log -- in the main log. -- If 2, then we just sanitize the output a bit and tell httpd to -- log the sanitized bits. if math.random(1,2) == 1 then -- Log stuff ourselves and don't log in the regular log local f = io.open("/foo/secret.log", "a") if f then f:write("Something secret happened at " .. r.uri .. "\n") f:close() end return apache2.DONE -- Tell httpd not to use the regular logging functions else r.uri = r.uri:gsub("somesecretstuff", "") -- sanitize the URI return apache2.OK -- tell httpd to log it. end end ``` LuaHookMapToStorage Directive ----------------------------- | | | | --- | --- | | Description: | Provide a hook for the map\_to\_storage phase of request processing | | Syntax: | ``` LuaHookMapToStorage /path/to/lua/script.lua hook_function_name ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | Like `LuaHookTranslateName` but executed at the map-to-storage phase of a request. Modules like mod\_cache run at this phase, which makes for an interesting example on what to do here: ``` LuaHookMapToStorage "/path/to/lua/script.lua" check_cache ``` ``` require"apache2" cached_files = {} function read_file(filename) local input = io.open(filename, "r") if input then local data = input:read("*a") cached_files[filename] = data file = cached_files[filename] input:close() end return cached_files[filename] end function check_cache(r) if r.filename:match("%.png$") then -- Only match PNG files local file = cached_files[r.filename] -- Check cache entries if not file then file = read_file(r.filename) -- Read file into cache end if file then -- If file exists, write it out r.status = 200 r:write(file) r:info(("Sent %s to client from cache"):format(r.filename)) return apache2.DONE -- skip default handler for PNG files end end return apache2.DECLINED -- If we had nothing to do, let others serve this. end ``` LuaHookPreTranslate Directive ----------------------------- | | | | --- | --- | | Description: | Provide a hook for the pre\_translate phase of a request processing | | Syntax: | ``` LuaHookPreTranslate /path/to/lua/script.lua hook_function_name ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | Just like LuaHookTranslateName, but executed at the pre\_translate phase, where the URI-path is not percent decoded. LuaHookTranslateName Directive ------------------------------ | | | | --- | --- | | Description: | Provide a hook for the translate name phase of request processing | | Syntax: | ``` LuaHookTranslateName /path/to/lua/script.lua hook_function_name [early|late] ``` | | Context: | server config, virtual host | | Override: | All | | Status: | Extension | | Module: | mod\_lua | | Compatibility: | The optional third argument is supported in 2.3.15 and later | Add a hook (at APR\_HOOK\_MIDDLE) to the translate name phase of request processing. The hook function receives a single argument, the request\_rec, and should return a status code, which is either an HTTP error code, or the constants defined in the apache2 module: apache2.OK, apache2.DECLINED, or apache2.DONE. For those new to hooks, basically each hook will be invoked until one of them returns apache2.OK. If your hook doesn't want to do the translation it should just return apache2.DECLINED. If the request should stop processing, then return apache2.DONE. Example: ``` # httpd.conf LuaHookTranslateName "/scripts/conf/hooks.lua" silly_mapper ``` ``` -- /scripts/conf/hooks.lua -- require "apache2" function silly_mapper(r) if r.uri == "/" then r.filename = "/var/www/home.lua" return apache2.OK else return apache2.DECLINED end end ``` **Context** This directive is not valid in `[<Directory>](core#directory)`, `[<Files>](core#files)`, or htaccess context. **Ordering** The optional arguments "early" or "late" control when this script runs relative to other modules. LuaHookTypeChecker Directive ---------------------------- | | | | --- | --- | | Description: | Provide a hook for the type\_checker phase of request processing | | Syntax: | ``` LuaHookTypeChecker /path/to/lua/script.lua hook_function_name ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | This directive provides a hook for the type\_checker phase of the request processing. This phase is where requests are assigned a content type and a handler, and thus can be used to modify the type and handler based on input: ``` LuaHookTypeChecker "/path/to/lua/script.lua" type_checker ``` ``` function type_checker(r) if r.uri:match("%.to_gif$") then -- match foo.png.to_gif r.content_type = "image/gif" -- assign it the image/gif type r.handler = "gifWizard" -- tell the gifWizard module to handle this r.filename = r.uri:gsub("%.to_gif$", "") -- fix the filename requested return apache2.OK end return apache2.DECLINED end ``` LuaInherit Directive -------------------- | | | | --- | --- | | Description: | Controls how parent configuration sections are merged into children | | Syntax: | ``` LuaInherit none|parent-first|parent-last ``` | | Default: | ``` LuaInherit parent-first ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | | Compatibility: | 2.4.0 and later | By default, if LuaHook\* directives are used in overlapping Directory or Location configuration sections, the scripts defined in the more specific section are run *after* those defined in the more generic section (LuaInherit parent-first). You can reverse this order, or make the parent context not apply at all. In previous 2.3.x releases, the default was effectively to ignore LuaHook\* directives from parent configuration sections. LuaInputFilter Directive ------------------------ | | | | --- | --- | | Description: | Provide a Lua function for content input filtering | | Syntax: | ``` LuaInputFilter filter_name /path/to/lua/script.lua function_name ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_lua | | Compatibility: | 2.4.5 and later | Provides a means of adding a Lua function as an input filter. As with output filters, input filters work as coroutines, first yielding before buffers are sent, then yielding whenever a bucket needs to be passed down the chain, and finally (optionally) yielding anything that needs to be appended to the input data. The global variable `bucket` holds the buckets as they are passed onto the Lua script: ``` LuaInputFilter myInputFilter "/www/filter.lua" input_filter <Files "*.lua"> SetInputFilter myInputFilter </Files> ``` ``` --[[ Example input filter that converts all POST data to uppercase. ]]-- function input_filter(r) print("luaInputFilter called") -- debug print coroutine.yield() -- Yield and wait for buckets while bucket do -- For each bucket, do... local output = string.upper(bucket) -- Convert all POST data to uppercase coroutine.yield(output) -- Send converted data down the chain end -- No more buckets available. coroutine.yield("&filterSignature=1234") -- Append signature at the end end ``` The input filter supports denying/skipping a filter if it is deemed unwanted: ``` function input_filter(r) if not good then return -- Simply deny filtering, passing on the original content instead end coroutine.yield() -- wait for buckets ... -- insert filter stuff here end ``` See "[Modifying contents with Lua filters](#modifying_buckets)" for more information. LuaMapHandler Directive ----------------------- | | | | --- | --- | | Description: | Map a path to a lua handler | | Syntax: | ``` LuaMapHandler uri-pattern /path/to/lua/script.lua [function-name] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | This directive matches a uri pattern to invoke a specific handler function in a specific file. It uses PCRE regular expressions to match the uri, and supports interpolating match groups into both the file path and the function name. Be careful writing your regular expressions to avoid security issues. ### Examples: ``` LuaMapHandler "/(\w+)/(\w+)" "/scripts/$1.lua" "handle_$2" ``` This would match uri's such as /photos/show?id=9 to the file /scripts/photos.lua and invoke the handler function handle\_show on the lua vm after loading that file. ``` LuaMapHandler "/bingo" "/scripts/wombat.lua" ``` This would invoke the "handle" function, which is the default if no specific function name is provided. LuaOutputFilter Directive ------------------------- | | | | --- | --- | | Description: | Provide a Lua function for content output filtering | | Syntax: | ``` LuaOutputFilter filter_name /path/to/lua/script.lua function_name ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_lua | | Compatibility: | 2.4.5 and later | Provides a means of adding a Lua function as an output filter. As with input filters, output filters work as coroutines, first yielding before buffers are sent, then yielding whenever a bucket needs to be passed down the chain, and finally (optionally) yielding anything that needs to be appended to the input data. The global variable `bucket` holds the buckets as they are passed onto the Lua script: ``` LuaOutputFilter myOutputFilter "/www/filter.lua" output_filter <Files "*.lua"> SetOutputFilter myOutputFilter </Files> ``` ``` --[[ Example output filter that escapes all HTML entities in the output ]]-- function output_filter(r) coroutine.yield("(Handled by myOutputFilter)<br/>\n") -- Prepend some data to the output, -- yield and wait for buckets. while bucket do -- For each bucket, do... local output = r:escape_html(bucket) -- Escape all output coroutine.yield(output) -- Send converted data down the chain end -- No more buckets available. end ``` As with the input filter, the output filter supports denying/skipping a filter if it is deemed unwanted: ``` function output_filter(r) if not r.content_type:match("text/html") then return -- Simply deny filtering, passing on the original content instead end coroutine.yield() -- wait for buckets ... -- insert filter stuff here end ``` **Lua filters with `<mod_filter>`** When a Lua filter is used as the underlying provider via the `[FilterProvider](mod_filter#filterprovider)` directive, filtering will only work when the filter-name is identical to the provider-name. See "[Modifying contents with Lua filters](#modifying_buckets)" for more information. LuaPackageCPath Directive ------------------------- | | | | --- | --- | | Description: | Add a directory to lua's package.cpath | | Syntax: | ``` LuaPackageCPath /path/to/include/?.soa ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | Add a path to lua's shared library search path. Follows the same conventions as lua. This just munges the package.cpath in the lua vms. LuaPackagePath Directive ------------------------ | | | | --- | --- | | Description: | Add a directory to lua's package.path | | Syntax: | ``` LuaPackagePath /path/to/include/?.lua ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | Add a path to lua's module search path. Follows the same conventions as lua. This just munges the package.path in the lua vms. ### Examples: ``` LuaPackagePath "/scripts/lib/?.lua" LuaPackagePath "/scripts/lib/?/init.lua" ``` LuaQuickHandler Directive ------------------------- | | | | --- | --- | | Description: | Provide a hook for the quick handler of request processing | | Syntax: | ``` LuaQuickHandler /path/to/script.lua hook_function_name ``` | | Context: | server config, virtual host | | Override: | All | | Status: | Extension | | Module: | mod\_lua | This phase is run immediately after the request has been mapped to a virtal host, and can be used to either do some request processing before the other phases kick in, or to serve a request without the need to translate, map to storage et cetera. As this phase is run before anything else, directives such as `[<Location>](core#location)` or `[<Directory>](core#directory)` are void in this phase, just as URIs have not been properly parsed yet. **Context** This directive is not valid in `[<Directory>](core#directory)`, `[<Files>](core#files)`, or htaccess context. LuaRoot Directive ----------------- | | | | --- | --- | | Description: | Specify the base path for resolving relative paths for mod\_lua directives | | Syntax: | ``` LuaRoot /path/to/a/directory ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | Specify the base path which will be used to evaluate all relative paths within mod\_lua. If not specified they will be resolved relative to the current working directory, which may not always work well for a server. LuaScope Directive ------------------ | | | | --- | --- | | Description: | One of once, request, conn, thread -- default is once | | Syntax: | ``` LuaScope once|request|conn|thread|server [min] [max] ``` | | Default: | ``` LuaScope once ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_lua | Specify the life cycle scope of the Lua interpreter which will be used by handlers in this "Directory." The default is "once" once: use the interpreter once and throw it away. request: use the interpreter to handle anything based on the same file within this request, which is also request scoped. conn: Same as request but attached to the connection\_rec thread: Use the interpreter for the lifetime of the thread handling the request (only available with threaded MPMs). server: This one is different than others because the server scope is quite long lived, and multiple threads will have the same server\_rec. To accommodate this, server scoped Lua states are stored in an apr resource list. The `min` and `max` arguments specify the minimum and maximum number of Lua states to keep in the pool. Generally speaking, the `thread` and `server` scopes execute roughly 2-3 times faster than the rest, because they don't have to spawn new Lua states on every request (especially with the event MPM, as even keepalive requests will use a new thread for each request). If you are satisfied that your scripts will not have problems reusing a state, then the `thread` or `server` scopes should be used for maximum performance. While the `thread` scope will provide the fastest responses, the `server` scope will use less memory, as states are pooled, allowing f.x. 1000 threads to share only 100 Lua states, thus using only 10% of the memory required by the `thread` scope.
programming_docs
apache_http_server Apache Module mod_proxy_hcheck Apache Module mod\_proxy\_hcheck ================================ | | | | --- | --- | | Description: | Dynamic health check of Balancer members (workers) for `<mod_proxy>` | | Status: | Extension | | Module Identifier: | proxy\_hcheck\_module | | Source File: | mod\_proxy\_hcheck.c | | Compatibility: | Available in Apache 2.4.21 and later | ### Summary This module provides for dynamic health checking of balancer members (workers). This can be enabled on a worker-by-worker basis. The health check is done independently of the actual reverse proxy requests. This module *requires* the service of `<mod_watchdog>`. **Parameters** The health check mechanism is enabled via the use of additional `[BalancerMember](mod_proxy#balancermember)` parameters, which are configured in the standard way via `[ProxyPass](mod_proxy#proxypass)`: A new BalancerMember [status](mod_proxy#status_table) state (flag) is defined via this module: "`C`". When the worker is taken offline due to failures as determined by the health check module, this flag is set, and can be seen (and modified) via the `balancer-manager`. | Parameter | Default | Description | | --- | --- | --- | | hcmethod | None | No dynamic health check performed. Choices are: | Method | Description | Note | | --- | --- | --- | | None | No dynamic health checking done | | | TCP | Check that a socket to the backend can be created: e.g. "are you up" | | | OPTIONS | Send an `HTTP OPTIONS` request to the backend | \* | | HEAD | Send an `HTTP HEAD` request to the backend | \* | | GET | Send an `HTTP GET` request to the backend | \* | | | | \*: Unless `hcexpr` is used, a 2xx or 3xx HTTP status will be interpreted as *passing* the health check | | | hcpasses | 1 | Number of successful health check tests before worker is re-enabled | | hcfails | 1 | Number of failed health check tests before worker is disabled | | hcinterval | 30 | Period of health checks in seconds (e.g. performed every 30 seconds) | | hcuri | | Additional URI to be appended to the worker URL for the health check. | | hctemplate | | Name of template, created via `[ProxyHCTemplate](#proxyhctemplate)`, to use for setting health check parameters for this worker | | hcexpr | | Name of expression, created via `[ProxyHCExpr](#proxyhcexpr)`, used to check response headers for health. *If not used, 2xx thru 3xx status codes imply success* | Usage examples -------------- The following example shows how one might configured health checking for various backend servers: ``` ProxyHCExpr ok234 {%{REQUEST_STATUS} =~ /^[234]/} ProxyHCExpr gdown {%{REQUEST_STATUS} =~ /^[5]/} ProxyHCExpr in_maint {hc('body') !~ /Under maintenance/} <Proxy balancer://foo> BalancerMember http://www.example.com/ hcmethod=GET hcexpr=in_maint hcuri=/status.php BalancerMember http://www2.example.com/ hcmethod=HEAD hcexpr=ok234 hcinterval=10 BalancerMember http://www3.example.com/ hcmethod=TCP hcinterval=5 hcpasses=2 hcfails=3 BalancerMember http://www4.example.com/ </Proxy> ProxyPass "/" "balancer://foo" ProxyPassReverse "/" "balancer://foo" ``` In this scenario, `http://www.example.com/` is health checked by sending a `GET /status.php` request to that server and seeing that the returned page does not include the string *Under maintenance*. If it does, that server is put in health-check fail mode, and disabled. This dynamic check is performed every 30 seconds, which is the default. `http://www2.example.com/` is checked by sending a simple `HEAD` request every 10 seconds and making sure that the response status is 2xx, 3xx or 4xx. `http://www3.example.com/` is checked every 5 seconds by simply ensuring that the socket to that server is up. If the backend is marked as "down" and it passes 2 health check, it will be re-enabled and added back into the load balancer. It takes 3 back-to-back health check failures to disable the server and move it out of rotation. Finally, `http://www4.example.com/` is not dynamically checked at all. ProxyHCExpr Directive --------------------- | | | | --- | --- | | Description: | Creates a named condition expression to use to determine health of the backend based on its response | | Syntax: | ``` ProxyHCExpr name {ap_expr expression} ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy\_hcheck | The `ProxyHCExpr` directive allows for creating a named condition expression that checks the response headers of the backend server to determine its health. This named condition can then be assigned to balancer members via the `hcexpr` parameter. ### ProxyHCExpr: Allow for 2xx/3xx/4xx as passing ``` ProxyHCExpr ok234 {%{REQUEST_STATUS} =~ /^[234]/} ProxyPass "/apps" "balancer://foo" <Proxy balancer://foo> BalancerMember http://www2.example.com/ hcmethod=HEAD hcexpr=ok234 hcinterval=10 </Proxy> ``` The [expression](../expr) can use curly-parens ("{}") as quoting deliminators in addition to normal quotes. If using a health check method (eg: `GET`) which results in a response body, that body itself can be checked via `ap_expr` using the `hc()` expression function, which is unique to this module. In the following example, we send the backend a `GET` request and if the response body contains the phrase *Under maintenance*, we want to disable the backend. ### ProxyHCExpr: Checking response body ``` ProxyHCExpr in_maint {hc('body') !~ /Under maintenance/} ProxyPass "/apps" "balancer://foo" <Proxy balancer://foo> BalancerMember http://www.example.com/ hcexpr=in_maint hcmethod=get hcuri=/status.php </Proxy> ``` *NOTE:* Since response body can quite large, it is best if used against specific status pages. ProxyHCTemplate Directive ------------------------- | | | | --- | --- | | Description: | Creates a named template for setting various health check parameters | | Syntax: | ``` ProxyHCTemplate name parameter=setting [...] ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy\_hcheck | The `ProxyHCTemplate` directive allows for creating a named set (template) of health check parameters that can then be assigned to balancer members via the `hctemplate` parameter. ### ProxyHCTemplate ``` ProxyHCTemplate tcp5 hcmethod=tcp hcinterval=5 ProxyPass "/apps" "balancer://foo" <Proxy balancer://foo> BalancerMember http://www2.example.com/ hctemplate=tcp5 </Proxy> ``` ProxyHCTPsize Directive ----------------------- | | | | --- | --- | | Description: | Sets the total server-wide size of the threadpool used for the health check workers | | Syntax: | ``` ProxyHCTPsize size ``` | | Default: | ``` ProxyHCTPsize 16 ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_proxy\_hcheck | If Apache httpd and APR are built with thread support, the health check module will offload the work of the actual checking to a threadpool associated with the Watchdog process, allowing for parallel checks. The `ProxyHCTPsize` directive determines the size of this threadpool. If set to `0`, no threadpool is used at all, resulting in serialized health checks. ### ProxyHCTPsize ``` ProxyHCTPsize 32 ``` apache_http_server Apache Module mod_dav_fs Apache Module mod\_dav\_fs ========================== | | | | --- | --- | | Description: | Filesystem provider for `<mod_dav>` | | Status: | Extension | | Module Identifier: | dav\_fs\_module | | Source File: | mod\_dav\_fs.c | ### Summary This module *requires* the service of `<mod_dav>`. It acts as a support module for `<mod_dav>` and provides access to resources located in the server's file system. The formal name of this provider is `filesystem`. `<mod_dav>` backend providers will be invoked by using the `[Dav](mod_dav#dav)` directive: ### Example ``` Dav filesystem ``` Since `filesystem` is the default provider for `<mod_dav>`, you may simply use the value `On` instead. DavLockDB Directive ------------------- | | | | --- | --- | | Description: | Location of the DAV lock database | | Syntax: | ``` DavLockDB file-path ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_dav\_fs | Use the `DavLockDB` directive to specify the full path to the lock database, excluding an extension. If the path is not absolute, it will be taken relative to `[ServerRoot](core#serverroot)`. The implementation of `<mod_dav_fs>` uses a SDBM database to track user locks. ### Example ``` DavLockDB "var/DavLock" ``` The directory containing the lock database file must be writable by the `[User](mod_unixd#user)` and `[Group](mod_unixd#group)` under which Apache is running. For security reasons, you should create a directory for this purpose rather than changing the permissions on an existing directory. In the above example, Apache will create files in the `var/` directory under the `[ServerRoot](core#serverroot)` with the base filename `DavLock` and extension name chosen by the server. apache_http_server Apache Module mod_mime_magic Apache Module mod\_mime\_magic ============================== | | | | --- | --- | | Description: | Determines the MIME type of a file by looking at a few bytes of its contents | | Status: | Extension | | Module Identifier: | mime\_magic\_module | | Source File: | mod\_mime\_magic.c | ### Summary This module determines the [MIME type](https://httpd.apache.org/docs/2.4/en/glossary.html#mime-type "see glossary") of files in the same way the Unix `file(1)` command works: it looks at the first few bytes of the file. It is intended as a "second line of defense" for cases that `<mod_mime>` can't resolve. This module is derived from a free version of the `file(1)` command for Unix, which uses "magic numbers" and other hints from a file's contents to figure out what the contents are. This module is active only if the magic file is specified by the `[MimeMagicFile](#mimemagicfile)` directive. Format of the Magic File ------------------------ The contents of the file are plain ASCII text in 4-5 columns. Blank lines are allowed but ignored. Commented lines use a hash mark (`#`). The remaining lines are parsed for the following columns: | Column | Description | | --- | --- | | 1 | byte number to begin checking from "`>`" indicates a dependency upon the previous non-"`>`" line | | 2 | type of data to match | | | | --- | --- | | `byte` | single character | | `short` | machine-order 16-bit integer | | `long` | machine-order 32-bit integer | | `string` | arbitrary-length string | | `date` | long integer date (seconds since Unix epoch/1970) | | `beshort` | big-endian 16-bit integer | | `belong` | big-endian 32-bit integer | | `bedate` | big-endian 32-bit integer date | | `leshort` | little-endian 16-bit integer | | `lelong` | little-endian 32-bit integer | | `ledate` | little-endian 32-bit integer date | | | 3 | contents of data to match | | 4 | MIME type if matched | | 5 | MIME encoding if matched (optional) | For example, the following magic file lines would recognize some audio formats: ``` # Sun/NeXT audio data 0 string .snd >12 belong 1 audio/basic >12 belong 2 audio/basic >12 belong 3 audio/basic >12 belong 4 audio/basic >12 belong 5 audio/basic >12 belong 6 audio/basic >12 belong 7 audio/basic >12 belong 23 audio/x-adpcm ``` Or these would recognize the difference between `*.doc` files containing Microsoft Word or FrameMaker documents. (These are incompatible file formats which use the same file suffix.) ``` # Frame 0 string \<MakerFile application/x-frame 0 string \<MIFFile application/x-frame 0 string \<MakerDictionary application/x-frame 0 string \<MakerScreenFon application/x-frame 0 string \<MML application/x-frame 0 string \<Book application/x-frame 0 string \<Maker application/x-frame # MS-Word 0 string \376\067\0\043 application/msword 0 string \320\317\021\340\241\261 application/msword 0 string \333\245-\0\0\0 application/msword ``` An optional MIME encoding can be included as a fifth column. For example, this can recognize gzipped files and set the encoding for them. ``` # gzip (GNU zip, not to be confused with # [Info-ZIP/PKWARE] zip archiver) 0 string \037\213 application/octet-stream x-gzip ``` Performance Issues ------------------ This module is not for every system. If your system is barely keeping up with its load or if you're performing a web server benchmark, you may not want to enable this because the processing is not free. However, an effort was made to improve the performance of the original `file(1)` code to make it fit in a busy web server. It was designed for a server where there are thousands of users who publish their own documents. This is probably very common on intranets. Many times, it's helpful if the server can make more intelligent decisions about a file's contents than the file name allows ...even if just to reduce the "why doesn't my page work" calls when users improperly name their own files. You have to decide if the extra work suits your environment. Notes ----- The following notes apply to the `<mod_mime_magic>` module and are included here for compliance with contributors' copyright restrictions that require their acknowledgment. mod\_mime\_magic: MIME type lookup via file magic numbers Copyright (c) 1996-1997 Cisco Systems, Inc. This software was submitted by Cisco Systems to the Apache Group in July 1997. Future revisions and derivatives of this source code must acknowledge Cisco Systems as the original contributor of this module. All other licensing and usage conditions are those of the Apache Group. Some of this code is derived from the free version of the file command originally posted to comp.sources.unix. Copyright info for that program is included below as required. - Copyright (c) Ian F. Darwin, 1987. Written by Ian F. Darwin. This software is not subject to any license of the American Telephone and Telegraph Company or of the Regents of the University of California. Permission is granted to anyone to use this software for any purpose on any computer system, and to alter it and redistribute it freely, subject to the following restrictions: 1. The author is not responsible for the consequences of use of this software, no matter how awful, even if they arise from flaws in it. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. Since few users ever read sources, credits must appear in the documentation. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. Since few users ever read sources, credits must appear in the documentation. 4. This notice may not be removed or altered. For compliance with Mr Darwin's terms: this has been very significantly modified from the free "file" command. * all-in-one file for compilation convenience when moving from one version of Apache to the next. * Memory allocation is done through the Apache API's pool structure. * All functions have had necessary Apache API request or server structures passed to them where necessary to call other Apache API routines. (*i.e.*, usually for logging, files, or memory allocation in itself or a called function.) * struct magic has been converted from an array to a single-ended linked list because it only grows one record at a time, it's only accessed sequentially, and the Apache API has no equivalent of `realloc()`. * Functions have been changed to get their parameters from the server configuration instead of globals. (It should be reentrant now but has not been tested in a threaded environment.) * Places where it used to print results to stdout now saves them in a list where they're used to set the MIME type in the Apache request record. * Command-line flags have been removed since they will never be used here. MimeMagicFile Directive ----------------------- | | | | --- | --- | | Description: | Enable MIME-type determination based on file contents using the specified magic file | | Syntax: | ``` MimeMagicFile file-path ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_mime\_magic | The `MimeMagicFile` directive can be used to enable this module, the default file is distributed at `conf/magic`. Non-rooted paths are relative to the `[ServerRoot](core#serverroot)`. Virtual hosts will use the same file as the main server unless a more specific setting is used, in which case the more specific setting overrides the main server's file. ### Example ``` MimeMagicFile conf/magic ``` apache_http_server Apache Module mod_slotmem_shm Apache Module mod\_slotmem\_shm =============================== | | | | --- | --- | | Description: | Slot-based shared memory provider. | | Status: | Extension | | Module Identifier: | slotmem\_shm\_module | | Source File: | mod\_slotmem\_shm.c | ### Summary `<mod_slotmem_shm>` is a memory provider which provides for creation and access to a shared memory segment in which the datasets are organized in "slots." All shared memory is cleared and cleaned with each restart, whether graceful or not. The data itself is stored and restored within a file noted by the `name` parameter in the `create` and `attach` calls. If not specified with an absolute path, the file will be created relative to the path specified by the `[DefaultRuntimeDir](core#defaultruntimedir)` directive. `<mod_slotmem_shm>` provides the following API functions: ``` /* call the callback on all worker slots */ apr_status_t doall(ap_slotmem_instance_t *s, ap_slotmem_callback_fn_t *func, void *data, apr_pool_t *pool) /* create a new slotmem with each item size is item_size. 'name' is used to generate a filename for the persistent store of the shared memory if configured. Values are: "none" - Anonymous shared memory and no persistent store "file-name" - [DefaultRuntimeDir]/file-name "/absolute-file-name" - Absolute file name */ apr_status_t create(ap_slotmem_instance_t **new, const char *name, apr_size_t item_size, unsigned int item_num, ap_slotmem_type_t type, apr_pool_t *pool) /* attach to an existing slotmem. See 'create()' for description of 'name' parameter */ apr_status_t attach(ap_slotmem_instance_t **new, const char *name, apr_size_t *item_size, unsigned int *item_num, apr_pool_t *pool) /* get the direct pointer to the memory associated with this worker slot */ apr_status_t dptr(ap_slotmem_instance_t *s, unsigned int item_id, void **mem) /* get/read the memory from this slot to dest */ apr_status_t get(ap_slotmem_instance_t *s, unsigned int item_id, unsigned char *dest, apr_size_t dest_len) /* put/write the data from src to this slot */ apr_status_t put(ap_slotmem_instance_t *slot, unsigned int item_id, unsigned char *src, apr_size_t src_len) /* return the total number of slots in the segment */ unsigned int num_slots(ap_slotmem_instance_t *s) /* return the total data size, in bytes, of a slot in the segment */ apr_size_t slot_size(ap_slotmem_instance_t *s) /* grab or allocate the first free slot and mark as in-use (does not do any data copying) */ apr_status_t grab(ap_slotmem_instance_t *s, unsigned int *item_id) /* forced grab or allocate the specified slot and mark as in-use (does not do any data copying) */ apr_status_t fgrab(ap_slotmem_instance_t *s, unsigned int item_id) /* release or free a slot and mark as not in-use (does not do any data copying) */ apr_status_t release(ap_slotmem_instance_t *s, unsigned int item_id) ``` apache_http_server Apache Module mod_authnz_fcgi Apache Module mod\_authnz\_fcgi =============================== | | | | --- | --- | | Description: | Allows a FastCGI authorizer application to handle Apache httpd authentication and authorization | | Status: | Extension | | Module Identifier: | authnz\_fcgi\_module | | Source File: | mod\_authnz\_fcgi.c | | Compatibility: | Available in version 2.4.10 and later | ### Summary This module allows FastCGI authorizer applications to authenticate users and authorize access to resources. It supports generic FastCGI authorizers which participate in a single phase for authentication and authorization as well as Apache httpd-specific authenticators and authorizors which participate in one or both phases. FastCGI authorizers can authenticate using user id and password, such as for Basic authentication, or can authenticate using arbitrary mechanisms. Invocation modes ---------------- The invocation modes for FastCGI authorizers supported by this module are distinguished by two characteristics, *type* and auth *mechanism*. *Type* is simply `authn` for authentication, `authz` for authorization, or `authnz` for combined authentication and authorization. Auth *mechanism* refers to the Apache httpd configuration mechanisms and processing phases, and can be `AuthBasicProvider`, `Require`, or `check_user_id`. The first two of these correspond to the directives used to enable participation in the appropriate processing phase. Descriptions of each mode: *Type* `authn`, *mechanism* `AuthBasicProvider` In this mode, `FCGI_ROLE` is set to `AUTHORIZER` and `FCGI_APACHE_ROLE` is set to `AUTHENTICATOR`. The application must be defined as provider type *authn* using `[AuthnzFcgiDefineProvider](#authnzfcgidefineprovider)` and enabled with `[AuthBasicProvider](mod_auth_basic#authbasicprovider)`. When invoked, the application is expected to authenticate the client using the provided user id and password. Example application: ``` #!/usr/bin/perl use FCGI; my $request = FCGI::Request(); while ($request->Accept() >= 0) { die if $ENV{'FCGI_APACHE_ROLE'} ne "AUTHENTICATOR"; die if $ENV{'FCGI_ROLE'} ne "AUTHORIZER"; die if !$ENV{'REMOTE_PASSWD'}; die if !$ENV{'REMOTE_USER'}; print STDERR "This text is written to the web server error log.\n"; if ( ($ENV{'REMOTE_USER' } eq "foo" || $ENV{'REMOTE_USER'} eq "foo1") && $ENV{'REMOTE_PASSWD'} eq "bar" ) { print "Status: 200\n"; print "Variable-AUTHN_1: authn_01\n"; print "Variable-AUTHN_2: authn_02\n"; print "\n"; } else { print "Status: 401\n\n"; } } ``` Example configuration: ``` AuthnzFcgiDefineProvider authn FooAuthn fcgi://localhost:10102/ <Location "/protected/"> AuthType Basic AuthName "Restricted" AuthBasicProvider FooAuthn Require ... </Location> ``` *Type* `authz`, *mechanism* `Require` In this mode, `FCGI_ROLE` is set to `AUTHORIZER` and `FCGI_APACHE_ROLE` is set to `AUTHORIZER`. The application must be defined as provider type *authz* using `[AuthnzFcgiDefineProvider](#authnzfcgidefineprovider)`. When invoked, the application is expected to authorize the client using the provided user id and other request data. Example application: ``` #!/usr/bin/perl use FCGI; my $request = FCGI::Request(); while ($request->Accept() >= 0) { die if $ENV{'FCGI_APACHE_ROLE'} ne "AUTHORIZER"; die if $ENV{'FCGI_ROLE'} ne "AUTHORIZER"; die if $ENV{'REMOTE_PASSWD'}; print STDERR "This text is written to the web server error log.\n"; if ($ENV{'REMOTE_USER'} eq "foo1") { print "Status: 200\n"; print "Variable-AUTHZ_1: authz_01\n"; print "Variable-AUTHZ_2: authz_02\n"; print "\n"; } else { print "Status: 403\n\n"; } } ``` Example configuration: ``` AuthnzFcgiDefineProvider authz FooAuthz fcgi://localhost:10103/ <Location "/protected/"> AuthType ... AuthName ... AuthBasicProvider ... Require FooAuthz </Location> ``` *Type* `authnz`, *mechanism* `AuthBasicProvider` *+* `Require` In this mode, which supports the web server-agnostic FastCGI `AUTHORIZER` protocol, `FCGI_ROLE` is set to `AUTHORIZER` and `FCGI_APACHE_ROLE` is not set. The application must be defined as provider type *authnz* using `[AuthnzFcgiDefineProvider](#authnzfcgidefineprovider)`. The application is expected to handle both authentication and authorization in the same invocation using the user id, password, and other request data. The invocation occurs during the Apache httpd API authentication phase. If the application returns 200 and the same provider is invoked during the authorization phase (via `Require`), mod\_authnz\_fcgi will return success for the authorization phase without invoking the application. Example application: ``` #!/usr/bin/perl use FCGI; my $request = FCGI::Request(); while ($request->Accept() >= 0) { die if $ENV{'FCGI_APACHE_ROLE'}; die if $ENV{'FCGI_ROLE'} ne "AUTHORIZER"; die if !$ENV{'REMOTE_PASSWD'}; die if !$ENV{'REMOTE_USER'}; print STDERR "This text is written to the web server error log.\n"; if ( ($ENV{'REMOTE_USER' } eq "foo" || $ENV{'REMOTE_USER'} eq "foo1") && $ENV{'REMOTE_PASSWD'} eq "bar" && $ENV{'REQUEST_URI'} =~ m%/bar/.*%) { print "Status: 200\n"; print "Variable-AUTHNZ_1: authnz_01\n"; print "Variable-AUTHNZ_2: authnz_02\n"; print "\n"; } else { print "Status: 401\n\n"; } } ``` Example configuration: ``` AuthnzFcgiDefineProvider authnz FooAuthnz fcgi://localhost:10103/ <Location "/protected/"> AuthType Basic AuthName "Restricted" AuthBasicProvider FooAuthnz Require FooAuthnz </Location> ``` *Type* `authn`, *mechanism* `check_user_id` In this mode, `FCGI_ROLE` is set to `AUTHORIZER` and `FCGI_APACHE_ROLE` is set to `AUTHENTICATOR`. The application must be defined as provider type *authn* using `[AuthnzFcgiDefineProvider](#authnzfcgidefineprovider)`. `[AuthnzFcgiCheckAuthnProvider](#authnzfcgicheckauthnprovider)` specifies when it is called. Example application: ``` #!/usr/bin/perl use FCGI; my $request = FCGI::Request(); while ($request->Accept() >= 0) { die if $ENV{'FCGI_APACHE_ROLE'} ne "AUTHENTICATOR"; die if $ENV{'FCGI_ROLE'} ne "AUTHORIZER"; # This authorizer assumes that the RequireBasicAuth option of # AuthnzFcgiCheckAuthnProvider is On: die if !$ENV{'REMOTE_PASSWD'}; die if !$ENV{'REMOTE_USER'}; print STDERR "This text is written to the web server error log.\n"; if ( ($ENV{'REMOTE_USER' } eq "foo" || $ENV{'REMOTE_USER'} eq "foo1") && $ENV{'REMOTE_PASSWD'} eq "bar" ) { print "Status: 200\n"; print "Variable-AUTHNZ_1: authnz_01\n"; print "Variable-AUTHNZ_2: authnz_02\n"; print "\n"; } else { print "Status: 401\n\n"; # If a response body is written here, it will be returned to # the client. } } ``` Example configuration: ``` AuthnzFcgiDefineProvider authn FooAuthn fcgi://localhost:10103/ <Location "/protected/"> AuthType ... AuthName ... AuthnzFcgiCheckAuthnProvider FooAuthn \ Authoritative On \ RequireBasicAuth Off \ UserExpr "%{reqenv:REMOTE_USER}" Require ... </Location> ``` Additional examples ------------------- 1. If your application supports the separate authentication and authorization roles (`AUTHENTICATOR` and `AUTHORIZER`), define separate providers as follows, even if they map to the same application: ``` AuthnzFcgiDefineProvider authn FooAuthn fcgi://localhost:10102/ AuthnzFcgiDefineProvider authz FooAuthz fcgi://localhost:10102/ ``` Specify the authn provider on `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` and the authz provider on `[Require](mod_authz_core#require)`: ``` AuthType Basic AuthName "Restricted" AuthBasicProvider FooAuthn Require FooAuthz ``` 2. If your application supports the generic `AUTHORIZER` role (authentication and authorizer in one invocation), define a single provider as follows: ``` AuthnzFcgiDefineProvider authnz FooAuthnz fcgi://localhost:10103/ ``` Specify the authnz provider on both `AuthBasicProvider` and `Require`: ``` AuthType Basic AuthName "Restricted" AuthBasicProvider FooAuthnz Require FooAuthnz ``` Limitations ----------- The following are potential features which are not currently implemented: Apache httpd access checker The Apache httpd API *access check* phase is a separate phase from authentication and authorization. Some other FastCGI implementations implement this phase, which is denoted by the setting of `FCGI_APACHE_ROLE` to `ACCESS_CHECKER`. Local (Unix) sockets or pipes Only TCP sockets are currently supported. Support for mod\_authn\_socache mod\_authn\_socache interaction should be implemented for applications which participate in Apache httpd-style authentication. Support for digest authentication using AuthDigestProvider This is expected to be a permanent limitation as there is no authorizer flow for retrieving a hash. Application process management This is expected to be permanently out of scope for this module. Application processes must be controlled by other means. For example, `[fcgistarter](../programs/fcgistarter)` can be used to start them. AP\_AUTH\_INTERNAL\_PER\_URI All providers are currently registered as AP\_AUTH\_INTERNAL\_PER\_CONF, which means that checks are not performed again for internal subrequests with the same access control configuration as the initial request. Protocol data charset conversion If mod\_authnz\_fcgi runs in an EBCDIC compilation environment, all FastCGI protocol data is written in EBCDIC and expected to be received in EBCDIC. Multiple requests per connection Currently the connection to the FastCGI authorizer is closed after every phase of processing. For example, if the authorizer handles separate *authn* and *authz* phases then two connections will be used. URI Mapping URIs from clients can't be mapped, such as with the `ProxyPass` used with FastCGI responders. Logging ------- 1. Processing errors are logged at log level `error` and higher. 2. Messages written by the application are logged at log level `warn`. 3. General messages for debugging are logged at log level `debug`. 4. Environment variables passed to the application are logged at log level `trace2`. The value of the `REMOTE_PASSWD` variable will be obscured, but **any other sensitive data will be visible in the log**. 5. All I/O between the module and the FastCGI application, including all environment variables, will be logged in printable and hex format at log level `trace5`. **All sensitive data will be visible in the log.** `[LogLevel](core#loglevel)` can be used to configure a log level specific to mod\_authnz\_fcgi. For example: ``` LogLevel info authnz_fcgi:trace8 ``` AuthnzFcgiCheckAuthnProvider Directive -------------------------------------- | | | | --- | --- | | Description: | Enables a FastCGI application to handle the check\_authn authentication hook. | | Syntax: | ``` AuthnzFcgiCheckAuthnProvider provider-name|None option ... ``` | | Default: | `none` | | Context: | directory | | Status: | Extension | | Module: | mod\_authnz\_fcgi | This directive is used to enable a FastCGI authorizer to handle a specific processing phase of authentication or authorization. Some capabilities of FastCGI authorizers require enablement using this directive instead of `AuthBasicProvider`: * Non-Basic authentication; generally, determining the user id of the client and returning it from the authorizer; see the `UserExpr` option below * Selecting a custom response code; for a non-200 response from the authorizer, the code from the authorizer will be the status of the response * Setting the body of a non-200 response; if the authorizer provides a response body with a non-200 response, that body will be returned to the client; up to 8192 bytes of text are supported *provider-name* This is the name of a provider defined with `AuthnzFcgiDefineProvider`. `None` Specify `None` to disable a provider enabled with this directive in an outer scope, such as in a parent directory. *option* The following options are supported: Authoritative On|Off (default On) This controls whether or not other modules are allowed to run when this module has a FastCGI authorizer configured and it fails the request. DefaultUser *userid* When the authorizer returns success and `UserExpr` is configured and evaluates to an empty string (e.g., authorizer didn't return a variable), this value will be used as the user id. This is typically used when the authorizer has a concept of guest, or unauthenticated, users and guest users are mapped to some specific user id for logging and other purposes. RequireBasicAuth On|Off (default Off) This controls whether or not Basic auth is required before passing the request to the authorizer. If required, the authorizer won't be invoked without a user id and password; 401 will be returned for a request without that. UserExpr *expr* (no default) When Basic authentication isn't provided by the client and the authorizer determines the user, this expression, evaluated after calling the authorizer, determines the user. The expression follows [ap\_expr syntax](../expr) and must resolve to a string. A typical use is to reference a `Variable-*XXX*` setting returned by the authorizer using an option like `UserExpr "%{reqenv:*XXX*}"`. If this option is specified and the user id can't be retrieved using the expression after a successful authentication, the request will be rejected with a 500 error. AuthnzFcgiDefineProvider Directive ---------------------------------- | | | | --- | --- | | Description: | Defines a FastCGI application as a provider for authentication and/or authorization | | Syntax: | ``` AuthnzFcgiDefineProvider type provider-name backend-address ``` | | Default: | `none` | | Context: | server config | | Status: | Extension | | Module: | mod\_authnz\_fcgi | This directive is used to define a FastCGI application as a provider for a particular phase of authentication or authorization. *type* This must be set to *authn* for authentication, *authz* for authorization, or *authnz* for a generic FastCGI authorizer which performs both checks. *provider-name* This is used to assign a name to the provider which is used in other directives such as `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` and `[Require](mod_authz_core#require)`. *backend-address* This specifies the address of the application, in the form *fcgi://hostname:port/*. The application process(es) must be managed independently, such as with `[fcgistarter](../programs/fcgistarter)`.
programming_docs
apache_http_server Apache Core Features Apache Core Features ==================== | | | | --- | --- | | Description: | Core Apache HTTP Server features that are always available | | Status: | Core | AcceptFilter Directive ---------------------- | | | | --- | --- | | Description: | Configures optimizations for a Protocol's Listener Sockets | | Syntax: | ``` AcceptFilter protocol accept_filter ``` | | Context: | server config | | Status: | Core | | Module: | core | This directive enables operating system specific optimizations for a listening socket by the `Protocol` type. The basic premise is for the kernel to not send a socket to the server process until either data is received or an entire HTTP Request is buffered. Only [FreeBSD's Accept Filters](http://www.freebsd.org/cgi/man.cgi?query=accept_filter&sektion=9), Linux's more primitive `TCP_DEFER_ACCEPT`, and Windows' optimized AcceptEx() are currently supported. Using `none` for an argument will disable any accept filters for that protocol. This is useful for protocols that require a server send data first, such as `ftp:` or `nntp`: ``` AcceptFilter nntp none ``` The default protocol names are `https` for port 443 and `http` for all other ports. To specify that another protocol is being used with a listening port, add the protocol argument to the `[Listen](mpm_common#listen)` directive. The default values on FreeBSD are: ``` AcceptFilter http httpready AcceptFilter https dataready ``` The `httpready` accept filter buffers entire HTTP requests at the kernel level. Once an entire request is received, the kernel then sends it to the server. See the [accf\_http(9)](http://www.freebsd.org/cgi/man.cgi?query=accf_http&sektion=9) man page for more details. Since HTTPS requests are encrypted, only the [accf\_data(9)](http://www.freebsd.org/cgi/man.cgi?query=accf_data&sektion=9) filter is used. The default values on Linux are: ``` AcceptFilter http data AcceptFilter https data ``` Linux's `TCP_DEFER_ACCEPT` does not support buffering http requests. Any value besides `none` will enable `TCP_DEFER_ACCEPT` on that listener. For more details see the Linux [tcp(7)](http://man7.org/linux/man-pages/man7/tcp.7.html) man page. The default values on Windows are: ``` AcceptFilter http connect AcceptFilter https connect ``` Window's mpm\_winnt interprets the AcceptFilter to toggle the AcceptEx() API, and does not support http protocol buffering. `connect` will use the AcceptEx() API, also retrieve the network endpoint addresses, but like `none` the `connect` option does not wait for the initial data transmission. On Windows, `none` uses accept() rather than AcceptEx() and will not recycle sockets between connections. This is useful for network adapters with broken driver support, as well as some virtual network providers such as vpn drivers, or spam, virus or spyware filters. **The `data` AcceptFilter (Windows)** For versions 2.4.23 and prior, the Windows `data` accept filter waited until data had been transmitted and the initial data buffer and network endpoint addresses had been retrieved from the single AcceptEx() invocation. This implementation was subject to a denial of service attack and has been disabled. Current releases of httpd default to the `connect` filter on Windows, and will fall back to `connect` if `data` is specified. Users of prior releases are encouraged to add an explicit setting of `connect` for their AcceptFilter, as shown above. ### See also * `[Protocol](#protocol)` AcceptPathInfo Directive ------------------------ | | | | --- | --- | | Description: | Resources accept trailing pathname information | | Syntax: | ``` AcceptPathInfo On|Off|Default ``` | | Default: | ``` AcceptPathInfo Default ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | This directive controls whether requests that contain trailing pathname information that follows an actual filename (or non-existent file in an existing directory) will be accepted or rejected. The trailing pathname information can be made available to scripts in the `PATH_INFO` environment variable. For example, assume the location `/test/` points to a directory that contains only the single file `here.html`. Then requests for `/test/here.html/more` and `/test/nothere.html/more` both collect `/more` as `PATH_INFO`. The three possible arguments for the `AcceptPathInfo` directive are: `Off` A request will only be accepted if it maps to a literal path that exists. Therefore a request with trailing pathname information after the true filename such as `/test/here.html/more` in the above example will return a 404 NOT FOUND error. `On` A request will be accepted if a leading path component maps to a file that exists. The above example `/test/here.html/more` will be accepted if `/test/here.html` maps to a valid file. `Default` The treatment of requests with trailing pathname information is determined by the [handler](../handler) responsible for the request. The core handler for normal files defaults to rejecting `PATH_INFO` requests. Handlers that serve scripts, such as [cgi-script](mod_cgi) and [isapi-handler](mod_isapi), generally accept `PATH_INFO` by default. The primary purpose of the `AcceptPathInfo` directive is to allow you to override the handler's choice of accepting or rejecting `PATH_INFO`. This override is required, for example, when you use a [filter](../filter), such as [INCLUDES](mod_include), to generate content based on `PATH_INFO`. The core handler would usually reject the request, so you can use the following configuration to enable such a script: ``` <Files "mypaths.shtml"> Options +Includes SetOutputFilter INCLUDES AcceptPathInfo On </Files> ``` AccessFileName Directive ------------------------ | | | | --- | --- | | Description: | Name of the distributed configuration file | | Syntax: | ``` AccessFileName filename [filename] ... ``` | | Default: | ``` AccessFileName .htaccess ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | While processing a request, the server looks for the first existing configuration file from this list of names in every directory of the path to the document, if distributed configuration files are [enabled for that directory](#allowoverride). For example: ``` AccessFileName .acl ``` Before returning the document `/usr/local/web/index.html`, the server will read `/.acl`, `/usr/.acl`, `/usr/local/.acl` and `/usr/local/web/.acl` for directives unless they have been disabled with: ``` <Directory "/"> AllowOverride None </Directory> ``` ### See also * `[AllowOverride](#allowoverride)` * [Configuration Files](../configuring) * [.htaccess Files](../howto/htaccess) AddDefaultCharset Directive --------------------------- | | | | --- | --- | | Description: | Default charset parameter to be added when a response content-type is `text/plain` or `text/html` | | Syntax: | ``` AddDefaultCharset On|Off|charset ``` | | Default: | ``` AddDefaultCharset Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | This directive specifies a default value for the media type charset parameter (the name of a character encoding) to be added to a response if and only if the response's content-type is either `text/plain` or `text/html`. This should override any charset specified in the body of the response via a `META` element, though the exact behavior is often dependent on the user's client configuration. A setting of `AddDefaultCharset Off` disables this functionality. `AddDefaultCharset On` enables a default charset of `iso-8859-1`. Any other value is assumed to be the charset to be used, which should be one of the [IANA registered charset values](http://www.iana.org/assignments/character-sets) for use in Internet media types (MIME types). For example: ``` AddDefaultCharset utf-8 ``` `AddDefaultCharset` should only be used when all of the text resources to which it applies are known to be in that character encoding and it is too inconvenient to label their charset individually. One such example is to add the charset parameter to resources containing generated content, such as legacy CGI scripts, that might be vulnerable to cross-site scripting attacks due to user-provided data being included in the output. Note, however, that a better solution is to just fix (or delete) those scripts, since setting a default charset does not protect users that have enabled the "auto-detect character encoding" feature on their browser. ### See also * `[AddCharset](mod_mime#addcharset)` AllowEncodedSlashes Directive ----------------------------- | | | | --- | --- | | Description: | Determines whether encoded path separators in URLs are allowed to be passed through | | Syntax: | ``` AllowEncodedSlashes On|Off|NoDecode ``` | | Default: | ``` AllowEncodedSlashes Off ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | | Compatibility: | NoDecode option available in 2.3.12 and later. | The `AllowEncodedSlashes` directive allows URLs which contain encoded path separators (`%2F` for `/` and additionally `%5C` for `\` on accordant systems) to be used in the path info. With the default value, `Off`, such URLs are refused with a 404 (Not found) error. With the value `On`, such URLs are accepted, and encoded slashes are decoded like all other encoded characters. With the value `NoDecode`, such URLs are accepted, but encoded slashes are not decoded but left in their encoded state. Turning `AllowEncodedSlashes` `On` is mostly useful when used in conjunction with `PATH_INFO`. **Note** If encoded slashes are needed in path info, use of `NoDecode` is strongly recommended as a security measure. Allowing slashes to be decoded could potentially allow unsafe paths. ### See also * `[AcceptPathInfo](#acceptpathinfo)` AllowOverride Directive ----------------------- | | | | --- | --- | | Description: | Types of directives that are allowed in `.htaccess` files | | Syntax: | ``` AllowOverride All|None|directive-type [directive-type] ... ``` | | Default: | ``` AllowOverride None (2.3.9 and later), AllowOverride All (2.3.8 and earlier) ``` | | Context: | directory | | Status: | Core | | Module: | core | When the server finds an `.htaccess` file (as specified by `[AccessFileName](#accessfilename)`), it needs to know which directives declared in that file can override earlier configuration directives. **Only available in <Directory> sections** `AllowOverride` is valid only in `[<Directory>](#directory)` sections specified without regular expressions, not in `[<Location>](#location)`, `[<DirectoryMatch>](#directorymatch)` or `[<Files>](#files)` sections. When this directive is set to `None` and `[AllowOverrideList](#allowoverridelist)` is set to `None`, [.htaccess](#accessfilename) files are completely ignored. In this case, the server will not even attempt to read `.htaccess` files in the filesystem. When this directive is set to `All`, then any directive which has the .htaccess Context is allowed in `.htaccess` files. The directive-type can be one of the following groupings of directives. (See the [override class index](overrides) for an up-to-date listing of which directives are enabled by each directive-type.) [AuthConfig](overrides#override-authconfig) Allow use of the authorization directives (`[AuthDBMGroupFile](mod_authz_dbm#authdbmgroupfile)`, `[AuthDBMUserFile](mod_authn_dbm#authdbmuserfile)`, `[AuthGroupFile](mod_authz_groupfile#authgroupfile)`, `[AuthName](mod_authn_core#authname)`, `[AuthType](mod_authn_core#authtype)`, `[AuthUserFile](mod_authn_file#authuserfile)`, `[Require](mod_authz_core#require)`, *etc.*). [FileInfo](overrides#override-fileinfo) Allow use of the directives controlling document types (`[ErrorDocument](#errordocument)`, `[ForceType](#forcetype)`, `[LanguagePriority](mod_negotiation#languagepriority)`, `[SetHandler](#sethandler)`, `[SetInputFilter](#setinputfilter)`, `[SetOutputFilter](#setoutputfilter)`, and `<mod_mime>` Add\* and Remove\* directives), document meta data (`[Header](mod_headers#header)`, `[RequestHeader](mod_headers#requestheader)`, `[SetEnvIf](mod_setenvif#setenvif)`, `[SetEnvIfNoCase](mod_setenvif#setenvifnocase)`, `[BrowserMatch](mod_setenvif#browsermatch)`, `[CookieExpires](mod_usertrack#cookieexpires)`, `[CookieDomain](mod_usertrack#cookiedomain)`, `[CookieStyle](mod_usertrack#cookiestyle)`, `[CookieTracking](mod_usertrack#cookietracking)`, `[CookieName](mod_usertrack#cookiename)`), `<mod_rewrite>` directives (`[RewriteEngine](mod_rewrite#rewriteengine)`, `[RewriteOptions](mod_rewrite#rewriteoptions)`, `[RewriteBase](mod_rewrite#rewritebase)`, `[RewriteCond](mod_rewrite#rewritecond)`, `[RewriteRule](mod_rewrite#rewriterule)`), `<mod_alias>` directives (`[Redirect](mod_alias#redirect)`, `[RedirectTemp](mod_alias#redirecttemp)`, `[RedirectPermanent](mod_alias#redirectpermanent)`, `[RedirectMatch](mod_alias#redirectmatch)`), and `[Action](mod_actions#action)` from `<mod_actions>`. [Indexes](overrides#override-indexes) Allow use of the directives controlling directory indexing (`[AddDescription](mod_autoindex#adddescription)`, `[AddIcon](mod_autoindex#addicon)`, `[AddIconByEncoding](mod_autoindex#addiconbyencoding)`, `[AddIconByType](mod_autoindex#addiconbytype)`, `[DefaultIcon](mod_autoindex#defaulticon)`, `[DirectoryIndex](mod_dir#directoryindex)`, [`FancyIndexing`](mod_autoindex#indexoptions.fancyindexing), `[HeaderName](mod_autoindex#headername)`, `[IndexIgnore](mod_autoindex#indexignore)`, `[IndexOptions](mod_autoindex#indexoptions)`, `[ReadmeName](mod_autoindex#readmename)`, *etc.*). [Limit](overrides#override-limit) Allow use of the directives controlling host access (`[Allow](mod_access_compat#allow)`, `[Deny](mod_access_compat#deny)` and `[Order](mod_access_compat#order)`). Nonfatal=[Override|Unknown|All] Allow use of AllowOverride option to treat syntax errors in .htaccess as nonfatal. Instead of causing an Internal Server Error, disallowed or unrecognised directives will be ignored and a warning logged: * **Nonfatal=Override** treats directives forbidden by AllowOverride as nonfatal. * **Nonfatal=Unknown** treats unknown directives as nonfatal. This covers typos and directives implemented by a module that's not present. * **Nonfatal=All** treats both the above as nonfatal. Note that a syntax error in a valid directive will still cause an internal server error. **Security** Nonfatal errors may have security implications for .htaccess users. For example, if AllowOverride disallows AuthConfig, users' configuration designed to restrict access to a site will be disabled. [Options](overrides#override-options)[=Option,...] Allow use of the directives controlling specific directory features (`[Options](#options)` and `[XBitHack](mod_include#xbithack)`). An equal sign may be given followed by a comma-separated list, without spaces, of options that may be set using the `[Options](#options)` command. **Implicit disabling of Options** Even though the list of options that may be used in .htaccess files can be limited with this directive, as long as any `[Options](#options)` directive is allowed any other inherited option can be disabled by using the non-relative syntax. In other words, this mechanism cannot force a specific option to remain *set* while allowing any others to be set. ``` AllowOverride Options=Indexes,MultiViews ``` Example: ``` AllowOverride AuthConfig Indexes ``` In the example above, all directives that are neither in the group `AuthConfig` nor `Indexes` cause an internal server error. For security and performance reasons, do not set `AllowOverride` to anything other than `None` in your `<Directory "/">` block. Instead, find (or create) the `<Directory>` block that refers to the directory where you're actually planning to place a `.htaccess` file. ### See also * `[AccessFileName](#accessfilename)` * `[AllowOverrideList](#allowoverridelist)` * [Configuration Files](../configuring) * [.htaccess Files](../howto/htaccess) * [Override Class Index for .htaccess](overrides) AllowOverrideList Directive --------------------------- | | | | --- | --- | | Description: | Individual directives that are allowed in `.htaccess` files | | Syntax: | ``` AllowOverrideList None|directive [directive-type] ... ``` | | Default: | ``` AllowOverrideList None ``` | | Context: | directory | | Status: | Core | | Module: | core | When the server finds an `.htaccess` file (as specified by `[AccessFileName](#accessfilename)`), it needs to know which directives declared in that file can override earlier configuration directives. **Only available in <Directory> sections** `AllowOverrideList` is valid only in `[<Directory>](#directory)` sections specified without regular expressions, not in `[<Location>](#location)`, `[<DirectoryMatch>](#directorymatch)` or `[<Files>](#files)` sections. When this directive is set to `None` and `[AllowOverride](#allowoverride)` is set to `None`, then [.htaccess](#accessfilename) files are completely ignored. In this case, the server will not even attempt to read `.htaccess` files in the filesystem. Example: ``` AllowOverride None AllowOverrideList Redirect RedirectMatch ``` In the example above, only the `Redirect` and `RedirectMatch` directives are allowed. All others will cause an internal server error. Example: ``` AllowOverride AuthConfig AllowOverrideList CookieTracking CookieName ``` In the example above, `[AllowOverride](#allowoverride)` grants permission to the `AuthConfig` directive grouping and `AllowOverrideList` grants permission to only two directives from the `FileInfo` directive grouping. All others will cause an internal server error. ### See also * `[AccessFileName](#accessfilename)` * `[AllowOverride](#allowoverride)` * [Configuration Files](../configuring) * [.htaccess Files](../howto/htaccess) CGIMapExtension Directive ------------------------- | | | | --- | --- | | Description: | Technique for locating the interpreter for CGI scripts | | Syntax: | ``` CGIMapExtension cgi-path .extension ``` | | Context: | directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | | Compatibility: | NetWare only | This directive is used to control how Apache httpd finds the interpreter used to run CGI scripts. For example, setting `CGIMapExtension sys:\foo.nlm .foo` will cause all CGI script files with a `.foo` extension to be passed to the FOO interpreter. CGIPassAuth Directive --------------------- | | | | --- | --- | | Description: | Enables passing HTTP authorization headers to scripts as CGI variables | | Syntax: | ``` CGIPassAuth On|Off ``` | | Default: | ``` CGIPassAuth Off ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Core | | Module: | core | | Compatibility: | Available in Apache HTTP Server 2.4.13 and later | `CGIPassAuth` allows scripts access to HTTP authorization headers such as `Authorization`, which is required for scripts that implement HTTP Basic authentication. Normally these HTTP headers are hidden from scripts. This is to disallow scripts from seeing user ids and passwords used to access the server when HTTP Basic authentication is enabled in the web server. This directive should be used when scripts are allowed to implement HTTP Basic authentication. This directive can be used instead of the compile-time setting `SECURITY_HOLE_PASS_AUTHORIZATION` which has been available in previous versions of Apache HTTP Server. The setting is respected by any modules which use `ap_add_common_vars()`, such as `<mod_cgi>`, `<mod_cgid>`, `<mod_proxy_fcgi>`, `<mod_proxy_scgi>`, and so on. Notably, it affects modules which don't handle the request in the usual sense but still use this API; examples of this are `<mod_include>` and `<mod_ext_filter>`. Third-party modules that don't use `ap_add_common_vars()` may choose to respect the setting as well. CGIVar Directive ---------------- | | | | --- | --- | | Description: | Controls how some CGI variables are set | | Syntax: | ``` CGIVar variable rule ``` | | Context: | directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | | Compatibility: | Available in Apache HTTP Server 2.4.21 and later | This directive controls how some CGI variables are set. **REQUEST\_URI** rules: `original-uri` (default) The value is taken from the original request line, and will not reflect internal redirects or subrequests which change the requested resource. `current-uri` The value reflects the resource currently being processed, which may be different than the original request from the client due to internal redirects or subrequests. ContentDigest Directive ----------------------- | | | | --- | --- | | Description: | Enables the generation of `Content-MD5` HTTP Response headers | | Syntax: | ``` ContentDigest On|Off ``` | | Default: | ``` ContentDigest Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Core | | Module: | core | This directive enables the generation of `Content-MD5` headers as defined in RFC1864 respectively RFC2616. MD5 is an algorithm for computing a "message digest" (sometimes called "fingerprint") of arbitrary-length data, with a high degree of confidence that any alterations in the data will be reflected in alterations in the message digest. The `Content-MD5` header provides an end-to-end message integrity check (MIC) of the entity-body. A proxy or client may check this header for detecting accidental modification of the entity-body in transit. Example header: ``` Content-MD5: AuLb7Dp1rqtRtxz2m9kRpA== ``` Note that this can cause performance problems on your server since the message digest is computed on every request (the values are not cached). `Content-MD5` is only sent for documents served by the `<core>`, and not by any module. For example, SSI documents, output from CGI scripts, and byte range responses do not have this header. DefaultRuntimeDir Directive --------------------------- | | | | --- | --- | | Description: | Base directory for the server run-time files | | Syntax: | ``` DefaultRuntimeDir directory-path ``` | | Default: | ``` DefaultRuntimeDir DEFAULT_REL_RUNTIMEDIR (logs/) ``` | | Context: | server config | | Status: | Core | | Module: | core | | Compatibility: | Available in Apache 2.4.2 and later | The `DefaultRuntimeDir` directive sets the directory in which the server will create various run-time files (shared memory, locks, etc.). If set as a relative path, the full path will be relative to `ServerRoot`. **Example** ``` DefaultRuntimeDir scratch/ ``` The default location of `DefaultRuntimeDir` may be modified by changing the `DEFAULT_REL_RUNTIMEDIR` #define at build time. Note: `ServerRoot` should be specified before this directive is used. Otherwise, the default value of `ServerRoot` would be used to set the base directory. ### See also * [the security tips](../misc/security_tips#serverroot) for information on how to properly set permissions on the `ServerRoot` DefaultType Directive --------------------- | | | | --- | --- | | Description: | This directive has no effect other than to emit warnings if the value is not `none`. In prior versions, DefaultType would specify a default media type to assign to response content for which no other media type configuration could be found. | | Syntax: | ``` DefaultType media-type|none ``` | | Default: | ``` DefaultType none ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | | Compatibility: | The argument `none` is available in Apache httpd 2.2.7 and later. All other choices are DISABLED for 2.3.x and later. | This directive has been disabled. For backwards compatibility of configuration files, it may be specified with the value `none`, meaning no default media type. For example: ``` DefaultType None ``` `DefaultType None` is only available in httpd-2.2.7 and later. Use the mime.types configuration file and the `[AddType](mod_mime#addtype)` to configure media type assignments via file extensions, or the `[ForceType](#forcetype)` directive to configure the media type for specific resources. Otherwise, the server will send the response without a Content-Type header field and the recipient may attempt to guess the media type. Define Directive ---------------- | | | | --- | --- | | Description: | Define a variable | | Syntax: | ``` Define parameter-name [parameter-value] ``` | | Context: | server config, virtual host, directory | | Status: | Core | | Module: | core | In its one parameter form, `Define` is equivalent to passing the `-D` argument to `[httpd](../programs/httpd)`. It can be used to toggle the use of `[<IfDefine>](#ifdefine)` sections without needing to alter `-D` arguments in any startup scripts. In addition to that, if the second parameter is given, a config variable is set to this value. The variable can be used in the configuration using the `${VAR}` syntax. The variable is always globally defined and not limited to the scope of the surrounding config section. ``` <IfDefine TEST> Define servername test.example.com </IfDefine> <IfDefine !TEST> Define servername www.example.com Define SSL </IfDefine> DocumentRoot "/var/www/${servername}/htdocs" ``` Variable names may not contain colon ":" characters, to avoid clashes with `[RewriteMap](mod_rewrite#rewritemap)`'s syntax. **Virtual Host scope and pitfalls** While this directive is supported in virtual host context, the changes it makes are visible to any later configuration directives, beyond any enclosing virtual host. ### See also * `[UnDefine](#undefine)` * `[IfDefine](#ifdefine)` <Directory> Directive --------------------- | | | | --- | --- | | Description: | Enclose a group of directives that apply only to the named file-system directory, sub-directories, and their contents. | | Syntax: | ``` <Directory directory-path> ... </Directory> ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | `<Directory>` and `</Directory>` are used to enclose a group of directives that will apply only to the named directory, sub-directories of that directory, and the files within the respective directories. Any directive that is allowed in a directory context may be used. Directory-path is either the full path to a directory, or a wild-card string using Unix shell-style matching. In a wild-card string, `?` matches any single character, and `*` matches any sequences of characters. You may also use `[]` character ranges. None of the wildcards match a `/' character, so `<Directory "/*/public_html">` will not match `/home/user/public_html`, but `<Directory "/home/*/public_html">` will match. Example: ``` <Directory "/usr/local/httpd/htdocs"> Options Indexes FollowSymLinks </Directory> ``` Directory paths *may* be quoted, if you like, however, it *must* be quoted if the path contains spaces. This is because a space would otherwise indicate the end of an argument. Be careful with the directory-path arguments: They have to literally match the filesystem path which Apache httpd uses to access the files. Directives applied to a particular `<Directory>` will not apply to files accessed from that same directory via a different path, such as via different symbolic links. [Regular expressions](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") can also be used, with the addition of the `~` character. For example: ``` <Directory ~ "^/www/[0-9]{3}"> </Directory> ``` would match directories in `/www/` that consisted of three numbers. If multiple (non-regular expression) `<Directory>` sections match the directory (or one of its parents) containing a document, then the directives are applied in the order of shortest match first, interspersed with the directives from the [.htaccess](#accessfilename) files. For example, with ``` <Directory "/"> AllowOverride None </Directory> <Directory "/home"> AllowOverride FileInfo </Directory> ``` for access to the document `/home/web/dir/doc.html` the steps are: * Apply directive `AllowOverride None` (disabling `.htaccess` files). * Apply directive `AllowOverride FileInfo` (for directory `/home`). * Apply any `FileInfo` directives in `/home/.htaccess`, `/home/web/.htaccess` and `/home/web/dir/.htaccess` in that order. Regular expressions are not considered until after all of the normal sections have been applied. Then all of the regular expressions are tested in the order they appeared in the configuration file. For example, with ``` <Directory ~ "abc$"> # ... directives here ... </Directory> ``` the regular expression section won't be considered until after all normal `<Directory>`s and `.htaccess` files have been applied. Then the regular expression will match on `/home/abc/public_html/abc` and the corresponding `<Directory>` will be applied. **Note that the default access for `<Directory "/">` is to permit all access. This means that Apache httpd will serve any file mapped from an URL. It is recommended that you change this with a block such as** ``` <Directory "/"> Require all denied </Directory> ``` **and then override this for directories you *want* accessible. See the [Security Tips](../misc/security_tips) page for more details.** The directory sections occur in the `httpd.conf` file. `<Directory>` directives cannot nest, and cannot appear in a `[<Limit>](#limit)` or `[<LimitExcept>](#limitexcept)` section. ### See also * [How <Directory>, <Location> and <Files> sections work](../sections) for an explanation of how these different sections are combined when a request is received <DirectoryMatch> Directive -------------------------- | | | | --- | --- | | Description: | Enclose directives that apply to the contents of file-system directories matching a regular expression. | | Syntax: | ``` <DirectoryMatch regex> ... </DirectoryMatch> ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | `<DirectoryMatch>` and `</DirectoryMatch>` are used to enclose a group of directives which will apply only to the named directory (and the files within), the same as `[<Directory>](#directory)`. However, it takes as an argument a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"). For example: ``` <DirectoryMatch "^/www/(.+/)?[0-9]{3}/"> # ... </DirectoryMatch> ``` matches directories in `/www/` (or any subdirectory thereof) that consist of three numbers. **Compatibility** Prior to 2.3.9, this directive implicitly applied to sub-directories (like `[<Directory>](#directory)`) and could not match the end of line symbol ($). In 2.3.9 and later, only directories that match the expression are affected by the enclosed directives. **Trailing Slash** This directive applies to requests for directories that may or may not end in a trailing slash, so expressions that are anchored to the end of line ($) must be written with care. From 2.4.8 onwards, named groups and backreferences are captured and written to the environment with the corresponding name prefixed with "MATCH\_" and in upper case. This allows elements of paths to be referenced from within [expressions](../expr) and modules like `<mod_rewrite>`. In order to prevent confusion, numbered (unnamed) backreferences are ignored. Use named groups instead. ``` <DirectoryMatch "^/var/www/combined/(?<sitename>[^/]+)"> Require ldap-group cn=%{env:MATCH_SITENAME},ou=combined,o=Example </DirectoryMatch> ``` ### See also * `[<Directory>](#directory)` for a description of how regular expressions are mixed in with normal `<Directory>`s * [How <Directory>, <Location> and <Files> sections work](../sections) for an explanation of how these different sections are combined when a request is received DocumentRoot Directive ---------------------- | | | | --- | --- | | Description: | Directory that forms the main document tree visible from the web | | Syntax: | ``` DocumentRoot directory-path ``` | | Default: | ``` DocumentRoot "/usr/local/apache/htdocs" ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | This directive sets the directory from which `[httpd](../programs/httpd)` will serve files. Unless matched by a directive like `[Alias](mod_alias#alias)`, the server appends the path from the requested URL to the document root to make the path to the document. Example: ``` DocumentRoot "/usr/web" ``` then an access to `http://my.example.com/index.html` refers to `/usr/web/index.html`. If the directory-path is not absolute then it is assumed to be relative to the `[ServerRoot](#serverroot)`. The `DocumentRoot` should be specified without a trailing slash. ### See also * [Mapping URLs to Filesystem Locations](../urlmapping#documentroot) <Else> Directive ---------------- | | | | --- | --- | | Description: | Contains directives that apply only if the condition of a previous `[<If>](#if)` or `[<ElseIf>](#elseif)` section is not satisfied by a request at runtime | | Syntax: | ``` <Else> ... </Else> ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | | Compatibility: | Nested conditions are evaluated in 2.4.26 and later | The `<Else>` applies the enclosed directives if and only if the most recent `<If>` or `<ElseIf>` section in the same scope has not been applied. For example: In ``` <If "-z req('Host')"> # ... </If> <Else> # ... </Else> ``` The `<If>` would match HTTP/1.0 requests without a Host: header and the `<Else>` would match requests with a Host: header. ### See also * `[<If>](#if)` * `[<ElseIf>](#elseif)` * [How <Directory>, <Location>, <Files> sections work](../sections) for an explanation of how these different sections are combined when a request is received. `<If>`, `<ElseIf>`, and `<Else>` are applied last. <ElseIf> Directive ------------------ | | | | --- | --- | | Description: | Contains directives that apply only if a condition is satisfied by a request at runtime while the condition of a previous `[<If>](#if)` or `<ElseIf>` section is not satisfied | | Syntax: | ``` <ElseIf expression> ... </ElseIf> ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | | Compatibility: | Nested conditions are evaluated in 2.4.26 and later | The `<ElseIf>` applies the enclosed directives if and only if both the given condition evaluates to true and the most recent `<If>` or `<ElseIf>` section in the same scope has not been applied. For example: In ``` <If "-R '10.1.0.0/16'"> #... </If> <ElseIf "-R '10.0.0.0/8'"> #... </ElseIf> <Else> #... </Else> ``` The `<ElseIf>` would match if the remote address of a request belongs to the subnet 10.0.0.0/8 but not to the subnet 10.1.0.0/16. ### See also * [Expressions in Apache HTTP Server](../expr), for a complete reference and more examples. * `[<If>](#if)` * `[<Else>](#else)` * [How <Directory>, <Location>, <Files> sections work](../sections) for an explanation of how these different sections are combined when a request is received. `<If>`, `<ElseIf>`, and `<Else>` are applied last. EnableMMAP Directive -------------------- | | | | --- | --- | | Description: | Use memory-mapping to read files during delivery | | Syntax: | ``` EnableMMAP On|Off ``` | | Default: | ``` EnableMMAP On ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | This directive controls whether the `[httpd](../programs/httpd)` may use memory-mapping if it needs to read the contents of a file during delivery. By default, when the handling of a request requires access to the data within a file -- for example, when delivering a server-parsed file using `<mod_include>` -- Apache httpd memory-maps the file if the OS supports it. This memory-mapping sometimes yields a performance improvement. But in some environments, it is better to disable the memory-mapping to prevent operational problems: * On some multiprocessor systems, memory-mapping can reduce the performance of the `[httpd](../programs/httpd)`. * Deleting or truncating a file while `[httpd](../programs/httpd)` has it memory-mapped can cause `[httpd](../programs/httpd)` to crash with a segmentation fault. For server configurations that are vulnerable to these problems, you should disable memory-mapping of delivered files by specifying: ``` EnableMMAP Off ``` For NFS mounted files, this feature may be disabled explicitly for the offending files by specifying: ``` <Directory "/path-to-nfs-files"> EnableMMAP Off </Directory> ``` EnableSendfile Directive ------------------------ | | | | --- | --- | | Description: | Use the kernel sendfile support to deliver files to the client | | Syntax: | ``` EnableSendfile On|Off ``` | | Default: | ``` EnableSendfile Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | | Compatibility: | Default changed to Off in version 2.3.9. | This directive controls whether `[httpd](../programs/httpd)` may use the sendfile support from the kernel to transmit file contents to the client. By default, when the handling of a request requires no access to the data within a file -- for example, when delivering a static file -- Apache httpd uses sendfile to deliver the file contents without ever reading the file if the OS supports it. This sendfile mechanism avoids separate read and send operations, and buffer allocations. But on some platforms or within some filesystems, it is better to disable this feature to avoid operational problems: * Some platforms may have broken sendfile support that the build system did not detect, especially if the binaries were built on another box and moved to such a machine with broken sendfile support. * On Linux the use of sendfile triggers TCP-checksum offloading bugs on certain networking cards when using IPv6. * On Linux on Itanium, `sendfile` may be unable to handle files over 2GB in size. * With a network-mounted `[DocumentRoot](#documentroot)` (e.g., NFS, SMB, CIFS, FUSE), the kernel may be unable to serve the network file through its own cache. For server configurations that are not vulnerable to these problems, you may enable this feature by specifying: ``` EnableSendfile On ``` For network mounted files, this feature may be disabled explicitly for the offending files by specifying: ``` <Directory "/path-to-nfs-files"> EnableSendfile Off </Directory> ``` Please note that the per-directory and .htaccess configuration of `EnableSendfile` is not supported by `<mod_cache_disk>`. Only global definition of `EnableSendfile` is taken into account by the module. Error Directive --------------- | | | | --- | --- | | Description: | Abort configuration parsing with a custom error message | | Syntax: | ``` Error message ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Core | | Module: | core | | Compatibility: | 2.3.9 and later | If an error can be detected within the configuration, this directive can be used to generate a custom error message, and halt configuration parsing. The typical use is for reporting required modules which are missing from the configuration. ``` # Example # ensure that mod_include is loaded <IfModule !include_module> Error "mod_include is required by mod_foo. Load it with LoadModule." </IfModule> # ensure that exactly one of SSL,NOSSL is defined <IfDefine SSL> <IfDefine NOSSL> Error "Both SSL and NOSSL are defined. Define only one of them." </IfDefine> </IfDefine> <IfDefine !SSL> <IfDefine !NOSSL> Error "Either SSL or NOSSL must be defined." </IfDefine> </IfDefine> ``` ErrorDocument Directive ----------------------- | | | | --- | --- | | Description: | What the server will return to the client in case of an error | | Syntax: | ``` ErrorDocument error-code document ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | In the event of a problem or error, Apache httpd can be configured to do one of four things, 1. output a simple hardcoded error message 2. output a customized message 3. internally redirect to a local URL-path to handle the problem/error 4. redirect to an external URL to handle the problem/error The first option is the default, while options 2-4 are configured using the `ErrorDocument` directive, which is followed by the HTTP response code and a URL or a message. Apache httpd will sometimes offer additional information regarding the problem/error. From 2.4.13, [expression syntax](../expr) can be used inside the directive to produce dynamic strings and URLs. URLs can begin with a slash (/) for local web-paths (relative to the `[DocumentRoot](#documentroot)`), or be a full URL which the client can resolve. Alternatively, a message can be provided to be displayed by the browser. Note that deciding whether the parameter is an URL, a path or a message is performed before any expression is parsed. Examples: ``` ErrorDocument 500 http://example.com/cgi-bin/server-error.cgi ErrorDocument 404 /errors/bad_urls.php ErrorDocument 401 /subscription_info.html ErrorDocument 403 "Sorry, can't allow you access today" ErrorDocument 403 Forbidden! ErrorDocument 403 /errors/forbidden.py?referrer=%{escape:%{HTTP_REFERER}} ``` Additionally, the special value `default` can be used to specify Apache httpd's simple hardcoded message. While not required under normal circumstances, `default` will restore Apache httpd's simple hardcoded message for configurations that would otherwise inherit an existing `ErrorDocument`. ``` ErrorDocument 404 /cgi-bin/bad_urls.pl <Directory "/web/docs"> ErrorDocument 404 default </Directory> ``` Note that when you specify an `ErrorDocument` that points to a remote URL (ie. anything with a method such as `http` in front of it), Apache HTTP Server will send a redirect to the client to tell it where to find the document, even if the document ends up being on the same server. This has several implications, the most important being that the client will not receive the original error status code, but instead will receive a redirect status code. This in turn can confuse web robots and other clients which try to determine if a URL is valid using the status code. In addition, if you use a remote URL in an `ErrorDocument 401`, the client will not know to prompt the user for a password since it will not receive the 401 status code. Therefore, **if you use an `ErrorDocument 401` directive, then it must refer to a local document.** Microsoft Internet Explorer (MSIE) will by default ignore server-generated error messages when they are "too small" and substitute its own "friendly" error messages. The size threshold varies depending on the type of error, but in general, if you make your error document greater than 512 bytes, then MSIE will show the server-generated error rather than masking it. More information is available in Microsoft Knowledge Base article [Q294807](http://support.microsoft.com/default.aspx?scid=kb;en-us;Q294807). Although most error messages can be overridden, there are certain circumstances where the internal messages are used regardless of the setting of `[ErrorDocument](#errordocument)`. In particular, if a malformed request is detected, normal request processing will be immediately halted and the internal error message returned. This is necessary to guard against security problems caused by bad requests. If you are using mod\_proxy, you may wish to enable `[ProxyErrorOverride](mod_proxy#proxyerroroverride)` so that you can provide custom error messages on behalf of your Origin servers. If you don't enable ProxyErrorOverride, Apache httpd will not generate custom error documents for proxied content. ### See also * [documentation of customizable responses](../custom-error) ErrorLog Directive ------------------ | | | | --- | --- | | Description: | Location where the server will log errors | | Syntax: | ``` ErrorLog file-path|syslog[:[facility][:tag]] ``` | | Default: | ``` ErrorLog logs/error_log (Unix) ErrorLog logs/error.log (Windows and OS/2) ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | The `ErrorLog` directive sets the name of the file to which the server will log any errors it encounters. If the file-path is not absolute then it is assumed to be relative to the `[ServerRoot](#serverroot)`. ``` ErrorLog "/var/log/httpd/error_log" ``` If the file-path begins with a pipe character "`|`" then it is assumed to be a command to spawn to handle the error log. ``` ErrorLog "|/usr/local/bin/httpd_errors" ``` See the notes on [piped logs](../logs#piped) for more information. Using `syslog` instead of a filename enables logging via syslogd(8) if the system supports it. The default is to use syslog facility `local7`, but you can override this by using the `syslog:facility` syntax where facility can be one of the names usually documented in syslog(1). The facility is effectively global, and if it is changed in individual virtual hosts, the final facility specified affects the entire server. Same rules apply for the syslog tag, which by default uses the Apache binary name, `httpd` in most cases. You can also override this by using the `syslog::tag` syntax. ``` ErrorLog syslog:user ErrorLog syslog:user:httpd.srv1 ErrorLog syslog::httpd.srv2 ``` SECURITY: See the [security tips](../misc/security_tips#serverroot) document for details on why your security could be compromised if the directory where log files are stored is writable by anyone other than the user that starts the server. **Note** When entering a file path on non-Unix platforms, care should be taken to make sure that only forward slashes are used even though the platform may allow the use of back slashes. In general it is a good idea to always use forward slashes throughout the configuration files. ### See also * `[LogLevel](#loglevel)` * [Apache HTTP Server Log Files](../logs) ErrorLogFormat Directive ------------------------ | | | | --- | --- | | Description: | Format specification for error log entries | | Syntax: | ``` ErrorLogFormat [connection|request] format ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | `ErrorLogFormat` allows to specify what supplementary information is logged in the error log in addition to the actual log message. ``` #Simple example ErrorLogFormat "[%t] [%l] [pid %P] %F: %E: [client %a] %M" ``` Specifying `connection` or `request` as first parameter allows to specify additional formats, causing additional information to be logged when the first message is logged for a specific connection or request, respectively. This additional information is only logged once per connection/request. If a connection or request is processed without causing any log message, the additional information is not logged either. It can happen that some format string items do not produce output. For example, the Referer header is only present if the log message is associated to a request and the log message happens at a time when the Referer header has already been read from the client. If no output is produced, the default behavior is to delete everything from the preceding space character to the next space character. This means the log line is implicitly divided into fields on non-whitespace to whitespace transitions. If a format string item does not produce output, the whole field is omitted. For example, if the remote address `%a` in the log format `[%t] [%l] [%a] %M` is not available, the surrounding brackets are not logged either. Space characters can be escaped with a backslash to prevent them from delimiting a field. The combination '% ' (percent space) is a zero-width field delimiter that does not produce any output. The above behavior can be changed by adding modifiers to the format string item. A `-` (minus) modifier causes a minus to be logged if the respective item does not produce any output. In once-per-connection/request formats, it is also possible to use the `+` (plus) modifier. If an item with the plus modifier does not produce any output, the whole line is omitted. A number as modifier can be used to assign a log severity level to a format item. The item will only be logged if the severity of the log message is not higher than the specified log severity level. The number can range from 1 (alert) over 4 (warn) and 7 (debug) to 15 (trace8). For example, here's what would happen if you added modifiers to the `%{Referer}i` token, which logs the `Referer` request header. | Modified Token | Meaning | | --- | --- | | `%-{Referer}i` | Logs a `-` if `Referer` is not set. | | `%+{Referer}i` | Omits the entire line if `Referer` is not set. | | `%4{Referer}i` | Logs the `Referer` only if the log message severity is higher than 4. | Some format string items accept additional parameters in braces. | Format String | Description | | --- | --- | | `%%` | The percent sign | | `%a` | Client IP address and port of the request | | `%{c}a` | Underlying peer IP address and port of the connection (see the `<mod_remoteip>` module) | | `%A` | Local IP-address and port | | `%{name}e` | Request environment variable *name* | | `%E` | APR/OS error status code and string | | `%F` | Source file name and line number of the log call | | `%{name}i` | Request header *name* | | `%k` | Number of keep-alive requests on this connection | | `%l` | Loglevel of the message | | `%L` | Log ID of the request | | `%{c}L` | Log ID of the connection | | `%{C}L` | Log ID of the connection if used in connection scope, empty otherwise | | `%m` | Name of the module logging the message | | `%M` | The actual log message | | `%{name}n` | Request note *name* | | `%P` | Process ID of current process | | `%T` | Thread ID of current thread | | `%{g}T` | System unique thread ID of current thread (the same ID as displayed by e.g. `top`; currently Linux only) | | `%t` | The current time | | `%{u}t` | The current time including micro-seconds | | `%{cu}t` | The current time in compact ISO 8601 format, including micro-seconds | | `%v` | The canonical `[ServerName](#servername)` of the current server. | | `%V` | The server name of the server serving the request according to the `[UseCanonicalName](#usecanonicalname)` setting. | | `\` (backslash space) | Non-field delimiting space | | `%` (percent space) | Field delimiter (no output) | The log ID format `%L` produces a unique id for a connection or request. This can be used to correlate which log lines belong to the same connection or request, which request happens on which connection. A `%L` format string is also available in `<mod_log_config>` to allow to correlate access log entries with error log lines. If `<mod_unique_id>` is loaded, its unique id will be used as log ID for requests. ``` #Example (default format for threaded MPMs) ErrorLogFormat "[%{u}t] [%-m:%l] [pid %P:tid %T] %7F: %E: [client\ %a] %M% ,\ referer\ %{Referer}i" ``` This would result in error messages such as: ``` [Thu May 12 08:28:57.652118 2011] [core:error] [pid 8777:tid 4326490112] [client ::1:58619] File does not exist: /usr/local/apache2/htdocs/favicon.ico ``` Notice that, as discussed above, some fields are omitted entirely because they are not defined. ``` #Example (similar to the 2.2.x format) ErrorLogFormat "[%t] [%l] %7F: %E: [client\ %a] %M% ,\ referer\ %{Referer}i" ``` ``` #Advanced example with request/connection log IDs ErrorLogFormat "[%{uc}t] [%-m:%-l] [R:%L] [C:%{C}L] %7F: %E: %M" ErrorLogFormat request "[%{uc}t] [R:%L] Request %k on C:%{c}L pid:%P tid:%T" ErrorLogFormat request "[%{uc}t] [R:%L] UA:'%+{User-Agent}i'" ErrorLogFormat request "[%{uc}t] [R:%L] Referer:'%+{Referer}i'" ErrorLogFormat connection "[%{uc}t] [C:%{c}L] local\ %a remote\ %A" ``` ### See also * `[ErrorLog](#errorlog)` * `[LogLevel](#loglevel)` * [Apache HTTP Server Log Files](../logs) ExtendedStatus Directive ------------------------ | | | | --- | --- | | Description: | Keep track of extended status information for each request | | Syntax: | ``` ExtendedStatus On|Off ``` | | Default: | ``` ExtendedStatus Off[*] ``` | | Context: | server config | | Status: | Core | | Module: | core | This option tracks additional data per worker about the currently executing request and creates a utilization summary. You can see these variables during runtime by configuring `<mod_status>`. Note that other modules may rely on this scoreboard. This setting applies to the entire server and cannot be enabled or disabled on a virtualhost-by-virtualhost basis. The collection of extended status information can slow down the server. Also note that this setting cannot be changed during a graceful restart. Note that loading `<mod_status>` will change the default behavior to ExtendedStatus On, while other third party modules may do the same. Such modules rely on collecting detailed information about the state of all workers. The default is changed by `<mod_status>` beginning with version 2.3.6. The previous default was always Off. FileETag Directive ------------------ | | | | --- | --- | | Description: | File attributes used to create the ETag HTTP response header for static files | | Syntax: | ``` FileETag component ... ``` | | Default: | ``` FileETag MTime Size ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | | Compatibility: | The default used to be "INode MTime Size" in 2.3.14 and earlier. | The `FileETag` directive configures the file attributes that are used to create the `ETag` (entity tag) response header field when the document is based on a static file. (The `ETag` value is used in cache management to save network bandwidth.) The `FileETag` directive allows you to choose which of these -- if any -- should be used. The recognized keywords are: **INode** The file's i-node number will be included in the calculation **MTime** The date and time the file was last modified will be included **Size** The number of bytes in the file will be included **All** All available fields will be used. This is equivalent to: ``` FileETag INode MTime Size ``` **Digest** If a document is file-based, the `ETag` field will be calculated by taking the digest over the file. **None** If a document is file-based, no `ETag` field will be included in the response The `INode`, `MTime`, `Size` and `Digest` keywords may be prefixed with either `+` or `-`, which allow changes to be made to the default setting inherited from a broader scope. Any keyword appearing without such a prefix immediately and completely cancels the inherited setting. If a directory's configuration includes `FileETag INode MTime Size`, and a subdirectory's includes `FileETag -INode`, the setting for that subdirectory (which will be inherited by any sub-subdirectories that don't override it) will be equivalent to `FileETag MTime Size`. **Server Side Includes** An ETag is not generated for responses parsed by `<mod_include>` since the response entity can change without a change of the INode, MTime, Size or Digest of the static file with embedded SSI directives. <Files> Directive ----------------- | | | | --- | --- | | Description: | Contains directives that apply to matched filenames | | Syntax: | ``` <Files filename> ... </Files> ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | The `<Files>` directive limits the scope of the enclosed directives by filename. It is comparable to the `[<Directory>](#directory)` and `[<Location>](#location)` directives. It should be matched with a `</Files>` directive. The directives given within this section will be applied to any object with a basename (last component of filename) matching the specified filename. `<Files>` sections are processed in the order they appear in the configuration file, after the `[<Directory>](#directory)` sections and `.htaccess` files are read, but before `[<Location>](#location)` sections. Note that `<Files>` can be nested inside `[<Directory>](#directory)` sections to restrict the portion of the filesystem they apply to. The filename argument should include a filename, or a wild-card string, where `?` matches any single character, and `*` matches any sequences of characters. ``` <Files "cat.html"> # Insert stuff that applies to cat.html here </Files> <Files "?at.*"> # This would apply to cat.html, bat.html, hat.php and so on. </Files> ``` [Regular expressions](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") can also be used, with the addition of the `~` character. For example: ``` <Files ~ "\.(gif|jpe?g|png)$"> #... </Files> ``` would match most common Internet graphics formats. `[<FilesMatch>](#filesmatch)` is preferred, however. Note that unlike `[<Directory>](#directory)` and `[<Location>](#location)` sections, `<Files>` sections can be used inside `.htaccess` files. This allows users to control access to their own files, at a file-by-file level. ### See also * [How <Directory>, <Location> and <Files> sections work](../sections) for an explanation of how these different sections are combined when a request is received <FilesMatch> Directive ---------------------- | | | | --- | --- | | Description: | Contains directives that apply to regular-expression matched filenames | | Syntax: | ``` <FilesMatch regex> ... </FilesMatch> ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | The `<FilesMatch>` directive limits the scope of the enclosed directives by filename, just as the `[<Files>](#files)` directive does. However, it accepts a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"). For example: ``` <FilesMatch ".+\.(gif|jpe?g|png)$"> # ... </FilesMatch> ``` would match most common Internet graphics formats. The `.+` at the start of the regex ensures that files named `.png`, or `.gif`, for example, are not matched. From 2.4.8 onwards, named groups and backreferences are captured and written to the environment with the corresponding name prefixed with "MATCH\_" and in upper case. This allows elements of files to be referenced from within [expressions](../expr) and modules like `<mod_rewrite>`. In order to prevent confusion, numbered (unnamed) backreferences are ignored. Use named groups instead. ``` <FilesMatch "^(?<sitename>[^/]+)"> Require ldap-group cn=%{env:MATCH_SITENAME},ou=combined,o=Example </FilesMatch> ``` ### See also * [How <Directory>, <Location> and <Files> sections work](../sections) for an explanation of how these different sections are combined when a request is received FlushMaxPipelined Directive --------------------------- | | | | --- | --- | | Description: | Maximum number of pipelined responses above which they are flushed to the network | | Syntax: | ``` FlushMaxPipelined number ``` | | Default: | ``` FlushMaxPipelined 5 ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | | Compatibility: | 2.4.47 and later | This directive allows to configure the maximum number of pipelined responses, which remain pending so long as pipelined request are received. When the limit is reached, reponses are forcibly flushed to the network in blocking mode, until passing under the limit again. `FlushMaxPipelined` helps constraining memory usage. When set to 0 pipelining is disabled, when set to -1 there is no limit (`FlushMaxThreshold` still applies). FlushMaxThreshold Directive --------------------------- | | | | --- | --- | | Description: | Threshold above which pending data are flushed to the network | | Syntax: | `FlushMaxThresholdnumber-of-bytes` | | Default: | ``` FlushMaxThreshold 65536 ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | | Compatibility: | 2.4.47 and later | This directive allows to configure the threshold for pending output data (in bytes). When the limit is reached, data are forcibly flushed to the network in blocking mode, until passing under the limit again. `FlushMaxThreshold` helps constraining memory usage. When set to 0 or a too small value there are actually no pending data, but for threaded MPMs there can be more threads busy waiting for the network thus less ones available to handle the other simultaneous connections. ForceType Directive ------------------- | | | | --- | --- | | Description: | Forces all matching files to be served with the specified media type in the HTTP Content-Type header field | | Syntax: | ``` ForceType media-type|None ``` | | Context: | directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | When placed into an `.htaccess` file or a `[<Directory>](#directory)`, or `[<Location>](#location)` or `[<Files>](#files)` section, this directive forces all matching files to be served with the content type identification given by media-type. For example, if you had a directory full of GIF files, but did not want to label them all with `.gif`, you might want to use: ``` ForceType image/gif ``` Note that this directive overrides other indirect media type associations defined in mime.types or via the `[AddType](mod_mime#addtype)`. You can also override more general `ForceType` settings by using the value of `None`: ``` # force all files to be image/gif: <Location "/images"> ForceType image/gif </Location> # but normal mime-type associations here: <Location "/images/mixed"> ForceType None </Location> ``` This directive primarily overrides the content types generated for static files served out of the filesystem. For resources other than static files, where the generator of the response typically specifies a Content-Type, this directive has no effect. **Note** When explicit directives such as `[SetHandler](#sethandler)` or `[AddHandler](mod_mime#addhandler)` do not apply to the current request, the internal handler name normally set by those directives is set to match the content type specified by this directive. This is a historical behavior that some third-party modules (such as mod\_php) may use "magic" content types used only to signal the module to take responsibility for the matching request. Configurations that rely on such "magic" types should be avoided by the use of `[SetHandler](#sethandler)` or `[AddHandler](mod_mime#addhandler)`. GprofDir Directive ------------------ | | | | --- | --- | | Description: | Directory to write gmon.out profiling data to. | | Syntax: | ``` GprofDir /tmp/gprof/|/tmp/gprof/% ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | When the server has been compiled with gprof profiling support, `GprofDir` causes `gmon.out` files to be written to the specified directory when the process exits. If the argument ends with a percent symbol ('%'), subdirectories are created for each process id. This directive currently only works with the `<prefork>` MPM. HostnameLookups Directive ------------------------- | | | | --- | --- | | Description: | Enables DNS lookups on client IP addresses | | Syntax: | ``` HostnameLookups On|Off|Double ``` | | Default: | ``` HostnameLookups Off ``` | | Context: | server config, virtual host, directory | | Status: | Core | | Module: | core | This directive enables DNS lookups so that host names can be logged (and passed to CGIs/SSIs in `REMOTE_HOST`). The value `Double` refers to doing double-reverse DNS lookup. That is, after a reverse lookup is performed, a forward lookup is then performed on that result. At least one of the IP addresses in the forward lookup must match the original address. (In "tcpwrappers" terminology this is called `PARANOID`.) Regardless of the setting, when `<mod_authz_host>` is used for controlling access by hostname, a double reverse lookup will be performed. This is necessary for security. Note that the result of this double-reverse isn't generally available unless you set `HostnameLookups Double`. For example, if only `HostnameLookups On` and a request is made to an object that is protected by hostname restrictions, regardless of whether the double-reverse fails or not, CGIs will still be passed the single-reverse result in `REMOTE_HOST`. The default is `Off` in order to save the network traffic for those sites that don't truly need the reverse lookups done. It is also better for the end users because they don't have to suffer the extra latency that a lookup entails. Heavily loaded sites should leave this directive `Off`, since DNS lookups can take considerable amounts of time. The utility `[logresolve](../programs/logresolve)`, compiled by default to the `bin` subdirectory of your installation directory, can be used to look up host names from logged IP addresses offline. Finally, if you have [hostname-based Require directives](mod_authz_host#reqhost), a hostname lookup will be performed regardless of the setting of `HostnameLookups`. HttpProtocolOptions Directive ----------------------------- | | | | --- | --- | | Description: | Modify restrictions on HTTP Request Messages | | Syntax: | ``` HttpProtocolOptions [Strict|Unsafe] [RegisteredMethods|LenientMethods] [Allow0.9|Require1.0] ``` | | Default: | ``` HttpProtocolOptions Strict LenientMethods Allow0.9 ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | | Compatibility: | 2.2.32 or 2.4.24 and later | This directive changes the rules applied to the HTTP Request Line ([RFC 7230 §3.1.1](https://tools.ietf.org/html/rfc7230#section-3.1.1)) and the HTTP Request Header Fields ([RFC 7230 §3.2](https://tools.ietf.org/html/rfc7230#section-3.2)), which are now applied by default or using the `Strict` option. Due to legacy modules, applications or custom user-agents which must be deprecated the `Unsafe` option has been added to revert to the legacy behaviors. These rules are applied prior to request processing, so must be configured at the global or default (first) matching virtual host section, by IP/port interface (and not by name) to be honored. The directive accepts three parameters from the following list of choices, applying the default to the ones not specified: Strict|Unsafe Prior to the introduction of this directive, the Apache HTTP Server request message parsers were tolerant of a number of forms of input which did not conform to the protocol. [RFC 7230 §9.4 Request Splitting](https://tools.ietf.org/html/rfc7230#section-9.4) and [§9.5 Response Smuggling](https://tools.ietf.org/html/rfc7230#section-9.5) call out only two of the potential risks of accepting non-conformant request messages, while [RFC 7230 §3.5](https://tools.ietf.org/html/rfc7230#section-3.5) "Message Parsing Robustness" identify the risks of accepting obscure whitespace and request message formatting. As of the introduction of this directive, all grammar rules of the specification are enforced in the default `Strict` operating mode, and the strict whitespace suggested by section 3.5 is enforced and cannot be relaxed. **Security risks of Unsafe** Users are strongly cautioned against toggling the `Unsafe` mode of operation, particularly on outward-facing, publicly accessible server deployments. If an interface is required for faulty monitoring or other custom service consumers running on an intranet, users should toggle the Unsafe option only on a specific virtual host configured to service their internal private network. ### Example of a request leading to HTTP 400 with Strict mode ``` # Missing CRLF GET / HTTP/1.0\n\n ``` **Command line tools and CRLF** Some tools need to be forced to use CRLF, otherwise httpd will return a HTTP 400 response like described in the above use case. For example, the **OpenSSL s\_client needs the -crlf parameter to work properly**. The `[DumpIOInput](mod_dumpio#dumpioinput)` directive can help while reviewing the HTTP request to identify issues like the absence of CRLF. RegisteredMethods|LenientMethods [RFC 7231 §4.1](https://tools.ietf.org/html/rfc7231#section-4.1) "Request Methods" "Overview" requires that origin servers shall respond with a HTTP 501 status code when an unsupported method is encountered in the request line. This already happens when the `LenientMethods` option is used, but administrators may wish to toggle the `RegisteredMethods` option and register any non-standard methods using the `[RegisterHttpMethod](#registerhttpmethod)` directive, particularly if the `Unsafe` option has been toggled. **Forward Proxy compatibility** The `RegisteredMethods` option should **not** be toggled for forward proxy hosts, as the methods supported by the origin servers are unknown to the proxy server. ### Example of a request leading to HTTP 501 with LenientMethods mode ``` # Unknown HTTP method WOW / HTTP/1.0\r\n\r\n # Lowercase HTTP method get / HTTP/1.0\r\n\r\n ``` Allow0.9|Require1.0 [RFC 2616 §19.6](https://tools.ietf.org/html/rfc2616#section-19.6) "Compatibility With Previous Versions" had encouraged HTTP servers to support legacy HTTP/0.9 requests. RFC 7230 supersedes this with "The expectation to support HTTP/0.9 requests has been removed" and offers additional comments in [RFC 7230 Appendix A](https://tools.ietf.org/html/rfc7230#appendix-A). The `Require1.0` option allows the user to remove support of the default `Allow0.9` option's behavior. ### Example of a request leading to HTTP 400 with Require1.0 mode ``` # Unsupported HTTP version GET /\r\n\r\n ``` Reviewing the messages logged to the `[ErrorLog](#errorlog)`, configured with `[LogLevel](#loglevel)` `debug` level, can help identify such faulty requests along with their origin. Users should pay particular attention to the 400 responses in the access log for invalid requests which were unexpectedly rejected. <If> Directive -------------- | | | | --- | --- | | Description: | Contains directives that apply only if a condition is satisfied by a request at runtime | | Syntax: | ``` <If expression> ... </If> ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | | Compatibility: | Nested conditions are evaluated in 2.4.26 and later | The `<If>` directive evaluates an expression at runtime, and applies the enclosed directives if and only if the expression evaluates to true. For example: ``` <If "-z req('Host')"> ``` would match HTTP/1.0 requests without a Host: header. Expressions may contain various shell-like operators for string comparison (`==`, `!=`, `<`, ...), integer comparison (`-eq`, `-ne`, ...), and others (`-n`, `-z`, `-f`, ...). It is also possible to use regular expressions, ``` <If "%{QUERY_STRING} =~ /(delete|commit)=.*?elem/"> ``` shell-like pattern matches and many other operations. These operations can be done on request headers (`req`), environment variables (`env`), and a large number of other properties. The full documentation is available in [Expressions in Apache HTTP Server](../expr). Only directives that support the directory context can be used within this configuration section. Certain variables, such as `CONTENT_TYPE` and other response headers, are set after <If> conditions have already been evaluated, and so will not be available to use in this directive. ### See also * [Expressions in Apache HTTP Server](../expr), for a complete reference and more examples. * `[<ElseIf>](#elseif)` * `[<Else>](#else)` * [How <Directory>, <Location>, <Files> sections work](../sections) for an explanation of how these different sections are combined when a request is received. `<If>`, `<ElseIf>`, and `<Else>` are applied last. <IfDefine> Directive -------------------- | | | | --- | --- | | Description: | Encloses directives that will be processed only if a test is true at startup | | Syntax: | ``` <IfDefine [!]parameter-name> ... </IfDefine> ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | The `<IfDefine test>...</IfDefine>` section is used to mark directives that are conditional. The directives within an `<IfDefine>` section are only processed if the test is true. If test is false, everything between the start and end markers is ignored. The test in the `<IfDefine>` section directive can be one of two forms: * parameter-name * `!`parameter-name In the former case, the directives between the start and end markers are only processed if the parameter named parameter-name is defined. The second format reverses the test, and only processes the directives if parameter-name is **not** defined. The parameter-name argument is a define as given on the `[httpd](../programs/httpd)` command line via `-Dparameter` at the time the server was started or by the `[Define](#define)` directive. `<IfDefine>` sections are nest-able, which can be used to implement simple multiple-parameter tests. Example: ``` httpd -DReverseProxy -DUseCache -DMemCache ... ``` ``` <IfDefine ReverseProxy> LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so <IfDefine UseCache> LoadModule cache_module modules/mod_cache.so <IfDefine MemCache> LoadModule mem_cache_module modules/mod_mem_cache.so </IfDefine> <IfDefine !MemCache> LoadModule cache_disk_module modules/mod_cache_disk.so </IfDefine> </IfDefine> </IfDefine> ``` <IfDirective> Directive ----------------------- | | | | --- | --- | | Description: | Encloses directives that are processed conditional on the presence or absence of a specific directive | | Syntax: | ``` <IfDirective [!]directive-name> ... </IfDirective> ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | | Compatibility: | Available in 2.4.34 and later. | The `<IfDirective test>...</IfDirective>` section is used to mark directives that are conditional on the presence of a specific directive. The directives within an `<IfDirective>` section are only processed if the test is true. If test is false, everything between the start and end markers is ignored. The test in the `<IfDirective>` section can be one of two forms: * directive-name * !directive-name In the former case, the directives between the start and end markers are only processed if a directive of the given name is available at the time of processing. The second format reverses the test, and only processes the directives if directive-name is **not** available. This section should only be used if you need to have one configuration file that works across multiple versions of `[httpd](../programs/httpd)`, regardless of whether a particular directive is available. In normal operation, directives need not be placed in `<IfDirective>` sections. ### See also * `[<IfSection>](#ifsection)` <IfFile> Directive ------------------ | | | | --- | --- | | Description: | Encloses directives that will be processed only if file exists at startup | | Syntax: | ``` <IfFile [!]filename> ... </IfFile> ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | | Compatibility: | Available in 2.4.34 and later. | The `<IfFile filename>...</IfFile>` section is used to mark directives that are conditional on the existence of a file on disk. The directives within an `<IfFile>` section are only processed if filename exists. If filename doesn't exist, everything between the start and end markers is ignored. filename can be an absolute path or a path relative to the server root. The filename in the `<IfFile>` section directive can take the same forms as the test variable in the `[<IfDefine>](#ifdefine)` section, i.e. the test can be negated if the `!` character is placed directly before filename. If a relative filename is supplied, the check is `[ServerRoot](#serverroot)` relative. In the case where this directive occurs before the `[ServerRoot](#serverroot)`, the path will be checked relative to the compiled-in server root or the server root passed in on the command line via the `-d` parameter. <IfModule> Directive -------------------- | | | | --- | --- | | Description: | Encloses directives that are processed conditional on the presence or absence of a specific module | | Syntax: | ``` <IfModule [!]module-file|module-identifier> ... </IfModule> ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | | Compatibility: | Module identifiers are available in version 2.1 and later. | The `<IfModule test>...</IfModule>` section is used to mark directives that are conditional on the presence of a specific module. The directives within an `<IfModule>` section are only processed if the test is true. If test is false, everything between the start and end markers is ignored. The test in the `<IfModule>` section directive can be one of two forms: * module * !module In the former case, the directives between the start and end markers are only processed if the module named module is included in Apache httpd -- either compiled in or dynamically loaded using `[LoadModule](mod_so#loadmodule)`. The second format reverses the test, and only processes the directives if module is **not** included. The module argument can be either the module identifier or the file name of the module, at the time it was compiled. For example, `rewrite_module` is the identifier and `mod_rewrite.c` is the file name. If a module consists of several source files, use the name of the file containing the string `STANDARD20_MODULE_STUFF`. `<IfModule>` sections are nest-able, which can be used to implement simple multiple-module tests. This section should only be used if you need to have one configuration file that works whether or not a specific module is available. In normal operation, directives need not be placed in `<IfModule>` sections. <IfSection> Directive --------------------- | | | | --- | --- | | Description: | Encloses directives that are processed conditional on the presence or absence of a specific section directive | | Syntax: | ``` <IfSection [!]section-name> ... </IfSection> ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | | Compatibility: | Available in 2.4.34 and later. | The `<IfSection test>...</IfSection>` section is used to mark directives that are conditional on the presence of a specific section directive. A section directive is any directive such as `<VirtualHost>` which encloses other directives, and has a directive name with a leading "<". The directives within an `<IfSection>` section are only processed if the test is true. If test is false, everything between the start and end markers is ignored. The section-name must be specified without either the leading "<" or closing ">". The test in the `<IfSection>` section can be one of two forms: * section-name * !section-name In the former case, the directives between the start and end markers are only processed if a section directive of the given name is available at the time of processing. The second format reverses the test, and only processes the directives if section-name is **not** an available section directive. For example: ``` <IfSection VirtualHost> ... </IfSection> ``` This section should only be used if you need to have one configuration file that works across multiple versions of `[httpd](../programs/httpd)`, regardless of whether a particular section directive is available. In normal operation, directives need not be placed in `<IfSection>` sections. ### See also * `[<IfDirective>](#ifdirective)` Include Directive ----------------- | | | | --- | --- | | Description: | Includes other configuration files from within the server configuration files | | Syntax: | ``` Include file-path|directory-path|wildcard ``` | | Context: | server config, virtual host, directory | | Status: | Core | | Module: | core | | Compatibility: | Directory wildcard matching available in 2.3.6 and later | This directive allows inclusion of other configuration files from within the server configuration files. Shell-style (`fnmatch()`) wildcard characters can be used in the filename or directory parts of the path to include several files at once, in alphabetical order. In addition, if `Include` points to a directory, rather than a file, Apache httpd will read all files in that directory and any subdirectory. However, including entire directories is not recommended, because it is easy to accidentally leave temporary files in a directory that can cause `[httpd](../programs/httpd)` to fail. Instead, we encourage you to use the wildcard syntax shown below, to include files that match a particular pattern, such as \*.conf, for example. The `[Include](#include)` directive will **fail with an error** if a wildcard expression does not match any file. The `[IncludeOptional](#includeoptional)` directive can be used if non-matching wildcards should be ignored. The file path specified may be an absolute path, or may be relative to the `[ServerRoot](#serverroot)` directory. Examples: ``` Include /usr/local/apache2/conf/ssl.conf Include /usr/local/apache2/conf/vhosts/*.conf ``` Or, providing paths relative to your `[ServerRoot](#serverroot)` directory: ``` Include conf/ssl.conf Include conf/vhosts/*.conf ``` Wildcards may be included in the directory or file portion of the path. This example will fail if there is no subdirectory in conf/vhosts that contains at least one \*.conf file: ``` Include conf/vhosts/*/*.conf ``` Alternatively, the following command will just be ignored in case of missing files or directories: ``` IncludeOptional conf/vhosts/*/*.conf ``` ### See also * `[IncludeOptional](#includeoptional)` * `[apachectl](../programs/apachectl)` IncludeOptional Directive ------------------------- | | | | --- | --- | | Description: | Includes other configuration files from within the server configuration files | | Syntax: | ``` IncludeOptional file-path|directory-path|wildcard ``` | | Context: | server config, virtual host, directory | | Status: | Core | | Module: | core | | Compatibility: | Available in 2.3.6 and later. Not existent file paths without wildcards do not cause SyntaxError after 2.4.30 | This directive allows inclusion of other configuration files from within the server configuration files. It works identically to the `[Include](#include)` directive, but it will be silently ignored (instead of causing an error) if wildcards are used and they do not match any file or directory or if a file path does not exist on the file system. ### See also * `[Include](#include)` * `[apachectl](../programs/apachectl)` KeepAlive Directive ------------------- | | | | --- | --- | | Description: | Enables HTTP persistent connections | | Syntax: | ``` KeepAlive On|Off ``` | | Default: | ``` KeepAlive On ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | The Keep-Alive extension to HTTP/1.0 and the persistent connection feature of HTTP/1.1 provide long-lived HTTP sessions which allow multiple requests to be sent over the same TCP connection. In some cases this has been shown to result in an almost 50% speedup in latency times for HTML documents with many images. To enable Keep-Alive connections, set `KeepAlive On`. For HTTP/1.0 clients, Keep-Alive connections will only be used if they are specifically requested by a client. In addition, a Keep-Alive connection with an HTTP/1.0 client can only be used when the length of the content is known in advance. This implies that dynamic content such as CGI output, SSI pages, and server-generated directory listings will generally not use Keep-Alive connections to HTTP/1.0 clients. For HTTP/1.1 clients, persistent connections are the default unless otherwise specified. If the client requests it, chunked encoding will be used in order to send content of unknown length over persistent connections. When a client uses a Keep-Alive connection, it will be counted as a single "request" for the `[MaxConnectionsPerChild](mpm_common#maxconnectionsperchild)` directive, regardless of how many requests are sent using the connection. ### See also * `[MaxKeepAliveRequests](#maxkeepaliverequests)` KeepAliveTimeout Directive -------------------------- | | | | --- | --- | | Description: | Amount of time the server will wait for subsequent requests on a persistent connection | | Syntax: | ``` KeepAliveTimeout num[ms] ``` | | Default: | ``` KeepAliveTimeout 5 ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | The number of seconds Apache httpd will wait for a subsequent request before closing the connection. By adding a postfix of ms the timeout can be also set in milliseconds. Once a request has been received, the timeout value specified by the `[Timeout](#timeout)` directive applies. Setting `KeepAliveTimeout` to a high value may cause performance problems in heavily loaded servers. The higher the timeout, the more server processes will be kept occupied waiting on connections with idle clients. If `KeepAliveTimeout` is **not** set for a name-based virtual host, the value of the first defined virtual host best matching the local IP and port will be used. <Limit> Directive ----------------- | | | | --- | --- | | Description: | Restrict enclosed access controls to only certain HTTP methods | | Syntax: | ``` <Limit method [method] ... > ... </Limit> ``` | | Context: | directory, .htaccess | | Override: | AuthConfig, Limit | | Status: | Core | | Module: | core | Access controls are normally effective for **all** access methods, and this is the usual desired behavior. **In the general case, access control directives should not be placed within a `<Limit>` section.** The purpose of the `<Limit>` directive is to restrict the effect of the access controls to the nominated HTTP methods. For all other methods, the access restrictions that are enclosed in the `<Limit>` bracket **will have no effect**. The following example applies the access control only to the methods `POST`, `PUT`, and `DELETE`, leaving all other methods unprotected: ``` <Limit POST PUT DELETE> Require valid-user </Limit> ``` The method names listed can be one or more of: `GET`, `POST`, `PUT`, `DELETE`, `CONNECT`, `OPTIONS`, `PATCH`, `PROPFIND`, `PROPPATCH`, `MKCOL`, `COPY`, `MOVE`, `LOCK`, and `UNLOCK`. **The method name is case-sensitive.** If `GET` is used, it will also restrict `HEAD` requests. The `TRACE` method cannot be limited (see `[TraceEnable](#traceenable)`). A `[<LimitExcept>](#limitexcept)` section should always be used in preference to a `<Limit>` section when restricting access, since a `[<LimitExcept>](#limitexcept)` section provides protection against arbitrary methods. The `<Limit>` and `[<LimitExcept>](#limitexcept)` directives may be nested. In this case, each successive level of `<Limit>` or `[<LimitExcept>](#limitexcept)` directives must further restrict the set of methods to which access controls apply. When using `<Limit>` or `<LimitExcept>` directives with the `[Require](mod_authz_core#require)` directive, note that the first `[Require](mod_authz_core#require)` to succeed authorizes the request, regardless of the presence of other `[Require](mod_authz_core#require)` directives. For example, given the following configuration, all users will be authorized for `POST` requests, and the `Require group editors` directive will be ignored in all cases: ``` <LimitExcept GET> Require valid-user </LimitExcept> <Limit POST> Require group editors </Limit> ``` <LimitExcept> Directive ----------------------- | | | | --- | --- | | Description: | Restrict access controls to all HTTP methods except the named ones | | Syntax: | ``` <LimitExcept method [method] ... > ... </LimitExcept> ``` | | Context: | directory, .htaccess | | Override: | AuthConfig, Limit | | Status: | Core | | Module: | core | `<LimitExcept>` and `</LimitExcept>` are used to enclose a group of access control directives which will then apply to any HTTP access method **not** listed in the arguments; i.e., it is the opposite of a `[<Limit>](#limit)` section and can be used to control both standard and nonstandard/unrecognized methods. See the documentation for `[<Limit>](#limit)` for more details. For example: ``` <LimitExcept POST GET> Require valid-user </LimitExcept> ``` LimitInternalRecursion Directive -------------------------------- | | | | --- | --- | | Description: | Determine maximum number of internal redirects and nested subrequests | | Syntax: | ``` LimitInternalRecursion number [number] ``` | | Default: | ``` LimitInternalRecursion 10 ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | An internal redirect happens, for example, when using the `[Action](mod_actions#action)` directive, which internally redirects the original request to a CGI script. A subrequest is Apache httpd's mechanism to find out what would happen for some URI if it were requested. For example, `<mod_dir>` uses subrequests to look for the files listed in the `[DirectoryIndex](mod_dir#directoryindex)` directive. `LimitInternalRecursion` prevents the server from crashing when entering an infinite loop of internal redirects or subrequests. Such loops are usually caused by misconfigurations. The directive stores two different limits, which are evaluated on per-request basis. The first number is the maximum number of internal redirects that may follow each other. The second number determines how deeply subrequests may be nested. If you specify only one number, it will be assigned to both limits. ``` LimitInternalRecursion 5 ``` LimitRequestBody Directive -------------------------- | | | | --- | --- | | Description: | Restricts the total size of the HTTP request body sent from the client | | Syntax: | ``` LimitRequestBody bytes ``` | | Default: | ``` LimitRequestBody 0 ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | This directive specifies the number of bytes from 0 (meaning unlimited) to 2147483647 (2GB) that are allowed in a request body. See the note below for the limited applicability to proxy requests. The `LimitRequestBody` directive allows the user to set a limit on the allowed size of an HTTP request message body within the context in which the directive is given (server, per-directory, per-file or per-location). If the client request exceeds that limit, the server will return an error response instead of servicing the request. The size of a normal request message body will vary greatly depending on the nature of the resource and the methods allowed on that resource. CGI scripts typically use the message body for retrieving form information. Implementations of the `PUT` method will require a value at least as large as any representation that the server wishes to accept for that resource. This directive gives the server administrator greater control over abnormal client request behavior, which may be useful for avoiding some forms of denial-of-service attacks. If, for example, you are permitting file upload to a particular location and wish to limit the size of the uploaded file to 100K, you might use the following directive: ``` LimitRequestBody 102400 ``` For a full description of how this directive is interpreted by proxy requests, see the `<mod_proxy>` documentation. LimitRequestFields Directive ---------------------------- | | | | --- | --- | | Description: | Limits the number of HTTP request header fields that will be accepted from the client | | Syntax: | ``` LimitRequestFields number ``` | | Default: | ``` LimitRequestFields 100 ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | Setting number at 0 means unlimited. The default value is defined by the compile-time constant `DEFAULT_LIMIT_REQUEST_FIELDS` (100 as distributed). The `LimitRequestFields` directive allows the server administrator to modify the limit on the number of request header fields allowed in an HTTP request. A server needs this value to be larger than the number of fields that a normal client request might include. The number of request header fields used by a client rarely exceeds 20, but this may vary among different client implementations, often depending upon the extent to which a user has configured their browser to support detailed content negotiation. Optional HTTP extensions are often expressed using request header fields. This directive gives the server administrator greater control over abnormal client request behavior, which may be useful for avoiding some forms of denial-of-service attacks. The value should be increased if normal clients see an error response from the server that indicates too many fields were sent in the request. For example: ``` LimitRequestFields 50 ``` **Warning** When name-based virtual hosting is used, the value for this directive is taken from the default (first-listed) virtual host for the local IP and port combination. LimitRequestFieldSize Directive ------------------------------- | | | | --- | --- | | Description: | Limits the size of the HTTP request header allowed from the client | | Syntax: | ``` LimitRequestFieldSize bytes ``` | | Default: | ``` LimitRequestFieldSize 8190 ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | This directive specifies the number of bytes that will be allowed in an HTTP request header. The `LimitRequestFieldSize` directive allows the server administrator to set the limit on the allowed size of an HTTP request header field. A server needs this value to be large enough to hold any one header field from a normal client request. The size of a normal request header field will vary greatly among different client implementations, often depending upon the extent to which a user has configured their browser to support detailed content negotiation. SPNEGO authentication headers can be up to 12392 bytes. This directive gives the server administrator greater control over abnormal client request behavior, which may be useful for avoiding some forms of denial-of-service attacks. For example: ``` LimitRequestFieldSize 4094 ``` Under normal conditions, the value should not be changed from the default. **Warning** When name-based virtual hosting is used, the value for this directive is taken from the default (first-listed) virtual host best matching the current IP address and port combination. LimitRequestLine Directive -------------------------- | | | | --- | --- | | Description: | Limit the size of the HTTP request line that will be accepted from the client | | Syntax: | ``` LimitRequestLine bytes ``` | | Default: | ``` LimitRequestLine 8190 ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | This directive sets the number of bytes that will be allowed on the HTTP request-line. The `LimitRequestLine` directive allows the server administrator to set the limit on the allowed size of a client's HTTP request-line. Since the request-line consists of the HTTP method, URI, and protocol version, the `LimitRequestLine` directive places a restriction on the length of a request-URI allowed for a request on the server. A server needs this value to be large enough to hold any of its resource names, including any information that might be passed in the query part of a `GET` request. This directive gives the server administrator greater control over abnormal client request behavior, which may be useful for avoiding some forms of denial-of-service attacks. For example: ``` LimitRequestLine 4094 ``` Under normal conditions, the value should not be changed from the default. **Warning** When name-based virtual hosting is used, the value for this directive is taken from the default (first-listed) virtual host best matching the current IP address and port combination. LimitXMLRequestBody Directive ----------------------------- | | | | --- | --- | | Description: | Limits the size of an XML-based request body | | Syntax: | ``` LimitXMLRequestBody bytes ``` | | Default: | ``` LimitXMLRequestBody 1000000 ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | Limit (in bytes) on maximum size of an XML-based request body. A value of `0` will disable any checking. Example: ``` LimitXMLRequestBody 0 ``` <Location> Directive -------------------- | | | | --- | --- | | Description: | Applies the enclosed directives only to matching URLs | | Syntax: | ``` <Location URL-path|URL> ... </Location> ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | The `<Location>` directive limits the scope of the enclosed directives by URL. It is similar to the `[<Directory>](#directory)` directive, and starts a subsection which is terminated with a `</Location>` directive. `<Location>` sections are processed in the order they appear in the configuration file, after the `[<Directory>](#directory)` sections and `.htaccess` files are read, and after the `[<Files>](#files)` sections. `<Location>` sections operate completely outside the filesystem. This has several consequences. Most importantly, `<Location>` directives should not be used to control access to filesystem locations. Since several different URLs may map to the same filesystem location, such access controls may by circumvented. The enclosed directives will be applied to the request if the path component of the URL meets *any* of the following criteria: * The specified location matches exactly the path component of the URL. * The specified location, which ends in a forward slash, is a prefix of the path component of the URL (treated as a context root). * The specified location, with the addition of a trailing slash, is a prefix of the path component of the URL (also treated as a context root). In the example below, where no trailing slash is used, requests to /private1, /private1/ and /private1/file.txt will have the enclosed directives applied, but /private1other would not. ``` <Location "/private1"> # ... </Location> ``` In the example below, where a trailing slash is used, requests to /private2/ and /private2/file.txt will have the enclosed directives applied, but /private2 and /private2other would not. ``` <Location "/private2*/*"> # ... </Location> ``` **When to use `<Location>`** Use `<Location>` to apply directives to content that lives outside the filesystem. For content that lives in the filesystem, use `[<Directory>](#directory)` and `[<Files>](#files)`. An exception is `<Location "/">`, which is an easy way to apply a configuration to the entire server. For all origin (non-proxy) requests, the URL to be matched is a URL-path of the form `/path/`. *No scheme, hostname, port, or query string may be included.* For proxy requests, the URL to be matched is of the form `scheme://servername/path`, and you must include the prefix. The URL may use wildcards. In a wild-card string, `?` matches any single character, and `*` matches any sequences of characters. Neither wildcard character matches a / in the URL-path. [Regular expressions](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") can also be used, with the addition of the `~` character. For example: ``` <Location ~ "/(extra|special)/data"> #... </Location> ``` would match URLs that contained the substring `/extra/data` or `/special/data`. The directive `[<LocationMatch>](#locationmatch)` behaves identical to the regex version of `<Location>`, and is preferred, for the simple reason that `~` is hard to distinguish from `-` in many fonts. The `<Location>` functionality is especially useful when combined with the `[SetHandler](#sethandler)` directive. For example, to enable status requests but allow them only from browsers at `example.com`, you might use: ``` <Location "/status"> SetHandler server-status Require host example.com </Location> ``` **Note about / (slash)** The slash character has special meaning depending on where in a URL it appears. People may be used to its behavior in the filesystem where multiple adjacent slashes are frequently collapsed to a single slash (*i.e.*, `/home///foo` is the same as `/home/foo`). In URL-space this is not necessarily true if directive `[MergeSlashes](#mergeslashes)` has been set to "OFF". The `[<LocationMatch>](#locationmatch)` directive and the regex version of `<Location>` require you to explicitly specify multiple slashes if the slashes are not being merged. For example, `<LocationMatch "^/abc">` would match the request URL `/abc` but not the request URL `//abc`. The (non-regex) `<Location>` directive behaves similarly when used for proxy requests. But when (non-regex) `<Location>` is used for non-proxy requests it will implicitly match multiple slashes with a single slash. For example, if you specify `<Location "/abc/def">` and the request is to `/abc//def` then it will match. ### See also * [How <Directory>, <Location> and <Files> sections work](../sections) for an explanation of how these different sections are combined when a request is received. * `[LocationMatch](#locationmatch)` <LocationMatch> Directive ------------------------- | | | | --- | --- | | Description: | Applies the enclosed directives only to regular-expression matching URLs | | Syntax: | ``` <LocationMatch regex> ... </LocationMatch> ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | The `<LocationMatch>` directive limits the scope of the enclosed directives by URL, in an identical manner to `[<Location>](#location)`. However, it takes a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") as an argument instead of a simple string. For example: ``` <LocationMatch "/(extra|special)/data"> # ... </LocationMatch> ``` would match URLs that contained the substring `/extra/data` or `/special/data`. If the intent is that a URL **starts with** `/extra/data`, rather than merely **contains** `/extra/data`, prefix the regular expression with a `^` to require this. ``` <LocationMatch "^/(extra|special)/data"> ``` From 2.4.8 onwards, named groups and backreferences are captured and written to the environment with the corresponding name prefixed with "MATCH\_" and in upper case. This allows elements of URLs to be referenced from within [expressions](../expr) and modules like `<mod_rewrite>`. In order to prevent confusion, numbered (unnamed) backreferences are ignored. Use named groups instead. ``` <LocationMatch "^/combined/(?<sitename>[^/]+)"> Require ldap-group cn=%{env:MATCH_SITENAME},ou=combined,o=Example </LocationMatch> ``` **Note about / (slash)** The slash character has special meaning depending on where in a URL it appears. People may be used to its behavior in the filesystem where multiple adjacent slashes are frequently collapsed to a single slash (*i.e.*, `/home///foo` is the same as `/home/foo`). In URL-space this is not necessarily true if directive `[MergeSlashes](#mergeslashes)` has been set to "OFF". The `[<LocationMatch>](#locationmatch)` directive and the regex version of `<Location>` require you to explicitly specify multiple slashes if the slashes are not being merged. For example, `<LocationMatch "^/abc">` would match the request URL `/abc` but not the request URL `//abc`. The (non-regex) `<Location>` directive behaves similarly when used for proxy requests. But when (non-regex) `<Location>` is used for non-proxy requests it will implicitly match multiple slashes with a single slash. For example, if you specify `<Location "/abc/def">` and the request is to `/abc//def` then it will match. ### See also * [How <Directory>, <Location> and <Files> sections work](../sections) for an explanation of how these different sections are combined when a request is received LogLevel Directive ------------------ | | | | --- | --- | | Description: | Controls the verbosity of the ErrorLog | | Syntax: | ``` LogLevel [module:]level [module:level] ... ``` | | Default: | ``` LogLevel warn ``` | | Context: | server config, virtual host, directory | | Status: | Core | | Module: | core | | Compatibility: | Per-module and per-directory configuration is available in Apache HTTP Server 2.3.6 and later | `LogLevel` adjusts the verbosity of the messages recorded in the error logs (see `[ErrorLog](#errorlog)` directive). The following levels are available, in order of decreasing significance: | **Level** | **Description** | **Example** | | --- | --- | --- | | `emerg` | Emergencies - system is unusable. | "Child cannot open lock file. Exiting" | | `alert` | Action must be taken immediately. | "getpwuid: couldn't determine user name from uid" | | `crit` | Critical Conditions. | "socket: Failed to get a socket, exiting child" | | `error` | Error conditions. | "Premature end of script headers" | | `warn` | Warning conditions. | "child process 1234 did not exit, sending another SIGHUP" | | `notice` | Normal but significant condition. | "httpd: caught SIGBUS, attempting to dump core in ..." | | `info` | Informational. | "Server seems busy, (you may need to increase StartServers, or Min/MaxSpareServers)..." | | `debug` | Debug-level messages | "Opening config file ..." | | `trace1` | Trace messages | "proxy: FTP: control connection complete" | | `trace2` | Trace messages | "proxy: CONNECT: sending the CONNECT request to the remote proxy" | | `trace3` | Trace messages | "openssl: Handshake: start" | | `trace4` | Trace messages | "read from buffered SSL brigade, mode 0, 17 bytes" | | `trace5` | Trace messages | "map lookup FAILED: map=rewritemap key=keyname" | | `trace6` | Trace messages | "cache lookup FAILED, forcing new map lookup" | | `trace7` | Trace messages, dumping large amounts of data | "| 0000: 02 23 44 30 13 40 ac 34 df 3d bf 9a 19 49 39 15 |" | | `trace8` | Trace messages, dumping large amounts of data | "| 0000: 02 23 44 30 13 40 ac 34 df 3d bf 9a 19 49 39 15 |" | When a particular level is specified, messages from all other levels of higher significance will be reported as well. *E.g.*, when `LogLevel info` is specified, then messages with log levels of `notice` and `warn` will also be posted. Using a level of at least `crit` is recommended. For example: ``` LogLevel notice ``` **Note** When logging to a regular file, messages of the level `notice` cannot be suppressed and thus are always logged. However, this doesn't apply when logging is done using `syslog`. Specifying a level without a module name will reset the level for all modules to that level. Specifying a level with a module name will set the level for that module only. It is possible to use the module source file name, the module identifier, or the module identifier with the trailing `_module` omitted as module specification. This means the following three specifications are equivalent: ``` LogLevel info ssl:warn LogLevel info mod_ssl.c:warn LogLevel info ssl_module:warn ``` It is also possible to change the level per directory: ``` LogLevel info <Directory "/usr/local/apache/htdocs/app"> LogLevel debug </Directory> ``` Per directory loglevel configuration only affects messages that are logged after the request has been parsed and that are associated with the request. Log messages which are associated with the connection or the server are not affected. ### See also * `[ErrorLog](#errorlog)` * `[ErrorLogFormat](#errorlogformat)` * [Apache HTTP Server Log Files](../logs) MaxKeepAliveRequests Directive ------------------------------ | | | | --- | --- | | Description: | Number of requests allowed on a persistent connection | | Syntax: | ``` MaxKeepAliveRequests number ``` | | Default: | ``` MaxKeepAliveRequests 100 ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | The `MaxKeepAliveRequests` directive limits the number of requests allowed per connection when `[KeepAlive](#keepalive)` is on. If it is set to `0`, unlimited requests will be allowed. We recommend that this setting be kept to a high value for maximum server performance. For example: ``` MaxKeepAliveRequests 500 ``` MaxRangeOverlaps Directive -------------------------- | | | | --- | --- | | Description: | Number of overlapping ranges (eg: `100-200,150-300`) allowed before returning the complete resource | | Syntax: | ``` MaxRangeOverlaps default | unlimited | none | number-of-ranges ``` | | Default: | ``` MaxRangeOverlaps 20 ``` | | Context: | server config, virtual host, directory | | Status: | Core | | Module: | core | | Compatibility: | Available in Apache HTTP Server 2.3.15 and later | The `MaxRangeOverlaps` directive limits the number of overlapping HTTP ranges the server is willing to return to the client. If more overlapping ranges than permitted are requested, the complete resource is returned instead. **default** Limits the number of overlapping ranges to a compile-time default of 20. **none** No overlapping Range headers are allowed. **unlimited** The server does not limit the number of overlapping ranges it is willing to satisfy. number-of-ranges A positive number representing the maximum number of overlapping ranges the server is willing to satisfy. MaxRangeReversals Directive --------------------------- | | | | --- | --- | | Description: | Number of range reversals (eg: `100-200,50-70`) allowed before returning the complete resource | | Syntax: | ``` MaxRangeReversals default | unlimited | none | number-of-ranges ``` | | Default: | ``` MaxRangeReversals 20 ``` | | Context: | server config, virtual host, directory | | Status: | Core | | Module: | core | | Compatibility: | Available in Apache HTTP Server 2.3.15 and later | The `MaxRangeReversals` directive limits the number of HTTP Range reversals the server is willing to return to the client. If more ranges reversals than permitted are requested, the complete resource is returned instead. **default** Limits the number of range reversals to a compile-time default of 20. **none** No Range reversals headers are allowed. **unlimited** The server does not limit the number of range reversals it is willing to satisfy. number-of-ranges A positive number representing the maximum number of range reversals the server is willing to satisfy. MaxRanges Directive ------------------- | | | | --- | --- | | Description: | Number of ranges allowed before returning the complete resource | | Syntax: | ``` MaxRanges default | unlimited | none | number-of-ranges ``` | | Default: | ``` MaxRanges 200 ``` | | Context: | server config, virtual host, directory | | Status: | Core | | Module: | core | | Compatibility: | Available in Apache HTTP Server 2.3.15 and later | The `MaxRanges` directive limits the number of HTTP ranges the server is willing to return to the client. If more ranges than permitted are requested, the complete resource is returned instead. **default** Limits the number of ranges to a compile-time default of 200. **none** Range headers are ignored. **unlimited** The server does not limit the number of ranges it is willing to satisfy. number-of-ranges A positive number representing the maximum number of ranges the server is willing to satisfy. MergeSlashes Directive ---------------------- | | | | --- | --- | | Description: | Controls whether the server merges consecutive slashes in URLs. | | Syntax: | ``` MergeSlashes ON|OFF ``` | | Default: | ``` MergeSlashes ON ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | | Compatibility: | Added in 2.4.39 | By default, the server merges (or collapses) multiple consecutive slash ('/') characters in the path component of the request URL. When mapping URL's to the filesystem, these multiple slashes are not significant. However, URL's handled other ways, such as by CGI or proxy, might prefer to retain the significance of multiple consecutive slashes. In these cases `MergeSlashes` can be set to *OFF* to retain the multiple consecutive slashes, which is the legacy behavior. When set to "OFF", regular expressions used in the configuration file that match the path component of the URL (`LocationMatch`, `RewriteRule`, ...) need to take into account multiple consecutive slashes. Non regular expression based `Location` always operate against a URL with merged slashes and cannot differentiate between multiple slashes. MergeTrailers Directive ----------------------- | | | | --- | --- | | Description: | Determines whether trailers are merged into headers | | Syntax: | ``` MergeTrailers [on|off] ``` | | Default: | ``` MergeTrailers off ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | | Compatibility: | 2.4.11 and later | This directive controls whether HTTP trailers are copied into the internal representation of HTTP headers. This merging occurs when the request body has been completely consumed, long after most header processing would have a chance to examine or modify request headers. This option is provided for compatibility with releases prior to 2.4.11, where trailers were always merged. Mutex Directive --------------- | | | | --- | --- | | Description: | Configures mutex mechanism and lock file directory for all or specified mutexes | | Syntax: | ``` Mutex mechanism [default|mutex-name] ... [OmitPID] ``` | | Default: | ``` Mutex default ``` | | Context: | server config | | Status: | Core | | Module: | core | | Compatibility: | Available in Apache HTTP Server 2.3.4 and later | The `Mutex` directive sets the mechanism, and optionally the lock file location, that httpd and modules use to serialize access to resources. Specify `default` as the second argument to change the settings for all mutexes; specify a mutex name (see table below) as the second argument to override defaults only for that mutex. The `Mutex` directive is typically used in the following exceptional situations: * change the mutex mechanism when the default mechanism selected by [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary") has a functional or performance problem * change the directory used by file-based mutexes when the default directory does not support locking **Supported modules** This directive only configures mutexes which have been registered with the core server using the `ap_mutex_register()` API. All modules bundled with httpd support the `Mutex` directive, but third-party modules may not. Consult the documentation of the third-party module, which must indicate the mutex name(s) which can be configured if this directive is supported. The following mutex *mechanisms* are available: * `default | yes` This selects the default locking implementation, as determined by [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary"). The default locking implementation can be displayed by running `[httpd](../programs/httpd)` with the `-V` option. * `none | no` This effectively disables the mutex, and is only allowed for a mutex if the module indicates that it is a valid choice. Consult the module documentation for more information. * `posixsem` This is a mutex variant based on a Posix semaphore. **Warning** The semaphore ownership is not recovered if a thread in the process holding the mutex segfaults, resulting in a hang of the web server. * `sysvsem` This is a mutex variant based on a SystemV IPC semaphore. **Warning** It is possible to "leak" SysV semaphores if processes crash before the semaphore is removed. **Security** The semaphore API allows for a denial of service attack by any CGIs running under the same uid as the webserver (*i.e.*, all CGIs, unless you use something like `[suexec](../programs/suexec)` or `cgiwrapper`). * `sem` This selects the "best" available semaphore implementation, choosing between Posix and SystemV IPC semaphores, in that order. * `pthread` This is a mutex variant based on cross-process Posix thread mutexes. **Warning** On most systems, if a child process terminates abnormally while holding a mutex that uses this implementation, the server will deadlock and stop responding to requests. When this occurs, the server will require a manual restart to recover. Solaris and Linux are notable exceptions as they provide a mechanism which usually allows the mutex to be recovered after a child process terminates abnormally while holding a mutex. If your system is POSIX compliant or if it implements the `pthread_mutexattr_setrobust_np()` function, you may be able to use the `pthread` option safely. * `fcntl:/path/to/mutex` This is a mutex variant where a physical (lock-)file and the `fcntl()` function are used as the mutex. **Warning** When multiple mutexes based on this mechanism are used within multi-threaded, multi-process environments, deadlock errors (EDEADLK) can be reported for valid mutex operations if `fcntl()` is not thread-aware, such as on Solaris. * `flock:/path/to/mutex` This is similar to the `fcntl:/path/to/mutex` method with the exception that the `flock()` function is used to provide file locking. * `file:/path/to/mutex` This selects the "best" available file locking implementation, choosing between `fcntl` and `flock`, in that order. Most mechanisms are only available on selected platforms, where the underlying platform and [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary") support it. Mechanisms which aren't available on all platforms are *posixsem*, *sysvsem*, *sem*, *pthread*, *fcntl*, *flock*, and *file*. With the file-based mechanisms *fcntl* and *flock*, the path, if provided, is a directory where the lock file will be created. The default directory is httpd's run-time file directory relative to `[ServerRoot](#serverroot)`. Always use a local disk filesystem for `/path/to/mutex` and never a directory residing on a NFS- or AFS-filesystem. The basename of the file will be the mutex type, an optional instance string provided by the module, and unless the `OmitPID` keyword is specified, the process id of the httpd parent process will be appended to make the file name unique, avoiding conflicts when multiple httpd instances share a lock file directory. For example, if the mutex name is `mpm-accept` and the lock file directory is `/var/httpd/locks`, the lock file name for the httpd instance with parent process id 12345 would be `/var/httpd/locks/mpm-accept.12345`. **Security** It is best to *avoid* putting mutex files in a world-writable directory such as `/var/tmp` because someone could create a denial of service attack and prevent the server from starting by creating a lockfile with the same name as the one the server will try to create. The following table documents the names of mutexes used by httpd and bundled modules. | Mutex name | Module(s) | Protected resource | | --- | --- | --- | | `mpm-accept` | `<prefork>` and `<worker>` MPMs | incoming connections, to avoid the thundering herd problem; for more information, refer to the [performance tuning](../misc/perf-tuning) documentation | | `authdigest-client` | `mod_auth_digest` | client list in shared memory | | `authdigest-opaque` | `mod_auth_digest` | counter in shared memory | | `ldap-cache` | `mod_ldap` | LDAP result cache | | `rewrite-map` | `mod_rewrite` | communication with external mapping programs, to avoid intermixed I/O from multiple requests | | `ssl-cache` | `mod_ssl` | SSL session cache | | `ssl-stapling` | `mod_ssl` | OCSP stapling response cache | | `watchdog-callback` | `mod_watchdog` | callback function of a particular client module | The `OmitPID` keyword suppresses the addition of the httpd parent process id from the lock file name. In the following example, the mutex mechanism for the MPM accept mutex will be changed from the compiled-in default to `fcntl`, with the associated lock file created in directory `/var/httpd/locks`. The mutex mechanism for all other mutexes will be changed from the compiled-in default to `sysvsem`. ``` Mutex sysvsem default Mutex fcntl:/var/httpd/locks mpm-accept ``` NameVirtualHost Directive ------------------------- | | | | --- | --- | | Description: | DEPRECATED: Designates an IP address for name-virtual hosting | | Syntax: | ``` NameVirtualHost addr[:port] ``` | | Context: | server config | | Status: | Core | | Module: | core | Prior to 2.3.11, `NameVirtualHost` was required to instruct the server that a particular IP address and port combination was usable as a name-based virtual host. In 2.3.11 and later, any time an IP address and port combination is used in multiple virtual hosts, name-based virtual hosting is automatically enabled for that address. This directive currently has no effect. ### See also * [Virtual Hosts documentation](../vhosts/index) Options Directive ----------------- | | | | --- | --- | | Description: | Configures what features are available in a particular directory | | Syntax: | ``` Options [+|-]option [[+|-]option] ... ``` | | Default: | ``` Options FollowSymlinks ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Core | | Module: | core | | Compatibility: | The default was changed from All to FollowSymlinks in 2.3.11 | The `Options` directive controls which server features are available in a particular directory. option can be set to `None`, in which case none of the extra features are enabled, or one or more of the following: `All` All options except for `MultiViews`. `ExecCGI` Execution of CGI scripts using `<mod_cgi>` is permitted. `FollowSymLinks` The server will follow symbolic links in this directory. This is the default setting. Even though the server follows the symlink it does *not* change the pathname used to match against `[<Directory>](#directory)` sections. The `FollowSymLinks` and `SymLinksIfOwnerMatch` `[Options](#options)` work only in `[<Directory>](#directory)` sections or `.htaccess` files. Omitting this option should not be considered a security restriction, since symlink testing is subject to race conditions that make it circumventable. `Includes` Server-side includes provided by `<mod_include>` are permitted. `IncludesNOEXEC` Server-side includes are permitted, but the `#exec cmd` and `#exec cgi` are disabled. It is still possible to `#include virtual` CGI scripts from `[ScriptAlias](mod_alias#scriptalias)`ed directories. `Indexes` If a URL which maps to a directory is requested and there is no `[DirectoryIndex](mod_dir#directoryindex)` (*e.g.*, `index.html`) in that directory, then `<mod_autoindex>` will return a formatted listing of the directory. `MultiViews` [Content negotiated](../content-negotiation) "MultiViews" are allowed using `<mod_negotiation>`. **Note** This option gets ignored if set anywhere other than `[<Directory>](#directory)`, as `<mod_negotiation>` needs real resources to compare against and evaluate from. `SymLinksIfOwnerMatch` The server will only follow symbolic links for which the target file or directory is owned by the same user id as the link. **Note** The `FollowSymLinks` and `SymLinksIfOwnerMatch` `[Options](#options)` work only in `[<Directory>](#directory)` sections or `.htaccess` files. This option should not be considered a security restriction, since symlink testing is subject to race conditions that make it circumventable. Normally, if multiple `Options` could apply to a directory, then the most specific one is used and others are ignored; the options are not merged. (See [how sections are merged](../sections#merging).) However if *all* the options on the `Options` directive are preceded by a `+` or `-` symbol, the options are merged. Any options preceded by a `+` are added to the options currently in force, and any options preceded by a `-` are removed from the options currently in force. **Note** Mixing `Options` with a `+` or `-` with those without is not valid syntax and will be rejected during server startup by the syntax check with an abort. For example, without any `+` and `-` symbols: ``` <Directory "/web/docs"> Options Indexes FollowSymLinks </Directory> <Directory "/web/docs/spec"> Options Includes </Directory> ``` then only `Includes` will be set for the `/web/docs/spec` directory. However if the second `Options` directive uses the `+` and `-` symbols: ``` <Directory "/web/docs"> Options Indexes FollowSymLinks </Directory> <Directory "/web/docs/spec"> Options +Includes -Indexes </Directory> ``` then the options `FollowSymLinks` and `Includes` are set for the `/web/docs/spec` directory. **Note** Using `-IncludesNOEXEC` or `-Includes` disables server-side includes completely regardless of the previous setting. The default in the absence of any other settings is `FollowSymlinks`. Protocol Directive ------------------ | | | | --- | --- | | Description: | Protocol for a listening socket | | Syntax: | ``` Protocol protocol ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | | Compatibility: | Available in Apache 2.1.5 and later. On Windows, from Apache 2.3.3 and later. | This directive specifies the protocol used for a specific listening socket. The protocol is used to determine which module should handle a request and to apply protocol specific optimizations with the `AcceptFilter` directive. This directive not required for most configurations. If not specified, `https` is the default for port 443 and `http` the default for all other ports. The protocol is used to determine which module should handle a request, and to apply protocol specific optimizations with the `[AcceptFilter](#acceptfilter)` directive. For example, if you are running `https` on a non-standard port, specify the protocol explicitly: ``` Protocol https ``` You can also specify the protocol using the `[Listen](mpm_common#listen)` directive. ### See also * `[AcceptFilter](#acceptfilter)` * `[Listen](mpm_common#listen)` Protocols Directive ------------------- | | | | --- | --- | | Description: | Protocols available for a server/virtual host | | Syntax: | ``` Protocols protocol ... ``` | | Default: | ``` Protocols http/1.1 ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | | Compatibility: | Only available from Apache 2.4.17 and later. | This directive specifies the list of protocols supported for a server/virtual host. The list determines the allowed protocols a client may negotiate for this server/host. You need to set protocols if you want to extend the available protocols for a server/host. By default, only the http/1.1 protocol (which includes the compatibility with 1.0 and 0.9 clients) is allowed. For example, if you want to support HTTP/2 for a server with TLS, specify: ``` Protocols h2 http/1.1 ``` Valid protocols are `http/1.1` for http and https connections, `h2` on https connections and `h2c` for http connections. Modules may enable more protocols. It is safe to specify protocols that are unavailable/disabled. Such protocol names will simply be ignored. Protocols specified in base servers are inherited for virtual hosts only if the virtual host has no own Protocols directive. Or, the other way around, Protocols directives in virtual hosts replace any such directive in the base server. ### See also * `[ProtocolsHonorOrder](#protocolshonororder)` ProtocolsHonorOrder Directive ----------------------------- | | | | --- | --- | | Description: | Determines if order of Protocols determines precedence during negotiation | | Syntax: | ``` ProtocolsHonorOrder On|Off ``` | | Default: | ``` ProtocolsHonorOrder On ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | | Compatibility: | Only available from Apache 2.4.17 and later. | This directive specifies if the server should honor the order in which the `Protocols` directive lists protocols. If configured Off, the client supplied list order of protocols has precedence over the order in the server configuration. With `ProtocolsHonorOrder` set to `on` (default), the client ordering does not matter and only the ordering in the server settings influences the outcome of the protocol negotiation. ### See also * `[Protocols](#protocols)` QualifyRedirectURL Directive ---------------------------- | | | | --- | --- | | Description: | Controls whether the REDIRECT\_URL environment variable is fully qualified | | Syntax: | ``` QualifyRedirectURL On|Off ``` | | Default: | ``` QualifyRedirectURL Off ``` | | Context: | server config, virtual host, directory | | Override: | FileInfo | | Status: | Core | | Module: | core | | Compatibility: | Directive supported in 2.4.18 and later. 2.4.17 acted as if 'QualifyRedirectURL On' was configured. | This directive controls whether the server will ensure that the REDIRECT\_URL environment variable is fully qualified. By default, the variable contains the verbatim URL requested by the client, such as "/index.html". With `QualifyRedirectURL On`, the same request would result in a value such as "http://www.example.com/index.html". Even without this directive set, when a request is issued against a fully qualified URL, REDIRECT\_URL will remain fully qualified. ReadBufferSize Directive ------------------------ | | | | --- | --- | | Description: | Size of the buffers used to read data | | Syntax: | ``` ReadBufferSize bytes ``` | | Default: | ``` ReadBufferSize 8192 ``` | | Context: | server config, virtual host, directory | | Status: | Core | | Module: | core | | Compatibility: | 2.4.27 and later | This directive allows to configure the size (in bytes) of the memory buffer used to read data from the network or files. A larger buffer can increase peformances with larger data, but consumes more memory per connection. The minimum configurable size is 1024. RegexDefaultOptions Directive ----------------------------- | | | | --- | --- | | Description: | Allow to configure global/default options for regexes | | Syntax: | ``` RegexDefaultOptions [none] [+|-]option [[+|-]option] ... ``` | | Default: | ``` RegexDefaultOptions DOTALL DOLLAR_ENDONLY ``` | | Context: | server config | | Status: | Core | | Module: | core | | Compatibility: | Only available from Apache 2.4.30 and later. | This directive adds some default behavior to ANY regular expression used afterwards. Any option preceded by a '+' is added to the already set options. Any option preceded by a '-' is removed from the already set options. Any option without a '+' or a '-' will be set, removing any other already set option. The `none` keyword resets any already set options. option can be: `ICASE` Use a case-insensitive match. `EXTENDED` Perl's /x flag, ignore (unescaped-)spaces and comments in the pattern. `DOTALL` Perl's /s flag, '.' matches newline characters. `DOLLAR_ENDONLY` '$' matches at end of subject string only. ``` # Add the ICASE option for all regexes by default RegexDefaultOptions +ICASE ... # Remove the default DOLLAR_ENDONLY option, but keep any other one RegexDefaultOptions -DOLLAR_ENDONLY ... # Set the DOTALL option only, resetting any other one RegexDefaultOptions DOTALL ... # Reset all defined options RegexDefaultOptions none ... ``` RegisterHttpMethod Directive ---------------------------- | | | | --- | --- | | Description: | Register non-standard HTTP methods | | Syntax: | ``` RegisterHttpMethod method [method [...]] ``` | | Context: | server config | | Status: | Core | | Module: | core | | Compatibility: | Available in Apache HTTP Server 2.4.24 and later | This directive may be used to register additional HTTP methods. This is necessary if non-standard methods need to be used with directives that accept method names as parameters, or to allow particular non-standard methods to be used via proxy or CGI script when the server has been configured to only pass recognized methods to modules. ### See also * `[HTTPProtocolOptions](#httpprotocoloptions)` * `[AllowMethods](mod_allowmethods#allowmethods)` RLimitCPU Directive ------------------- | | | | --- | --- | | Description: | Limits the CPU consumption of processes launched by Apache httpd children | | Syntax: | ``` RLimitCPU seconds|max [seconds|max] ``` | | Default: | ``` Unset; uses operating system defaults ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | Takes 1 or 2 parameters. The first parameter sets the soft resource limit for all processes and the second parameter sets the maximum resource limit. Either parameter can be a number, or `max` to indicate to the server that the limit should be set to the maximum allowed by the operating system configuration. Raising the maximum resource limit requires that the server is running as `root` or in the initial startup phase. This applies to processes forked from Apache httpd children servicing requests, not the Apache httpd children themselves. This includes CGI scripts and SSI exec commands, but not any processes forked from the Apache httpd parent, such as piped logs. CPU resource limits are expressed in seconds per process. ### See also * `[RLimitMEM](#rlimitmem)` * `[RLimitNPROC](#rlimitnproc)` RLimitMEM Directive ------------------- | | | | --- | --- | | Description: | Limits the memory consumption of processes launched by Apache httpd children | | Syntax: | ``` RLimitMEM bytes|max [bytes|max] ``` | | Default: | ``` Unset; uses operating system defaults ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | Takes 1 or 2 parameters. The first parameter sets the soft resource limit for all processes and the second parameter sets the maximum resource limit. Either parameter can be a number, or `max` to indicate to the server that the limit should be set to the maximum allowed by the operating system configuration. Raising the maximum resource limit requires that the server is running as `root` or in the initial startup phase. This applies to processes forked from Apache httpd children servicing requests, not the Apache httpd children themselves. This includes CGI scripts and SSI exec commands, but not any processes forked from the Apache httpd parent, such as piped logs. Memory resource limits are expressed in bytes per process. ### See also * `[RLimitCPU](#rlimitcpu)` * `[RLimitNPROC](#rlimitnproc)` RLimitNPROC Directive --------------------- | | | | --- | --- | | Description: | Limits the number of processes that can be launched by processes launched by Apache httpd children | | Syntax: | ``` RLimitNPROC number|max [number|max] ``` | | Default: | ``` Unset; uses operating system defaults ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | Takes 1 or 2 parameters. The first parameter sets the soft resource limit for all processes, and the second parameter sets the maximum resource limit. Either parameter can be a number, or `max` to indicate to the server that the limit should be set to the maximum allowed by the operating system configuration. Raising the maximum resource limit requires that the server is running as `root` or in the initial startup phase. This applies to processes forked from Apache httpd children servicing requests, not the Apache httpd children themselves. This includes CGI scripts and SSI exec commands, but not any processes forked from the Apache httpd parent, such as piped logs. Process limits control the number of processes per user. **Note** If CGI processes are **not** running under user ids other than the web server user id, this directive will limit the number of processes that the server itself can create. Evidence of this situation will be indicated by **`cannot fork`** messages in the `error_log`. ### See also * `[RLimitMEM](#rlimitmem)` * `[RLimitCPU](#rlimitcpu)` ScriptInterpreterSource Directive --------------------------------- | | | | --- | --- | | Description: | Technique for locating the interpreter for CGI scripts | | Syntax: | ``` ScriptInterpreterSource Registry|Registry-Strict|Script ``` | | Default: | ``` ScriptInterpreterSource Script ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | | Compatibility: | Win32 only. | This directive is used to control how Apache httpd finds the interpreter used to run CGI scripts. The default setting is `Script`. This causes Apache httpd to use the interpreter pointed to by the shebang line (first line, starting with `#!`) in the script. On Win32 systems this line usually looks like: ``` #!C:/Perl/bin/perl.exe ``` or, if `perl` is in the `PATH`, simply: ``` #!perl ``` Setting `ScriptInterpreterSource Registry` will cause the Windows Registry tree `HKEY_CLASSES_ROOT` to be searched using the script file extension (e.g., `.pl`) as a search key. The command defined by the registry subkey `Shell\ExecCGI\Command` or, if it does not exist, by the subkey `Shell\Open\Command` is used to open the script file. If the registry keys cannot be found, Apache httpd falls back to the behavior of the `Script` option. **Security** Be careful when using `ScriptInterpreterSource Registry` with `[ScriptAlias](mod_alias#scriptalias)`'ed directories, because Apache httpd will try to execute **every** file within this directory. The `Registry` setting may cause undesired program calls on files which are typically not executed. For example, the default open command on `.htm` files on most Windows systems will execute Microsoft Internet Explorer, so any HTTP request for an `.htm` file existing within the script directory would start the browser in the background on the server. This is a good way to crash your system within a minute or so. The option `Registry-Strict` does the same thing as `Registry` but uses only the subkey `Shell\ExecCGI\Command`. The `ExecCGI` key is not a common one. It must be configured manually in the windows registry and hence prevents accidental program calls on your system. SeeRequestTail Directive ------------------------ | | | | --- | --- | | Description: | Determine if mod\_status displays the first 63 characters of a request or the last 63, assuming the request itself is greater than 63 chars. | | Syntax: | ``` SeeRequestTail On|Off ``` | | Default: | ``` SeeRequestTail Off ``` | | Context: | server config | | Status: | Core | | Module: | core | | Compatibility: | Available in Apache httpd 2.2.7 and later. | mod\_status with `ExtendedStatus On` displays the actual request being handled. For historical purposes, only 63 characters of the request are actually stored for display purposes. This directive controls whether the 1st 63 characters are stored (the previous behavior and the default) or if the last 63 characters are. This is only applicable, of course, if the length of the request is 64 characters or greater. If Apache httpd is handling `GET /disk1/storage/apache/htdocs/images/imagestore1/food/apples.jpg HTTP/1.1` mod\_status displays as follows: | | | | --- | --- | | Off (default) | GET /disk1/storage/apache/htdocs/images/imagestore1/food/apples | | On | orage/apache/htdocs/images/imagestore1/food/apples.jpg HTTP/1.1 | ServerAdmin Directive --------------------- | | | | --- | --- | | Description: | Email address that the server includes in error messages sent to the client | | Syntax: | ``` ServerAdmin email-address|URL ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | The `ServerAdmin` sets the contact address that the server includes in any error messages it returns to the client. If the `httpd` doesn't recognize the supplied argument as an URL, it assumes, that it's an email-address and prepends it with `mailto:` in hyperlink targets. However, it's recommended to actually use an email address, since there are a lot of CGI scripts that make that assumption. If you want to use an URL, it should point to another server under your control. Otherwise users may not be able to contact you in case of errors. It may be worth setting up a dedicated address for this, e.g. ``` ServerAdmin [email protected] ``` as users do not always mention that they are talking about the server! ServerAlias Directive --------------------- | | | | --- | --- | | Description: | Alternate names for a host used when matching requests to name-virtual hosts | | Syntax: | ``` ServerAlias hostname [hostname] ... ``` | | Context: | virtual host | | Status: | Core | | Module: | core | The `ServerAlias` directive sets the alternate names for a host, for use with [name-based virtual hosts](../vhosts/name-based). The `ServerAlias` may include wildcards, if appropriate. ``` <VirtualHost *:80> ServerName server.example.com ServerAlias server server2.example.com server2 ServerAlias *.example.com UseCanonicalName Off # ... </VirtualHost> ``` Name-based virtual hosts for the best-matching set of `[<virtualhost>](#virtualhost)`s are processed in the order they appear in the configuration. The first matching `[ServerName](#servername)` or `[ServerAlias](#serveralias)` is used, with no different precedence for wildcards (nor for ServerName vs. ServerAlias). The complete list of names in the `[<VirtualHost>](#virtualhost)` directive are treated just like a (non wildcard) `ServerAlias`. ### See also * `[UseCanonicalName](#usecanonicalname)` * [Apache HTTP Server Virtual Host documentation](../vhosts/index) ServerName Directive -------------------- | | | | --- | --- | | Description: | Hostname and port that the server uses to identify itself | | Syntax: | ``` ServerName [scheme://]domain-name|ip-address[:port] ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | The `ServerName` directive sets the request scheme, hostname and port that the server uses to identify itself. `ServerName` is used (possibly in conjunction with `[ServerAlias](#serveralias)`) to uniquely identify a virtual host, when using [name-based virtual hosts](../vhosts/name-based). Additionally, this is used when creating self-referential redirection URLs when `[UseCanonicalName](#usecanonicalname)` is set to a non-default value. For example, if the name of the machine hosting the web server is `simple.example.com`, but the machine also has the DNS alias `www.example.com` and you wish the web server to be so identified, the following directive should be used: ``` ServerName www.example.com ``` The `ServerName` directive may appear anywhere within the definition of a server. However, each appearance overrides the previous appearance (within that server). If no `ServerName` is specified, the server attempts to deduce the client visible hostname by first asking the operating system for the system hostname, and if that fails, performing a reverse lookup on an IP address present on the system. If no port is specified in the `ServerName`, then the server will use the port from the incoming request. For optimal reliability and predictability, you should specify an explicit hostname and port using the `ServerName` directive. If you are using [name-based virtual hosts](../vhosts/name-based), the `ServerName` inside a `[<VirtualHost>](#virtualhost)` section specifies what hostname must appear in the request's `Host:` header to match this virtual host. Sometimes, the server runs behind a device that processes SSL, such as a reverse proxy, load balancer or SSL offload appliance. When this is the case, specify the `https://` scheme and the port number to which the clients connect in the `ServerName` directive to make sure that the server generates the correct self-referential URLs. See the description of the `[UseCanonicalName](#usecanonicalname)` and `[UseCanonicalPhysicalPort](#usecanonicalphysicalport)` directives for settings which determine whether self-referential URLs (e.g., by the `<mod_dir>` module) will refer to the specified port, or to the port number given in the client's request. Failure to set `ServerName` to a name that your server can resolve to an IP address will result in a startup warning. `httpd` will then use whatever hostname it can determine, using the system's `hostname` command. This will almost never be the hostname you actually want. ``` httpd: Could not reliably determine the server's fully qualified domain name, using rocinante.local for ServerName ``` ### See also * [Issues Regarding DNS and Apache HTTP Server](../dns-caveats) * [Apache HTTP Server virtual host documentation](../vhosts/index) * `[UseCanonicalName](#usecanonicalname)` * `[UseCanonicalPhysicalPort](#usecanonicalphysicalport)` * `[ServerAlias](#serveralias)` ServerPath Directive -------------------- | | | | --- | --- | | Description: | Legacy URL pathname for a name-based virtual host that is accessed by an incompatible browser | | Syntax: | ``` ServerPath URL-path ``` | | Context: | virtual host | | Status: | Core | | Module: | core | The `ServerPath` directive sets the legacy URL pathname for a host, for use with [name-based virtual hosts](../vhosts/index). ### See also * [Apache HTTP Server Virtual Host documentation](../vhosts/index) ServerRoot Directive -------------------- | | | | --- | --- | | Description: | Base directory for the server installation | | Syntax: | ``` ServerRoot directory-path ``` | | Default: | ``` ServerRoot /usr/local/apache ``` | | Context: | server config | | Status: | Core | | Module: | core | The `ServerRoot` directive sets the directory in which the server lives. Typically it will contain the subdirectories `conf/` and `logs/`. Relative paths in other configuration directives (such as `[Include](#include)` or `[LoadModule](mod_so#loadmodule)`, for example) are taken as relative to this directory. ``` ServerRoot "/home/httpd" ``` The default location of `ServerRoot` may be modified by using the `--prefix` argument to [`configure`](../programs/configure), and most third-party distributions of the server have a different default location from the one listed above. ### See also * [the `-d` option to `httpd`](../invoking) * [the security tips](../misc/security_tips#serverroot) for information on how to properly set permissions on the `ServerRoot` ServerSignature Directive ------------------------- | | | | --- | --- | | Description: | Configures the footer on server-generated documents | | Syntax: | ``` ServerSignature On|Off|EMail ``` | | Default: | ``` ServerSignature Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Core | | Module: | core | The `ServerSignature` directive allows the configuration of a trailing footer line under server-generated documents (error messages, `<mod_proxy>` ftp directory listings, `<mod_info>` output, ...). The reason why you would want to enable such a footer line is that in a chain of proxies, the user often has no possibility to tell which of the chained servers actually produced a returned error message. The `Off` setting, which is the default, suppresses the footer line. The `On` setting simply adds a line with the server version number and `[ServerName](#servername)` of the serving virtual host, and the `EMail` setting additionally creates a "mailto:" reference to the `[ServerAdmin](#serveradmin)` of the referenced document. The details of the server version number presented are controlled by the `[ServerTokens](#servertokens)` directive. ### See also * `[ServerTokens](#servertokens)` ServerTokens Directive ---------------------- | | | | --- | --- | | Description: | Configures the `Server` HTTP response header | | Syntax: | ``` ServerTokens Major|Minor|Min[imal]|Prod[uctOnly]|OS|Full ``` | | Default: | ``` ServerTokens Full ``` | | Context: | server config | | Status: | Core | | Module: | core | This directive controls whether `Server` response header field which is sent back to clients includes a description of the generic OS-type of the server as well as information about compiled-in modules. `ServerTokens Full` (or not specified) Server sends (*e.g.*): `Server: Apache/2.4.2 (Unix) PHP/4.2.2 MyMod/1.2` `ServerTokens Prod[uctOnly]` Server sends (*e.g.*): `Server: Apache` `ServerTokens Major` Server sends (*e.g.*): `Server: Apache/2` `ServerTokens Minor` Server sends (*e.g.*): `Server: Apache/2.4` `ServerTokens Min[imal]` Server sends (*e.g.*): `Server: Apache/2.4.2` `ServerTokens OS` Server sends (*e.g.*): `Server: Apache/2.4.2 (Unix)` This setting applies to the entire server, and cannot be enabled or disabled on a virtualhost-by-virtualhost basis. This directive also controls the information presented by the `[ServerSignature](#serversignature)` directive. Setting `ServerTokens` to less than `minimal` is not recommended because it makes it more difficult to debug interoperational problems. Also note that disabling the Server: header does nothing at all to make your server more secure. The idea of "security through obscurity" is a myth and leads to a false sense of safety. ### See also * `[ServerSignature](#serversignature)` SetHandler Directive -------------------- | | | | --- | --- | | Description: | Forces all matching files to be processed by a handler | | Syntax: | ``` SetHandler handler-name|none|expression ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | | Compatibility: | expression argument 2.4.19 and later | When placed into an `.htaccess` file or a `[<Directory>](#directory)` or `[<Location>](#location)` section, this directive forces all matching files to be parsed through the [handler](../handler) given by handler-name. For example, if you had a directory you wanted to be parsed entirely as imagemap rule files, regardless of extension, you might put the following into an `.htaccess` file in that directory: ``` SetHandler imap-file ``` Another example: if you wanted to have the server display a status report whenever a URL of `http://servername/status` was called, you might put the following into `httpd.conf`: ``` <Location "/status"> SetHandler server-status </Location> ``` You could also use this directive to configure a particular handler for files with a particular file extension. For example: ``` <FilesMatch "\.php$"> SetHandler application/x-httpd-php </FilesMatch> ``` String-valued expressions can be used to reference per-request variables, including backreferences to named regular expressions: ``` <LocationMatch ^/app/(?<sub>[^/]+)/> SetHandler "proxy:unix:/var/run/app_%{env:MATCH_sub}.sock|fcgi://localhost:8080" </LocationMatch> ``` You can override an earlier defined `SetHandler` directive by using the value `None`. **Note** Because `SetHandler` overrides default handlers, normal behavior such as handling of URLs ending in a slash (/) as directories or index files is suppressed. ### See also * `[AddHandler](mod_mime#addhandler)` SetInputFilter Directive ------------------------ | | | | --- | --- | | Description: | Sets the filters that will process client requests and POST input | | Syntax: | ``` SetInputFilter filter[;filter...] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | The `SetInputFilter` directive sets the filter or filters which will process client requests and POST input when they are received by the server. This is in addition to any filters defined elsewhere, including the `[AddInputFilter](mod_mime#addinputfilter)` directive. If more than one filter is specified, they must be separated by semicolons in the order in which they should process the content. ### See also * [Filters](../filter) documentation SetOutputFilter Directive ------------------------- | | | | --- | --- | | Description: | Sets the filters that will process responses from the server | | Syntax: | ``` SetOutputFilter filter[;filter...] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Core | | Module: | core | The `SetOutputFilter` directive sets the filters which will process responses from the server before they are sent to the client. This is in addition to any filters defined elsewhere, including the `[AddOutputFilter](mod_mime#addoutputfilter)` directive. For example, the following configuration will process all files in the `/www/data/` directory for server-side includes. ``` <Directory "/www/data/"> SetOutputFilter INCLUDES </Directory> ``` If more than one filter is specified, they must be separated by semicolons in the order in which they should process the content. ### See also * [Filters](../filter) documentation StrictHostCheck Directive ------------------------- | | | | --- | --- | | Description: | Controls whether the server requires the requested hostname be listed enumerated in the virtual host handling the request | | Syntax: | ``` StrictHostCheck ON|OFF ``` | | Default: | ``` StrictHostCheck OFF ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | | Compatibility: | Added in 2.4.49 | By default, the server will respond to requests for any hostname, including requests addressed to unexpected or unconfigured hostnames. While this is convenient, it is sometimes desirable to limit what hostnames a backend application handles since it will often generate self-referential responses. By setting `StrictHostCheck` to *ON*, the server will return an HTTP 400 error if the requested hostname hasn't been explicitly listed by either `[ServerName](#servername)` or `[ServerAlias](#serveralias)` in the virtual host that best matches the details of the incoming connection. This directive also allows matching of the requested hostname to hostnames specified within the opening `[VirtualHost](#virtualhost)` tag, which is a relatively obscure configuration mechanism that acts like additional `[ServerAlias](#serveralias)` entries. This directive has no affect in non-default virtual hosts. The value inherited from the global server configuration, or the default virtualhost for the ip:port the underlying connection, determine the effective value. TimeOut Directive ----------------- | | | | --- | --- | | Description: | Amount of time the server will wait for certain events before failing a request | | Syntax: | ``` TimeOut seconds ``` | | Default: | ``` TimeOut 60 ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | The `TimeOut` directive defines the length of time Apache httpd will wait for I/O in various circumstances: * When reading data from the client, the length of time to wait for a TCP packet to arrive if the read buffer is empty. For initial data on a new connection, this directive doesn't take effect until after any configured `[AcceptFilter](#acceptfilter)` has passed the new connection to the server. * When writing data to the client, the length of time to wait for an acknowledgement of a packet if the send buffer is full. * In `<mod_cgi>` and `<mod_cgid>`, the length of time to wait for any individual block of output from a CGI script. * In `<mod_ext_filter>`, the length of time to wait for output from a filtering process. * In `<mod_proxy>`, the default timeout value if `[ProxyTimeout](mod_proxy#proxytimeout)` is not configured. TraceEnable Directive --------------------- | | | | --- | --- | | Description: | Determines the behavior on `TRACE` requests | | Syntax: | ``` TraceEnable [on|off|extended] ``` | | Default: | ``` TraceEnable on ``` | | Context: | server config, virtual host | | Status: | Core | | Module: | core | This directive overrides the behavior of `TRACE` for both the core server and `<mod_proxy>`. The default `TraceEnable on` permits `TRACE` requests per RFC 2616, which disallows any request body to accompany the request. `TraceEnable off` causes the core server and `<mod_proxy>` to return a `405` (Method not allowed) error to the client. Finally, for testing and diagnostic purposes only, request bodies may be allowed using the non-compliant `TraceEnable extended` directive. The core (as an origin server) will restrict the request body to 64Kb (plus 8Kb for chunk headers if `Transfer-Encoding: chunked` is used). The core will reflect the full headers and all chunk headers with the response body. As a proxy server, the request body is not restricted to 64Kb. **Note** Despite claims to the contrary, enabling the `TRACE` method does not expose any security vulnerability in Apache httpd. The `TRACE` method is defined by the HTTP/1.1 specification and implementations are expected to support it. UnDefine Directive ------------------ | | | | --- | --- | | Description: | Undefine the existence of a variable | | Syntax: | ``` UnDefine parameter-name ``` | | Context: | server config | | Status: | Core | | Module: | core | Undoes the effect of a `[Define](#define)` or of passing a `-D` argument to `[httpd](../programs/httpd)`. This directive can be used to toggle the use of `[<IfDefine>](#ifdefine)` sections without needing to alter `-D` arguments in any startup scripts. Variable names may not contain colon ":" characters, to avoid clashes with `[RewriteMap](mod_rewrite#rewritemap)`'s syntax. **Virtual Host scope and pitfalls** While this directive is supported in virtual host context, the changes it makes are visible to any later configuration directives, beyond any enclosing virtual host. ### See also * `[Define](#define)` * `[IfDefine](#ifdefine)` UseCanonicalName Directive -------------------------- | | | | --- | --- | | Description: | Configures how the server determines its own name and port | | Syntax: | ``` UseCanonicalName On|Off|DNS ``` | | Default: | ``` UseCanonicalName Off ``` | | Context: | server config, virtual host, directory | | Status: | Core | | Module: | core | In many situations Apache httpd must construct a *self-referential* URL -- that is, a URL that refers back to the same server. With `UseCanonicalName On` Apache httpd will use the hostname and port specified in the `[ServerName](#servername)` directive to construct the canonical name for the server. This name is used in all self-referential URLs, and for the values of `SERVER_NAME` and `SERVER_PORT` in CGIs. With `UseCanonicalName Off` Apache httpd will form self-referential URLs using the hostname and port supplied by the client if any are supplied (otherwise it will use the canonical name, as defined above). These values are the same that are used to implement [name-based virtual hosts](../vhosts/name-based) and are available with the same clients. The CGI variables `SERVER_NAME` and `SERVER_PORT` will be constructed from the client supplied values as well. An example where this may be useful is on an intranet server where you have users connecting to the machine using short names such as `www`. You'll notice that if the users type a shortname and a URL which is a directory, such as `http://www/splat`, *without the trailing slash*, then Apache httpd will redirect them to `http://www.example.com/splat/`. If you have authentication enabled, this will cause the user to have to authenticate twice (once for `www` and once again for `www.example.com` -- see [the FAQ on this subject for more information](http://wiki.apache.org/httpd/FAQ#Why_does_Apache_ask_for_my_password_twice_before_serving_a_file.3F)). But if `UseCanonicalName` is set `Off`, then Apache httpd will redirect to `http://www/splat/`. There is a third option, `UseCanonicalName DNS`, which is intended for use with mass IP-based virtual hosting to support ancient clients that do not provide a `Host:` header. With this option, Apache httpd does a reverse DNS lookup on the server IP address that the client connected to in order to work out self-referential URLs. **Warning** If CGIs make assumptions about the values of `SERVER_NAME`, they may be broken by this option. The client is essentially free to give whatever value they want as a hostname. But if the CGI is only using `SERVER_NAME` to construct self-referential URLs, then it should be just fine. ### See also * `[UseCanonicalPhysicalPort](#usecanonicalphysicalport)` * `[ServerName](#servername)` * `[Listen](mpm_common#listen)` UseCanonicalPhysicalPort Directive ---------------------------------- | | | | --- | --- | | Description: | Configures how the server determines its own port | | Syntax: | ``` UseCanonicalPhysicalPort On|Off ``` | | Default: | ``` UseCanonicalPhysicalPort Off ``` | | Context: | server config, virtual host, directory | | Status: | Core | | Module: | core | In many situations Apache httpd must construct a *self-referential* URL -- that is, a URL that refers back to the same server. With `UseCanonicalPhysicalPort On`, Apache httpd will, when constructing the canonical port for the server to honor the `[UseCanonicalName](#usecanonicalname)` directive, provide the actual physical port number being used by this request as a potential port. With `UseCanonicalPhysicalPort Off`, Apache httpd will not ever use the actual physical port number, instead relying on all configured information to construct a valid port number. **Note** The ordering of the lookup when the physical port is used is as follows: `UseCanonicalName On` 1. Port provided in `[Servername](#servername)` 2. Physical port 3. Default port `UseCanonicalName Off | DNS` 1. Parsed port from `Host:` header 2. Physical port 3. Port provided in `[Servername](#servername)` 4. Default port With `UseCanonicalPhysicalPort Off`, the physical ports are removed from the ordering. ### See also * `[UseCanonicalName](#usecanonicalname)` * `[ServerName](#servername)` * `[Listen](mpm_common#listen)` <VirtualHost> Directive ----------------------- | | | | --- | --- | | Description: | Contains directives that apply only to a specific hostname or IP address | | Syntax: | ``` <VirtualHost addr[:port] [addr[:port]] ...> ... </VirtualHost> ``` | | Context: | server config | | Status: | Core | | Module: | core | `<VirtualHost>` and `</VirtualHost>` are used to enclose a group of directives that will apply only to a particular virtual host. Any directive that is allowed in a virtual host context may be used. When the server receives a request for a document on a particular virtual host, it uses the configuration directives enclosed in the `<VirtualHost>` section. Addr can be any of the following, optionally followed by a colon and a port number (or \*): * The IP address of the virtual host; * A fully qualified domain name for the IP address of the virtual host (not recommended); * The character `*`, which acts as a wildcard and matches any IP address. * The string `_default_`, which is an alias for `*` ``` <VirtualHost 10.1.2.3:80> ServerAdmin [email protected] DocumentRoot "/www/docs/host.example.com" ServerName host.example.com ErrorLog "logs/host.example.com-error_log" TransferLog "logs/host.example.com-access_log" </VirtualHost> ``` IPv6 addresses must be specified in square brackets because the optional port number could not be determined otherwise. An IPv6 example is shown below: ``` <VirtualHost [2001:db8::a00:20ff:fea7:ccea]:80> ServerAdmin [email protected] DocumentRoot "/www/docs/host.example.com" ServerName host.example.com ErrorLog "logs/host.example.com-error_log" TransferLog "logs/host.example.com-access_log" </VirtualHost> ``` Each Virtual Host must correspond to a different IP address, different port number, or a different host name for the server, in the former case the server machine must be configured to accept IP packets for multiple addresses. (If the machine does not have multiple network interfaces, then this can be accomplished with the `ifconfig alias` command -- if your OS supports it). **Note** The use of `<VirtualHost>` does **not** affect what addresses Apache httpd listens on. You may need to ensure that Apache httpd is listening on the correct addresses using `[Listen](mpm_common#listen)`. A `[ServerName](#servername)` should be specified inside each `<VirtualHost>` block. If it is absent, the `[ServerName](#servername)` from the "main" server configuration will be inherited. When a request is received, the server first maps it to the best matching `<VirtualHost>` based on the local IP address and port combination only. Non-wildcards have a higher precedence. If no match based on IP and port occurs at all, the "main" server configuration is used. If multiple virtual hosts contain the best matching IP address and port, the server selects from these virtual hosts the best match based on the requested hostname. If no matching name-based virtual host is found, then the first listed virtual host that matched the IP address will be used. As a consequence, the first listed virtual host for a given IP address and port combination is the default virtual host for that IP and port combination. **Security** See the [security tips](../misc/security_tips) document for details on why your security could be compromised if the directory where log files are stored is writable by anyone other than the user that starts the server. ### See also * [Apache HTTP Server Virtual Host documentation](../vhosts/index) * [Issues Regarding DNS and Apache HTTP Server](../dns-caveats) * [Setting which addresses and ports Apache HTTP Server uses](../bind) * [How <Directory>, <Location> and <Files> sections work](../sections) for an explanation of how these different sections are combined when a request is received
programming_docs
apache_http_server Apache Module mod_authn_core Apache Module mod\_authn\_core ============================== | | | | --- | --- | | Description: | Core Authentication | | Status: | Base | | Module Identifier: | authn\_core\_module | | Source File: | mod\_authn\_core.c | | Compatibility: | Available in Apache 2.3 and later | ### Summary This module provides core authentication capabilities to allow or deny access to portions of the web site. `<mod_authn_core>` provides directives that are common to all authentication providers. Creating Authentication Provider Aliases ---------------------------------------- Extended authentication providers can be created within the configuration file and assigned an alias name. The alias providers can then be referenced through the directives `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` or `[AuthDigestProvider](mod_auth_digest#authdigestprovider)` in the same way as a base authentication provider. Besides the ability to create and alias an extended provider, it also allows the same extended authentication provider to be reference by multiple locations. ### Examples This example checks for passwords in two different text files. ### Checking multiple text password files ``` # Check here first <AuthnProviderAlias file file1> AuthUserFile "/www/conf/passwords1" </AuthnProviderAlias> # Then check here <AuthnProviderAlias file file2> AuthUserFile "/www/conf/passwords2" </AuthnProviderAlias> <Directory "/var/web/pages/secure"> AuthBasicProvider file1 file2 AuthType Basic AuthName "Protected Area" Require valid-user </Directory> ``` The example below creates two different ldap authentication provider aliases based on the ldap provider. This allows a single authenticated location to be serviced by multiple ldap hosts: ### Checking multiple LDAP servers ``` <AuthnProviderAlias ldap ldap-alias1> AuthLDAPBindDN cn=youruser,o=ctx AuthLDAPBindPassword yourpassword AuthLDAPURL ldap://ldap.host/o=ctx </AuthnProviderAlias> <AuthnProviderAlias ldap ldap-other-alias> AuthLDAPBindDN cn=yourotheruser,o=dev AuthLDAPBindPassword yourotherpassword AuthLDAPURL ldap://other.ldap.host/o=dev?cn </AuthnProviderAlias> Alias "/secure" "/webpages/secure" <Directory "/webpages/secure"> AuthBasicProvider ldap-other-alias ldap-alias1 AuthType Basic AuthName "LDAP Protected Place" Require valid-user # Note that Require ldap-* would not work here, since the # AuthnProviderAlias does not provide the config to authorization providers # that are implemented in the same module as the authentication provider. </Directory> ``` AuthName Directive ------------------ | | | | --- | --- | | Description: | Authorization realm for use in HTTP authentication | | Syntax: | ``` AuthName auth-domain ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_authn\_core | This directive sets the name of the authorization realm for a directory. This realm is given to the client so that the user knows which username and password to send. `AuthName` takes a single argument; if the realm name contains spaces, it must be enclosed in quotation marks. It must be accompanied by `[AuthType](#authtype)` and `[Require](mod_authz_core#require)` directives, and directives such as `[AuthUserFile](mod_authn_file#authuserfile)` and `[AuthGroupFile](mod_authz_groupfile#authgroupfile)` to work. For example: ``` AuthName "Top Secret" ``` The string provided for the `AuthName` is what will appear in the password dialog provided by most browsers. ### See also * [Authentication, Authorization, and Access Control](../howto/auth) * `<mod_authz_core>` <AuthnProviderAlias> Directive ------------------------------ | | | | --- | --- | | Description: | Enclose a group of directives that represent an extension of a base authentication provider and referenced by the specified alias | | Syntax: | ``` <AuthnProviderAlias baseProvider Alias> ... </AuthnProviderAlias> ``` | | Context: | server config | | Status: | Base | | Module: | mod\_authn\_core | `<AuthnProviderAlias>` and `</AuthnProviderAlias>` are used to enclose a group of authentication directives that can be referenced by the alias name using one of the directives `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` or `[AuthDigestProvider](mod_auth_digest#authdigestprovider)`. This directive has no affect on authorization, even for modules that provide both authentication and authorization. AuthType Directive ------------------ | | | | --- | --- | | Description: | Type of user authentication | | Syntax: | ``` AuthType None|Basic|Digest|Form ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_authn\_core | This directive selects the type of user authentication for a directory. The authentication types available are `None`, `Basic` (implemented by `<mod_auth_basic>`), `Digest` (implemented by `<mod_auth_digest>`), and `Form` (implemented by `<mod_auth_form>`). To implement authentication, you must also use the `[AuthName](#authname)` and `[Require](mod_authz_core#require)` directives. In addition, the server must have an authentication-provider module such as `<mod_authn_file>` and an authorization module such as `<mod_authz_user>`. The authentication type `None` disables authentication. When authentication is enabled, it is normally inherited by each subsequent [configuration section](../sections#mergin), unless a different authentication type is specified. If no authentication is desired for a subsection of an authenticated section, the authentication type `None` may be used; in the following example, clients may access the `/www/docs/public` directory without authenticating: ``` <Directory "/www/docs"> AuthType Basic AuthName Documents AuthBasicProvider file AuthUserFile "/usr/local/apache/passwd/passwords" Require valid-user </Directory> <Directory "/www/docs/public"> AuthType None Require all granted </Directory> ``` When disabling authentication, note that clients which have already authenticated against another portion of the server's document tree will typically continue to send authentication HTTP headers or cookies with each request, regardless of whether the server actually requires authentication for every resource. ### See also * [Authentication, Authorization, and Access Control](../howto/auth) apache_http_server Apache Module mod_data Apache Module mod\_data ======================= | | | | --- | --- | | Description: | Convert response body into an RFC2397 data URL | | Status: | Extension | | Module Identifier: | data\_module | | Source File: | mod\_data.c | | Compatibility: | Available in Apache 2.3 and later | ### Summary This module provides the ability to convert a response into an [RFC2397 data URL](http://tools.ietf.org/html/rfc2397). Data URLs can be embedded inline within web pages using something like the `<mod_include>` module, to remove the need for clients to make separate connections to fetch what may potentially be many small images. Data URLs may also be included into pages generated by scripting languages such as PHP. ### An example of a data URL ``` data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH hhx4dbgYKAAA7 ``` The filter takes no parameters, and can be added to the filter stack using the `[SetOutputFilter](core#setoutputfilter)` directive, or any of the directives supported by the `<mod_filter>` module. ### Configuring the filter ``` <Location "/data/images"> SetOutputFilter DATA </Location> ``` apache_http_server Apache Module mod_proxy_http Apache Module mod\_proxy\_http ============================== | | | | --- | --- | | Description: | HTTP support module for `<mod_proxy>` | | Status: | Extension | | Module Identifier: | proxy\_http\_module | | Source File: | mod\_proxy\_http.c | ### Summary This module *requires* the service of `<mod_proxy>`. It provides the features used for proxying HTTP and HTTPS requests. `<mod_proxy_http>` supports HTTP/0.9, HTTP/1.0 and HTTP/1.1. It does *not* provide any caching abilities. If you want to set up a caching proxy, you might want to use the additional service of the `<mod_cache>` module. Thus, in order to get the ability of handling HTTP proxy requests, `<mod_proxy>` and `<mod_proxy_http>` have to be present in the server. **Warning** Do not enable proxying until you have [secured your server](mod_proxy#access). Open proxy servers are dangerous both to your network and to the Internet at large. Environment Variables --------------------- In addition to the configuration directives that control the behaviour of `<mod_proxy>`, there are a number of environment variables that control the HTTP protocol provider. Environment variables below that don't specify specific values are enabled when set to any value. proxy-sendextracrlf Causes proxy to send an extra CR-LF newline on the end of a request. This is a workaround for a bug in some browsers. force-proxy-request-1.0 Forces the proxy to send requests to the backend as HTTP/1.0 and disables HTTP/1.1 features. proxy-nokeepalive Forces the proxy to close the backend connection after each request. proxy-chain-auth If the proxy requires authentication, it will read and consume the proxy authentication credentials sent by the client. With proxy-chain-auth it will *also* forward the credentials to the next proxy in the chain. This may be necessary if you have a chain of proxies that share authentication information. **Security Warning:** Do not set this unless you know you need it, as it forwards sensitive information! proxy-sendcl HTTP/1.0 required all HTTP requests that include a body (e.g. POST requests) to include a Content-Length header. This environment variable forces the Apache proxy to send this header to the backend server, regardless of what the Client sent to the proxy. It ensures compatibility when proxying for an HTTP/1.0 or unknown backend. However, it may require the entire request to be buffered by the proxy, so it becomes very inefficient for large requests. proxy-sendchunks or proxy-sendchunked This is the opposite of proxy-sendcl. It allows request bodies to be sent to the backend using chunked transfer encoding. This allows the request to be efficiently streamed, but requires that the backend server supports HTTP/1.1. proxy-interim-response This variable takes values `RFC` (the default) or `Suppress`. Earlier httpd versions would suppress HTTP interim (1xx) responses sent from the backend. This is technically a violation of the HTTP protocol. In practice, if a backend sends an interim response, it may itself be extending the protocol in a manner we know nothing about, or just broken. So this is now configurable: set `proxy-interim-response RFC` to be fully protocol compliant, or `proxy-interim-response Suppress` to suppress interim responses. proxy-initial-not-pooled If this variable is set, no pooled connection will be reused if the client request is the initial request on the frontend connection. This avoids the "proxy: error reading status line from remote server" error message caused by the race condition that the backend server closed the pooled connection after the connection check by the proxy and before data sent by the proxy reached the backend. It has to be kept in mind that setting this variable downgrades performance, especially with HTTP/1.0 clients. Request notes ------------- `<mod_proxy_http>` creates the following request notes for logging using the `%{VARNAME}n` format in `[LogFormat](mod_log_config#logformat)` or `[ErrorLogFormat](core#errorlogformat)`: proxy-source-port The local port used for the connection to the backend server. proxy-status The HTTP status received from the backend server. apache_http_server Apache Module mod_actions Apache Module mod\_actions ========================== | | | | --- | --- | | Description: | Execute CGI scripts based on media type or request method. | | Status: | Base | | Module Identifier: | actions\_module | | Source File: | mod\_actions.c | ### Summary This module has two directives. The `[Action](#action)` directive lets you run CGI scripts whenever a file of a certain [MIME content type](https://httpd.apache.org/docs/2.4/en/glossary.html#mime-type "see glossary") is requested. The `[Script](#script)` directive lets you run CGI scripts whenever a particular method is used in a request. This makes it much easier to execute scripts that process files. Action Directive ---------------- | | | | --- | --- | | Description: | Activates a CGI script for a particular handler or content-type | | Syntax: | ``` Action action-type cgi-script [virtual] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_actions | | Compatibility: | The `virtual` modifier and handler passing were introduced in Apache 2.1 | This directive adds an action, which will activate cgi-script when action-type is triggered by the request. The cgi-script is the URL-path to a resource that has been designated as a CGI script using `[ScriptAlias](mod_alias#scriptalias)` or `[AddHandler](mod_mime#addhandler)`. The action-type can be either a [handler](../handler) or a [MIME content type](https://httpd.apache.org/docs/2.4/en/glossary.html#mime-type "see glossary"). It sends the URL and file path of the requested document using the standard CGI `PATH_INFO` and `PATH_TRANSLATED` environment variables. The handler used for the particular request is passed using the `REDIRECT_HANDLER` variable. ### Example: MIME type ``` # Requests for files of a particular MIME content type: Action image/gif /cgi-bin/images.cgi ``` In this example, requests for files with a MIME content type of `image/gif` will be handled by the specified cgi script `/cgi-bin/images.cgi`. ### Example: File extension ``` # Files of a particular file extension AddHandler my-file-type .xyz Action my-file-type "/cgi-bin/program.cgi" ``` In this example, requests for files with a file extension of `.xyz` are handled by the specified cgi script `/cgi-bin/program.cgi`. The optional `virtual` modifier turns off the check whether the requested file really exists. This is useful, for example, if you want to use the `Action` directive in virtual locations. ``` <Location "/news"> SetHandler news-handler Action news-handler "/cgi-bin/news.cgi" virtual </Location> ``` ### See also * `[AddHandler](mod_mime#addhandler)` Script Directive ---------------- | | | | --- | --- | | Description: | Activates a CGI script for a particular request method. | | Syntax: | ``` Script method cgi-script ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_actions | This directive adds an action, which will activate cgi-script when a file is requested using the method of method. The cgi-script is the URL-path to a resource that has been designated as a CGI script using `[ScriptAlias](mod_alias#scriptalias)` or `[AddHandler](mod_mime#addhandler)`. The URL and file path of the requested document is sent using the standard CGI `PATH_INFO` and `PATH_TRANSLATED` environment variables. Any arbitrary method name may be used. **Method names are case-sensitive**, so `Script PUT` and `Script put` have two entirely different effects. Note that the `Script` command defines default actions only. If a CGI script is called, or some other resource that is capable of handling the requested method internally, it will do so. Also note that `Script` with a method of `GET` will only be called if there are query arguments present (*e.g.*, foo.html?hi). Otherwise, the request will proceed normally. ``` # All GET requests go here Script GET "/cgi-bin/search" # A CGI PUT handler Script PUT "/~bob/put.cgi" ``` apache_http_server Apache Module mod_dav Apache Module mod\_dav ====================== | | | | --- | --- | | Description: | Distributed Authoring and Versioning ([WebDAV](http://www.webdav.org/)) functionality | | Status: | Extension | | Module Identifier: | dav\_module | | Source File: | mod\_dav.c | ### Summary This module provides class 1 and class 2 [WebDAV](http://www.webdav.org) ('Web-based Distributed Authoring and Versioning') functionality for Apache. This extension to the HTTP protocol allows creating, moving, copying, and deleting resources and collections on a remote web server. Enabling WebDAV --------------- To enable `<mod_dav>`, add the following to a container in your `httpd.conf` file: ``` Dav On ``` This enables the DAV file system provider, which is implemented by the `<mod_dav_fs>` module. Therefore, that module must be compiled into the server or loaded at runtime using the `[LoadModule](mod_so#loadmodule)` directive. In addition, a location for the DAV lock database must be specified in the global section of your `httpd.conf` file using the `[DavLockDB](mod_dav_fs#davlockdb)` directive: ``` DavLockDB /usr/local/apache2/var/DavLock ``` The directory containing the lock database file must be writable by the `[User](mod_unixd#user)` and `[Group](mod_unixd#group)` under which Apache is running. You may wish to add a `[<Limit>](core#limit)` clause inside the `[<Location>](core#location)` directive to limit access to DAV-enabled locations. If you want to set the maximum amount of bytes that a DAV client can send at one request, you have to use the `[LimitXMLRequestBody](core#limitxmlrequestbody)` directive. The "normal" `[LimitRequestBody](core#limitrequestbody)` directive has no effect on DAV requests. ### Full Example ``` DavLockDB "/usr/local/apache2/var/DavLock" <Directory "/usr/local/apache2/htdocs/foo"> Require all granted Dav On AuthType Basic AuthName DAV AuthUserFile "user.passwd" <LimitExcept GET POST OPTIONS> Require user admin </LimitExcept> </Directory> ``` Security Issues --------------- Since DAV access methods allow remote clients to manipulate files on the server, you must take particular care to assure that your server is secure before enabling `<mod_dav>`. Any location on the server where DAV is enabled should be protected by authentication. The use of HTTP Basic Authentication is not recommended. You should use at least HTTP Digest Authentication, which is provided by the `<mod_auth_digest>` module. Nearly all WebDAV clients support this authentication method. An alternative is Basic Authentication over an [SSL](../ssl/index) enabled connection. In order for `<mod_dav>` to manage files, it must be able to write to the directories and files under its control using the `[User](mod_unixd#user)` and `[Group](mod_unixd#group)` under which Apache is running. New files created will also be owned by this `[User](mod_unixd#user)` and `[Group](mod_unixd#group)`. For this reason, it is important to control access to this account. The DAV repository is considered private to Apache; modifying files outside of Apache (for example using FTP or filesystem-level tools) should not be allowed. `<mod_dav>` may be subject to various kinds of denial-of-service attacks. The `[LimitXMLRequestBody](core#limitxmlrequestbody)` directive can be used to limit the amount of memory consumed in parsing large DAV requests. The `[DavDepthInfinity](#davdepthinfinity)` directive can be used to prevent `PROPFIND` requests on a very large repository from consuming large amounts of memory. Another possible denial-of-service attack involves a client simply filling up all available disk space with many large files. There is no direct way to prevent this in Apache, so you should avoid giving DAV access to untrusted users. Complex Configurations ---------------------- One common request is to use `<mod_dav>` to manipulate dynamic files (PHP scripts, CGI scripts, etc). This is difficult because a `GET` request will always run the script, rather than downloading its contents. One way to avoid this is to map two different URLs to the content, one of which will run the script, and one of which will allow it to be downloaded and manipulated with DAV. ``` Alias "/phparea" "/home/gstein/php_files" Alias "/php-source" "/home/gstein/php_files" <Location "/php-source"> Dav On ForceType text/plain </Location> ``` With this setup, `http://example.com/phparea` can be used to access the output of the PHP scripts, and `http://example.com/php-source` can be used with a DAV client to manipulate them. Dav Directive ------------- | | | | --- | --- | | Description: | Enable WebDAV HTTP methods | | Syntax: | ``` Dav On|Off|provider-name ``` | | Default: | ``` Dav Off ``` | | Context: | directory | | Status: | Extension | | Module: | mod\_dav | Use the `Dav` directive to enable the WebDAV HTTP methods for the given container: ``` <Location "/foo"> Dav On </Location> ``` The value `On` is actually an alias for the default provider `filesystem` which is served by the `<mod_dav_fs>` module. Note, that once you have DAV enabled for some location, it *cannot* be disabled for sublocations. For a complete configuration example have a look at the [section above](#example). Do not enable WebDAV until you have secured your server. Otherwise everyone will be able to distribute files on your system. DavDepthInfinity Directive -------------------------- | | | | --- | --- | | Description: | Allow PROPFIND, Depth: Infinity requests | | Syntax: | ``` DavDepthInfinity on|off ``` | | Default: | ``` DavDepthInfinity off ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_dav | Use the `DavDepthInfinity` directive to allow the processing of `PROPFIND` requests containing the header 'Depth: Infinity'. Because this type of request could constitute a denial-of-service attack, by default it is not allowed. DavMinTimeout Directive ----------------------- | | | | --- | --- | | Description: | Minimum amount of time the server holds a lock on a DAV resource | | Syntax: | ``` DavMinTimeout seconds ``` | | Default: | ``` DavMinTimeout 0 ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_dav | When a client requests a DAV resource lock, it can also specify a time when the lock will be automatically removed by the server. This value is only a request, and the server can ignore it or inform the client of an arbitrary value. Use the `DavMinTimeout` directive to specify, in seconds, the minimum lock timeout to return to a client. Microsoft Web Folders defaults to a timeout of 120 seconds; the `DavMinTimeout` can override this to a higher value (like 600 seconds) to reduce the chance of the client losing the lock due to network latency. ### Example ``` <Location "/MSWord"> DavMinTimeout 600 </Location> ```
programming_docs
apache_http_server Apache Module mod_alias Apache Module mod\_alias ======================== | | | | --- | --- | | Description: | Provides for mapping different parts of the host filesystem in the document tree and for URL redirection | | Status: | Base | | Module Identifier: | alias\_module | | Source File: | mod\_alias.c | ### Summary The directives contained in this module allow for manipulation and control of URLs as requests arrive at the server. The `[Alias](#alias)` and `[ScriptAlias](#scriptalias)` directives are used to map between URLs and filesystem paths. This allows for content which is not directly under the `[DocumentRoot](core#documentroot)` served as part of the web document tree. The `[ScriptAlias](#scriptalias)` directive has the additional effect of marking the target directory as containing only CGI scripts. The `[Redirect](#redirect)` directives are used to instruct clients to make a new request with a different URL. They are often used when a resource has moved to a new location. When the `[Alias](#alias)`, `[ScriptAlias](#scriptalias)` and `[Redirect](#redirect)` directives are used within a `[<Location>](core#location)` or `[<LocationMatch>](core#locationmatch)` section, [expression syntax](../expr) can be used to manipulate the destination path or URL. `<mod_alias>` is designed to handle simple URL manipulation tasks. For more complicated tasks such as manipulating the query string, use the tools provided by `<mod_rewrite>`. Order of Processing ------------------- Aliases and Redirects occurring in different contexts are processed like other directives according to standard [merging rules](../sections#mergin). But when multiple Aliases or Redirects occur in the same context (for example, in the same `[<VirtualHost>](core#virtualhost)` section) they are processed in a particular order. First, all Redirects are processed before Aliases are processed, and therefore a request that matches a `[Redirect](#redirect)` or `[RedirectMatch](#redirectmatch)` will never have Aliases applied. Second, the Aliases and Redirects are processed in the order they appear in the configuration files, with the first match taking precedence. For this reason, when two or more of these directives apply to the same sub-path, you must list the most specific path first in order for all the directives to have an effect. For example, the following configuration will work as expected: ``` Alias "/foo/bar" "/baz" Alias "/foo" "/gaq" ``` But if the above two directives were reversed in order, the `/foo` `[Alias](#alias)` would always match before the `/foo/bar` `[Alias](#alias)`, so the latter directive would be ignored. When the `[Alias](#alias)`, `[ScriptAlias](#scriptalias)` and `[Redirect](#redirect)` directives are used within a `[<Location>](core#location)` or `[<LocationMatch>](core#locationmatch)` section, these directives will take precedence over any globally defined `[Alias](#alias)`, `[ScriptAlias](#scriptalias)` and `[Redirect](#redirect)` directives. Alias Directive --------------- | | | | --- | --- | | Description: | Maps URLs to filesystem locations | | Syntax: | ``` Alias [URL-path] file-path|directory-path ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_alias | The `Alias` directive allows documents to be stored in the local filesystem other than under the `[DocumentRoot](core#documentroot)`. URLs with a (%-decoded) path beginning with URL-path will be mapped to local files beginning with directory-path. The URL-path is case-sensitive, even on case-insensitive file systems. ``` Alias "/image" "/ftp/pub/image" ``` A request for `http://example.com/image/foo.gif` would cause the server to return the file `/ftp/pub/image/foo.gif`. Only complete path segments are matched, so the above alias would not match a request for `http://example.com/imagefoo.gif`. For more complex matching using regular expressions, see the `[AliasMatch](#aliasmatch)` directive. Note that if you include a trailing / on the URL-path then the server will require a trailing / in order to expand the alias. That is, if you use ``` Alias "/icons/" "/usr/local/apache/icons/" ``` then the URL `/icons` will not be aliased, as it lacks that trailing /. Likewise, if you omit the slash on the URL-path then you must also omit it from the file-path. Note that you may need to specify additional `[<Directory>](core#directory)` sections which cover the *destination* of aliases. Aliasing occurs before `[<Directory>](core#directory)` sections are checked, so only the destination of aliases are affected. (Note however `[<Location>](core#location)` sections are run through once before aliases are performed, so they will apply.) In particular, if you are creating an `Alias` to a directory outside of your `[DocumentRoot](core#documentroot)`, you may need to explicitly permit access to the target directory. ``` Alias "/image" "/ftp/pub/image" <Directory "/ftp/pub/image"> Require all granted </Directory> ``` Any number slashes in the URL-path parameter matches any number of slashes in the requested URL-path. If the `Alias` directive is used within a `[<Location>](core#location)` or `[<LocationMatch>](core#locationmatch)` section the URL-path is omitted, and the file-path is interpreted using [expression syntax](../expr). This syntax is available in Apache 2.4.19 and later. ``` <Location "/image"> Alias "/ftp/pub/image" </Location> <LocationMatch "/error/(?<NUMBER>[0-9]+)"> Alias "/usr/local/apache/errors/%{env:MATCH_NUMBER}.html" </LocationMatch> ``` AliasMatch Directive -------------------- | | | | --- | --- | | Description: | Maps URLs to filesystem locations using regular expressions | | Syntax: | ``` AliasMatch regex file-path|directory-path ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_alias | This directive is equivalent to `[Alias](#alias)`, but makes use of [regular expressions](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"), instead of simple prefix matching. The supplied regular expression is matched against the URL-path, and if it matches, the server will substitute any parenthesized matches into the given string and use it as a filename. For example, to activate the `/icons` directory, one might use: ``` AliasMatch "^/icons(/|$)(.*)" "/usr/local/apache/icons$1$2" ``` The full range of [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") power is available. For example, it is possible to construct an alias with case-insensitive matching of the URL-path: ``` AliasMatch "(?i)^/image(.*)" "/ftp/pub/image$1" ``` One subtle difference between `[Alias](#alias)` and `[AliasMatch](#aliasmatch)` is that `[Alias](#alias)` will automatically copy any additional part of the URI, past the part that matched, onto the end of the file path on the right side, while `[AliasMatch](#aliasmatch)` will not. This means that in almost all cases, you will want the regular expression to match the entire request URI from beginning to end, and to use substitution on the right side. In other words, just changing `[Alias](#alias)` to `[AliasMatch](#aliasmatch)` will not have the same effect. At a minimum, you need to add `^` to the beginning of the regular expression and add `(.*)$` to the end, and add `$1` to the end of the replacement. For example, suppose you want to replace this with AliasMatch: ``` Alias "/image/" "/ftp/pub/image/" ``` This is NOT equivalent - don't do this! This will send all requests that have /image/ anywhere in them to /ftp/pub/image/: ``` AliasMatch "/image/" "/ftp/pub/image/" ``` This is what you need to get the same effect: ``` AliasMatch "^/image/(.*)$" "/ftp/pub/image/$1" ``` Of course, there's no point in using `[AliasMatch](#aliasmatch)` where `[Alias](#alias)` would work. `[AliasMatch](#aliasmatch)` lets you do more complicated things. For example, you could serve different kinds of files from different directories: ``` AliasMatch "^/image/(.*)\.jpg$" "/files/jpg.images/$1.jpg" AliasMatch "^/image/(.*)\.gif$" "/files/gif.images/$1.gif" ``` Multiple leading slashes in the requested URL are discarded by the server before directives from this module compares against the requested URL-path. Redirect Directive ------------------ | | | | --- | --- | | Description: | Sends an external redirect asking the client to fetch a different URL | | Syntax: | ``` Redirect [status] [URL-path] URL ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_alias | The `Redirect` directive maps an old URL into a new one by asking the client to refetch the resource at the new location. The old *URL-path* is a case-sensitive (%-decoded) path beginning with a slash. A relative path is not allowed. The new *URL* may be either an absolute URL beginning with a scheme and hostname, or a URL-path beginning with a slash. In this latter case the scheme and hostname of the current server will be added. Then any request beginning with *URL-path* will return a redirect request to the client at the location of the target *URL*. Additional path information beyond the matched *URL-path* will be appended to the target URL. ``` # Redirect to a URL on a different host Redirect "/service" "http://foo2.example.com/service" # Redirect to a URL on the same host Redirect "/one" "/two" ``` If the client requests `http://example.com/service/foo.txt`, it will be told to access `http://foo2.example.com/service/foo.txt` instead. This includes requests with `GET` parameters, such as `http://example.com/service/foo.pl?q=23&a=42`, it will be redirected to `http://foo2.example.com/service/foo.pl?q=23&a=42`. Note that `POST`s will be discarded. Only complete path segments are matched, so the above example would not match a request for `http://example.com/servicefoo.txt`. For more complex matching using the [expression syntax](../expr), omit the URL-path argument as described below. Alternatively, for matching using regular expressions, see the `[RedirectMatch](#redirectmatch)` directive. **Note** `Redirect` directives take precedence over `[Alias](#alias)` and `[ScriptAlias](#scriptalias)` directives, irrespective of their ordering in the configuration file. `Redirect` directives inside a Location take precedence over `Redirect` and `[Alias](#alias)` directives with an URL-path. If no status argument is given, the redirect will be "temporary" (HTTP status 302). This indicates to the client that the resource has moved temporarily. The status argument can be used to return other HTTP status codes: permanent Returns a permanent redirect status (301) indicating that the resource has moved permanently. temp Returns a temporary redirect status (302). This is the default. seeother Returns a "See Other" status (303) indicating that the resource has been replaced. gone Returns a "Gone" status (410) indicating that the resource has been permanently removed. When this status is used the URL argument should be omitted. Other status codes can be returned by giving the numeric status code as the value of status. If the status is between 300 and 399, the URL argument must be present. If the status is *not* between 300 and 399, the URL argument must be omitted. The status must be a valid HTTP status code, known to the Apache HTTP Server (see the function `send_error_response` in http\_protocol.c). ``` Redirect permanent "/one" "http://example.com/two" Redirect 303 "/three" "http://example.com/other" ``` If the `Redirect` directive is used within a `[<Location>](core#location)` or `[<LocationMatch>](core#locationmatch)` section with the URL-path omitted, then the URL parameter will be interpreted using [expression syntax](../expr). This syntax is available in Apache 2.4.19 and later. ``` <Location "/one"> Redirect permanent "http://example.com/two" </Location> <Location "/three"> Redirect 303 "http://example.com/other" </Location> <LocationMatch "/error/(?<NUMBER>[0-9]+)"> Redirect permanent "http://example.com/errors/%{env:MATCH_NUMBER}.html" </LocationMatch> ``` RedirectMatch Directive ----------------------- | | | | --- | --- | | Description: | Sends an external redirect based on a regular expression match of the current URL | | Syntax: | ``` RedirectMatch [status] regex URL ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_alias | This directive is equivalent to `[Redirect](#redirect)`, but makes use of [regular expressions](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"), instead of simple prefix matching. The supplied regular expression is matched against the URL-path, and if it matches, the server will substitute any parenthesized matches into the given string and use it as a filename. For example, to redirect all GIF files to like-named JPEG files on another server, one might use: ``` RedirectMatch "(.*)\.gif$" "http://other.example.com$1.jpg" ``` The considerations related to the difference between `[Alias](#alias)` and `[AliasMatch](#aliasmatch)` also apply to the difference between `[Redirect](#redirect)` and `[RedirectMatch](#redirectmatch)`. See `[AliasMatch](#aliasmatch)` for details. RedirectPermanent Directive --------------------------- | | | | --- | --- | | Description: | Sends an external permanent redirect asking the client to fetch a different URL | | Syntax: | ``` RedirectPermanent URL-path URL ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_alias | This directive makes the client know that the Redirect is permanent (status 301). Exactly equivalent to `Redirect permanent`. RedirectTemp Directive ---------------------- | | | | --- | --- | | Description: | Sends an external temporary redirect asking the client to fetch a different URL | | Syntax: | ``` RedirectTemp URL-path URL ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_alias | This directive makes the client know that the Redirect is only temporary (status 302). Exactly equivalent to `Redirect temp`. ScriptAlias Directive --------------------- | | | | --- | --- | | Description: | Maps a URL to a filesystem location and designates the target as a CGI script | | Syntax: | ``` ScriptAlias [URL-path] file-path|directory-path ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_alias | The `ScriptAlias` directive has the same behavior as the `[Alias](#alias)` directive, except that in addition it marks the target directory as containing CGI scripts that will be processed by `<mod_cgi>`'s cgi-script handler. URLs with a case-sensitive (%-decoded) path beginning with URL-path will be mapped to scripts beginning with the second argument, which is a full pathname in the local filesystem. ``` ScriptAlias "/cgi-bin/" "/web/cgi-bin/" ``` A request for `http://example.com/cgi-bin/foo` would cause the server to run the script `/web/cgi-bin/foo`. This configuration is essentially equivalent to: ``` Alias "/cgi-bin/" "/web/cgi-bin/" <Location "/cgi-bin"> SetHandler cgi-script Options +ExecCGI </Location> ``` `ScriptAlias` can also be used in conjunction with a script or handler you have. For example: ``` ScriptAlias "/cgi-bin/" "/web/cgi-handler.pl" ``` In this scenario all files requested in `/cgi-bin/` will be handled by the file you have configured, this allows you to use your own custom handler. You may want to use this as a wrapper for CGI so that you can add content, or some other bespoke action. It is safer to avoid placing CGI scripts under the `[DocumentRoot](core#documentroot)` in order to avoid accidentally revealing their source code if the configuration is ever changed. The `ScriptAlias` makes this easy by mapping a URL and designating CGI scripts at the same time. If you do choose to place your CGI scripts in a directory already accessible from the web, do not use `ScriptAlias`. Instead, use `[<Directory>](core#directory)`, `[SetHandler](core#sethandler)`, and `[Options](core#options)` as in: ``` <Directory "/usr/local/apache2/htdocs/cgi-bin"> SetHandler cgi-script Options ExecCGI </Directory> ``` This is necessary since multiple URL-paths can map to the same filesystem location, potentially bypassing the `ScriptAlias` and revealing the source code of the CGI scripts if they are not restricted by a `[Directory](core#directory)` section. If the `ScriptAlias` directive is used within a `[<Location>](core#location)` or `[<LocationMatch>](core#locationmatch)` section with the URL-path omitted, then the URL parameter will be interpreted using [expression syntax](../expr). This syntax is available in Apache 2.4.19 and later. ``` <Location "/cgi-bin"> ScriptAlias "/web/cgi-bin/" </Location> <LocationMatch "/cgi-bin/errors/(?<NUMBER>[0-9]+)"> ScriptAlias "/web/cgi-bin/errors/%{env:MATCH_NUMBER}.cgi" </LocationMatch> ``` ### See also * [CGI Tutorial](../howto/cgi) ScriptAliasMatch Directive -------------------------- | | | | --- | --- | | Description: | Maps a URL to a filesystem location using a regular expression and designates the target as a CGI script | | Syntax: | ``` ScriptAliasMatch regex file-path|directory-path ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_alias | This directive is equivalent to `[ScriptAlias](#scriptalias)`, but makes use of [regular expressions](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"), instead of simple prefix matching. The supplied regular expression is matched against the URL-path, and if it matches, the server will substitute any parenthesized matches into the given string and use it as a filename. For example, to activate the standard `/cgi-bin`, one might use: ``` ScriptAliasMatch "^/cgi-bin(.*)" "/usr/local/apache/cgi-bin$1" ``` As for AliasMatch, the full range of [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#rexex "see glossary") power is available. For example, it is possible to construct an alias with case-insensitive matching of the URL-path: ``` ScriptAliasMatch "(?i)^/cgi-bin(.*)" "/usr/local/apache/cgi-bin$1" ``` The considerations related to the difference between `[Alias](#alias)` and `[AliasMatch](#aliasmatch)` also apply to the difference between `[ScriptAlias](#scriptalias)` and `[ScriptAliasMatch](#scriptaliasmatch)`. See `[AliasMatch](#aliasmatch)` for details. apache_http_server Apache MPM Common Directives Apache MPM Common Directives ============================ | | | | --- | --- | | Description: | A collection of directives that are implemented by more than one multi-processing module (MPM) | | Status: | MPM | CoreDumpDirectory Directive --------------------------- | | | | --- | --- | | Description: | Directory where Apache HTTP Server attempts to switch before dumping core | | Syntax: | ``` CoreDumpDirectory directory ``` | | Default: | ``` See usage for the default setting ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>` | This controls the directory to which Apache httpd attempts to switch before dumping core. If your operating system is configured to create core files in the working directory of the crashing process, `CoreDumpDirectory` is necessary to change working directory from the default `[ServerRoot](core#serverroot)` directory, which should not be writable by the user the server runs as. If you want a core dump for debugging, you can use this directive to place it in a different location. This directive has no effect if your operating system is not configured to write core files to the working directory of the crashing processes. **Security note for Linux systems** Using this directive on Linux may allow other processes on the system (if running with similar privileges, such as CGI scripts) to attach to httpd children via the `ptrace` system call. This may make weaken the protection from certain security attacks. It is not recommended to use this directive on production systems. **Core Dumps on Linux** If Apache httpd starts as root and switches to another user, the Linux kernel *disables* core dumps even if the directory is writable for the process. Apache httpd (2.0.46 and later) reenables core dumps on Linux 2.4 and beyond, but only if you explicitly configure a `CoreDumpDirectory`. **Core Dumps on BSD** To enable core-dumping of suid-executables on BSD-systems (such as FreeBSD), set `kern.sugid_coredump` to 1. **Specific signals** `CoreDumpDirectory` processing only occurs for a select set of fatal signals: SIGFPE, SIGILL, SIGABORT, SIGSEGV, and SIGBUS. On some operating systems, SIGQUIT also results in a core dump but does not go through `CoreDumpDirectory` or `EnableExceptionHook` processing, so the core location is dictated entirely by the operating system. EnableExceptionHook Directive ----------------------------- | | | | --- | --- | | Description: | Enables a hook that runs exception handlers after a crash | | Syntax: | ``` EnableExceptionHook On|Off ``` | | Default: | ``` EnableExceptionHook Off ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>` | For safety reasons this directive is only available if the server was configured with the `--enable-exception-hook` option. It enables a hook that allows external modules to plug in and do something after a child crashed. There are already two modules, `mod_whatkilledus` and `mod_backtrace` that make use of this hook. Please have a look at Jeff Trawick's [EnableExceptionHook site](https://emptyhammock.com/projects/httpd/diag/) for more information about these. GracefulShutdownTimeout Directive --------------------------------- | | | | --- | --- | | Description: | Specify a timeout after which a gracefully shutdown server will exit. | | Syntax: | ``` GracefulShutdownTimeout seconds ``` | | Default: | ``` GracefulShutdownTimeout 0 ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>` | | Compatibility: | Available in version 2.2 and later | The `GracefulShutdownTimeout` specifies how many seconds after receiving a "graceful-stop" signal, a server should continue to run, handling the existing connections. Setting this value to zero means that the server will wait indefinitely until all remaining requests have been fully served. Listen Directive ---------------- | | | | --- | --- | | Description: | IP addresses and ports that the server listens to | | Syntax: | ``` Listen [IP-address:]portnumber [protocol] ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>`, `<mpm_winnt>`, `<mpm_netware>`, `<mpmt_os2>` | | Compatibility: | The protocol argument was added in 2.1.5 | The `Listen` directive instructs Apache httpd to listen to only specific IP addresses or ports; by default it responds to requests on all IP interfaces. `Listen` is now a required directive. If it is not in the config file, the server will fail to start. This is a change from previous versions of Apache httpd. The `Listen` directive tells the server to accept incoming requests on the specified port or address-and-port combination. If only a port number is specified, the server listens to the given port on all interfaces. If an IP address is given as well as a port, the server will listen on the given port and interface. Multiple `Listen` directives may be used to specify a number of addresses and ports to listen to. The server will respond to requests from any of the listed addresses and ports. For example, to make the server accept connections on both port 80 and port 8000, use: ``` Listen 80 Listen 8000 ``` To make the server accept connections on two specified interfaces and port numbers, use ``` Listen 192.170.2.1:80 Listen 192.170.2.5:8000 ``` IPv6 addresses must be surrounded in square brackets, as in the following example: ``` Listen [2001:db8::a00:20ff:fea7:ccea]:80 ``` The optional protocol argument is not required for most configurations. If not specified, `https` is the default for port 443 and `http` the default for all other ports. The protocol is used to determine which module should handle a request, and to apply protocol specific optimizations with the `[AcceptFilter](core#acceptfilter)` directive. You only need to set the protocol if you are running on non-standard ports. For example, running an `https` site on port 8443: ``` Listen 192.170.2.1:8443 https ``` **Error condition** Multiple `Listen` directives for the same ip address and port will result in an `Address already in use` error message. ### See also * [DNS Issues](../dns-caveats) * [Setting which addresses and ports Apache HTTP Server uses](../bind) * [Further discussion of the `Address already in use` error message, including other causes.](http://wiki.apache.org/httpd/CouldNotBindToAddress) ListenBackLog Directive ----------------------- | | | | --- | --- | | Description: | Maximum length of the queue of pending connections | | Syntax: | ``` ListenBackLog backlog ``` | | Default: | ``` ListenBackLog 511 ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>`, `<mpm_winnt>`, `<mpm_netware>`, `<mpmt_os2>` | The maximum length of the queue of pending connections. Generally no tuning is needed or desired; however on some systems, it is desirable to increase this when under a TCP SYN flood attack. See the backlog parameter to the `listen(2)` system call. This will often be limited to a smaller number by the operating system. This varies from OS to OS. Also note that many OSes do not use exactly what is specified as the backlog, but use a number based on (but normally larger than) what is set. ListenCoresBucketsRatio Directive --------------------------------- | | | | --- | --- | | Description: | Ratio between the number of CPU cores (online) and the number of listeners' buckets | | Syntax: | ``` ListenCoresBucketsRatio ratio ``` | | Default: | ``` ListenCoresBucketsRatio 0 (disabled) ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>` | | Compatibility: | Available in Apache HTTP Server 2.4.17, with a kernel supporting the socket option `SO_REUSEPORT` and distributing new connections evenly across listening processes' (or threads') sockets using it (eg. Linux 3.9 and later, but not the current implementations of `SO_REUSEPORT` in \*BSDs. | A ratio between the number of (online) CPU cores and the number of listeners' buckets can be used to make Apache HTTP Server create `num_cpu_cores / ratio` listening buckets, each containing its own `[Listen](#listen)`-ing socket(s) on the same port(s), and then make each child handle a single bucket (with round-robin distribution of the buckets at children creation time). **Meaning of "online" CPU core** On Linux (and also BSD) a CPU core can be turned on/off if [Hotplug](https://www.kernel.org/doc/Documentation/cpu-hotplug.txt) is configured, therefore `ListenCoresBucketsRatio` needs to take this parameter into account while calculating the number of buckets to create. `ListenCoresBucketsRatio` can improve the scalability when accepting new connections is/becomes the bottleneck. On systems with a large number of CPU cores, enabling this feature has been tested to show significant performances improvement and shorter responses time. There must be at least twice the number of CPU cores than the configured ratio for this to be active. The recommended ratio is `8`, hence at least `16` cores should be available at runtime when this value is used. The right ratio to obtain maximum performance needs to be calculated for each target system, testing multiple values and observing the variations in your key performance metrics. This directive influences the calculation of the `[MinSpareThreads](#minsparethreads)` and `[MaxSpareThreads](#maxsparethreads)` lower bound values. The number of children processes needs to be a multiple of the number of buckets to optimally accept connections. **Multiple `Listen`ers or Apache HTTP servers on the same IP address and port** Setting the `SO_REUSEPORT` option on the listening socket(s) consequently allows multiple processes (sharing the same `EUID`, e.g. `root`) to bind to the the same IP address and port, without the binding error raised by the system in the usual case. This also means that multiple instances of Apache httpd configured on a same `IP:port` and with a positive `ListenCoresBucketsRatio` would start without an error too, and then run with incoming connections evenly distributed across both instances (this is NOT a recommendation or a sensible usage in any case, but just a notice that it would prevent such possible issues to be detected). Within the same instance, Apache httpd will check and fail to start if multiple `Listen` directives on the exact same IP (or hostname) and port are configured, thus avoiding the creation of some duplicated buckets which would be useless and kill performances. However it can't (and won't try harder to) catch all the possible overlapping cases (like a hostname resolving to an IP used elsewhere). MaxConnectionsPerChild Directive -------------------------------- | | | | --- | --- | | Description: | Limit on the number of connections that an individual child server will handle during its life | | Syntax: | ``` MaxConnectionsPerChild number ``` | | Default: | ``` MaxConnectionsPerChild 0 ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>`, `<mpm_winnt>`, `<mpm_netware>`, `<mpmt_os2>` | | Compatibility: | Available Apache HTTP Server 2.3.9 and later. The old name `MaxRequestsPerChild` is still supported. | The `MaxConnectionsPerChild` directive sets the limit on the number of connections that an individual child server process will handle. After `MaxConnectionsPerChild` connections, the child process will die. If `MaxConnectionsPerChild` is `0`, then the process will never expire. Setting `MaxConnectionsPerChild` to a non-zero value limits the amount of memory that a process can consume by (accidental) memory leakage. MaxMemFree Directive -------------------- | | | | --- | --- | | Description: | Maximum amount of memory that the main allocator is allowed to hold without calling `free()` | | Syntax: | ``` MaxMemFree KBytes ``` | | Default: | ``` MaxMemFree 2048 ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>`, `<mpm_winnt>`, `<mpm_netware>` | The `MaxMemFree` directive sets the maximum number of free Kbytes that every allocator is allowed to hold without calling `free()`. In threaded MPMs, every thread has its own allocator. When set to zero, the threshold will be set to unlimited. MaxRequestWorkers Directive --------------------------- | | | | --- | --- | | Description: | Maximum number of connections that will be processed simultaneously | | Syntax: | ``` MaxRequestWorkers number ``` | | Default: | ``` See usage for details ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>` | The `MaxRequestWorkers` directive sets the limit on the number of simultaneous requests that will be served. Any connection attempts over the `MaxRequestWorkers` limit will normally be queued, up to a number based on the `[ListenBacklog](#listenbacklog)` directive. Once a child process is freed at the end of a different request, the connection will then be serviced. For non-threaded servers (*i.e.*, `<prefork>`), `MaxRequestWorkers` translates into the maximum number of child processes that will be launched to serve requests. The default value is `256`; to increase it, you must also raise `[ServerLimit](#serverlimit)`. For threaded and hybrid servers (*e.g.* `<event>` or `<worker>`), `MaxRequestWorkers` restricts the total number of threads that will be available to serve clients. For hybrid MPMs, the default value is `16` (`[ServerLimit](#serverlimit)`) multiplied by the value of `25` (`[ThreadsPerChild](#threadsperchild)`). Therefore, to increase `MaxRequestWorkers` to a value that requires more than 16 processes, you must also raise `[ServerLimit](#serverlimit)`. `MaxRequestWorkers` was called `MaxClients` before version 2.3.13. The old name is still supported. MaxSpareThreads Directive ------------------------- | | | | --- | --- | | Description: | Maximum number of idle threads | | Syntax: | ``` MaxSpareThreads number ``` | | Default: | ``` See usage for details ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<mpm_netware>`, `<mpmt_os2>` | Maximum number of idle threads. Different MPMs deal with this directive differently. For `<worker>` and `<event>`, the default is `MaxSpareThreads 250`. These MPMs deal with idle threads on a server-wide basis. If there are too many idle threads in the server, then child processes are killed until the number of idle threads is less than this number. Additional processes/threads might be created if `[ListenCoresBucketsRatio](#listencoresbucketsratio)` is enabled. For `<mpm_netware>` the default is `MaxSpareThreads 100`. Since this MPM runs a single-process, the spare thread count is also server-wide. `<mpmt_os2>` works similar to `<mpm_netware>`. For `<mpmt_os2>` the default value is `10`. **Restrictions** The range of the `MaxSpareThreads` value is restricted. Apache httpd will correct the given value automatically according to the following rules: * `<mpm_netware>` wants the value to be greater than `[MinSpareThreads](#minsparethreads)`. * For `<worker>` and `<event>`, the value must be greater or equal to the sum of `[MinSpareThreads](#minsparethreads)` and `[ThreadsPerChild](#threadsperchild)`. ### See also * `[MinSpareThreads](#minsparethreads)` * `[StartServers](#startservers)` * `[MaxSpareServers](prefork#maxspareservers)` MinSpareThreads Directive ------------------------- | | | | --- | --- | | Description: | Minimum number of idle threads available to handle request spikes | | Syntax: | ``` MinSpareThreads number ``` | | Default: | ``` See usage for details ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<mpm_netware>`, `<mpmt_os2>` | Minimum number of idle threads to handle request spikes. Different MPMs deal with this directive differently. `<worker>` and `<event>` use a default of `MinSpareThreads 75` and deal with idle threads on a server-wide basis. If there aren't enough idle threads in the server, then child processes are created until the number of idle threads is greater than number. Additional processes/threads might be created if `[ListenCoresBucketsRatio](#listencoresbucketsratio)` is enabled. `<mpm_netware>` uses a default of `MinSpareThreads 10` and, since it is a single-process MPM, tracks this on a server-wide basis. `<mpmt_os2>` works similar to `<mpm_netware>`. For `<mpmt_os2>` the default value is `5`. ### See also * `[MaxSpareThreads](#maxsparethreads)` * `[StartServers](#startservers)` * `[MinSpareServers](prefork#minspareservers)` PidFile Directive ----------------- | | | | --- | --- | | Description: | File where the server records the process ID of the daemon | | Syntax: | ``` PidFile filename ``` | | Default: | ``` PidFile logs/httpd.pid ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>`, `<mpm_winnt>`, `<mpmt_os2>` | The `PidFile` directive sets the file to which the server records the process id of the daemon. If the filename is not absolute, then it is assumed to be relative to the `[ServerRoot](core#serverroot)`. ### Example ``` PidFile /var/run/apache.pid ``` It is often useful to be able to send the server a signal, so that it closes and then re-opens its `[ErrorLog](core#errorlog)` and `[TransferLog](mod_log_config#transferlog)`, and re-reads its configuration files. This is done by sending a SIGHUP (kill -1) signal to the process id listed in the `PidFile`. The `PidFile` is subject to the same warnings about log file placement and [security](../misc/security_tips#serverroot). **Note** As of Apache HTTP Server 2, we recommended that you only use the `[apachectl](../programs/apachectl)` script, or the init script that your OS provides, for (re-)starting or stopping the server. ReceiveBufferSize Directive --------------------------- | | | | --- | --- | | Description: | TCP receive buffer size | | Syntax: | ``` ReceiveBufferSize bytes ``` | | Default: | ``` ReceiveBufferSize 0 ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>`, `<mpm_winnt>`, `<mpm_netware>`, `<mpmt_os2>` | The server will set the TCP receive buffer size to the number of bytes specified. If set to the value of `0`, the server will use the OS default. ScoreBoardFile Directive ------------------------ | | | | --- | --- | | Description: | Location of the file used to store coordination data for the child processes | | Syntax: | ``` ScoreBoardFile file-path ``` | | Default: | ``` ScoreBoardFile logs/apache_runtime_status ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>`, `<mpm_winnt>` | Apache HTTP Server uses a scoreboard to communicate between its parent and child processes. Some architectures require a file to facilitate this communication. If the file is left unspecified, Apache httpd first attempts to create the scoreboard entirely in memory (using anonymous shared memory) and, failing that, will attempt to create the file on disk (using file-based shared memory). Specifying this directive causes Apache httpd to always create the file on the disk. ### Example ``` ScoreBoardFile /var/run/apache_runtime_status ``` File-based shared memory is useful for third-party applications that require direct access to the scoreboard. If you use a `ScoreBoardFile`, then you may see improved speed by placing it on a RAM disk. But be careful that you heed the same warnings about log file placement and [security](../misc/security_tips). ### See also * [Stopping and Restarting Apache HTTP Server](../stopping) SendBufferSize Directive ------------------------ | | | | --- | --- | | Description: | TCP buffer size | | Syntax: | ``` SendBufferSize bytes ``` | | Default: | ``` SendBufferSize 0 ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>`, `<mpm_winnt>`, `<mpm_netware>`, `<mpmt_os2>` | Sets the server's TCP send buffer size to the number of bytes specified. It is often useful to set this past the OS's standard default value on high speed, high latency connections (*i.e.*, 100ms or so, such as transcontinental fast pipes). If set to the value of `0`, the server will use the default value provided by your OS. Further configuration of your operating system may be required to elicit better performance on high speed, high latency connections. On some operating systems, changes in TCP behavior resulting from a larger `SendBufferSize` may not be seen unless `[EnableSendfile](core#enablesendfile)` is set to OFF. This interaction applies only to static files. ServerLimit Directive --------------------- | | | | --- | --- | | Description: | Upper limit on configurable number of processes | | Syntax: | ``` ServerLimit number ``` | | Default: | ``` See usage for details ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>` | For the `<prefork>` MPM, this directive sets the maximum configured value for `[MaxRequestWorkers](#maxrequestworkers)` for the lifetime of the Apache httpd process. For the `<worker>` and `<event>` MPMs, this directive in combination with `[ThreadLimit](#threadlimit)` sets the maximum configured value for `[MaxRequestWorkers](#maxrequestworkers)` for the lifetime of the Apache httpd process. For the `<event>` MPM, this directive also defines how many old server processes may keep running and finish processing open connections. Any attempts to change this directive during a restart will be ignored, but `[MaxRequestWorkers](#maxrequestworkers)` can be modified during a restart. Special care must be taken when using this directive. If `ServerLimit` is set to a value much higher than necessary, extra, unused shared memory will be allocated. If both `ServerLimit` and `[MaxRequestWorkers](#maxrequestworkers)` are set to values higher than the system can handle, Apache httpd may not start or the system may become unstable. With the `<prefork>` MPM, use this directive only if you need to set `[MaxRequestWorkers](#maxrequestworkers)` higher than 256 (default). Do not set the value of this directive any higher than what you might want to set `[MaxRequestWorkers](#maxrequestworkers)` to. With `<worker>`, use this directive only if your `[MaxRequestWorkers](#maxrequestworkers)` and `[ThreadsPerChild](#threadsperchild)` settings require more than 16 server processes (default). Do not set the value of this directive any higher than the number of server processes required by what you may want for `[MaxRequestWorkers](#maxrequestworkers)` and `[ThreadsPerChild](#threadsperchild)`. With `<event>`, increase this directive if the process number defined by your `[MaxRequestWorkers](#maxrequestworkers)` and `[ThreadsPerChild](#threadsperchild)` settings, plus the number of gracefully shutting down processes, is more than 16 server processes (default). **Note** There is a hard limit of `ServerLimit 20000` compiled into the server (for the `<prefork>` MPM 200000). This is intended to avoid nasty effects caused by typos. To increase it even further past this limit, you will need to modify the value of MAX\_SERVER\_LIMIT in the mpm source file and rebuild the server. ### See also * [Stopping and Restarting Apache HTTP Server](../stopping) StartServers Directive ---------------------- | | | | --- | --- | | Description: | Number of child server processes created at startup | | Syntax: | ``` StartServers number ``` | | Default: | ``` See usage for details ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<prefork>`, `<mpmt_os2>` | The `StartServers` directive sets the number of child server processes created on startup. As the number of processes is dynamically controlled depending on the load, (see `[MinSpareThreads](#minsparethreads)`, `[MaxSpareThreads](#maxsparethreads)`, `[MinSpareServers](prefork#minspareservers)`, `[MaxSpareServers](prefork#maxspareservers)`) there is usually little reason to adjust this parameter. The default value differs from MPM to MPM. `<worker>` and `<event>` default to `StartServers 3`; `<prefork>` defaults to `5`; `<mpmt_os2>` defaults to `2`. StartThreads Directive ---------------------- | | | | --- | --- | | Description: | Number of threads created on startup | | Syntax: | ``` StartThreads number ``` | | Default: | ``` See usage for details ``` | | Context: | server config | | Status: | MPM | | Module: | `mpm_netware` | Number of threads created on startup. As the number of threads is dynamically controlled depending on the load, (see `[MinSpareThreads](#minsparethreads)`, `[MaxSpareThreads](#maxsparethreads)`, `[MinSpareServers](prefork#minspareservers)`, `[MaxSpareServers](prefork#maxspareservers)`) there is usually little reason to adjust this parameter. For `<mpm_netware>` the default is `StartThreads 50` and, since there is only a single process, this is the total number of threads created at startup to serve requests. ThreadLimit Directive --------------------- | | | | --- | --- | | Description: | Sets the upper limit on the configurable number of threads per child process | | Syntax: | ``` ThreadLimit number ``` | | Default: | ``` See usage for details ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<mpm_winnt>` | This directive sets the maximum configured value for `[ThreadsPerChild](#threadsperchild)` for the lifetime of the Apache httpd process. Any attempts to change this directive during a restart will be ignored, but `[ThreadsPerChild](#threadsperchild)` can be modified during a restart up to the value of this directive. Special care must be taken when using this directive. If `ThreadLimit` is set to a value much higher than `[ThreadsPerChild](#threadsperchild)`, extra unused shared memory will be allocated. If both `ThreadLimit` and `[ThreadsPerChild](#threadsperchild)` are set to values higher than the system can handle, Apache httpd may not start or the system may become unstable. Do not set the value of this directive any higher than your greatest predicted setting of `[ThreadsPerChild](#threadsperchild)` for the current run of Apache httpd. The default value for `ThreadLimit` is `1920` when used with `<mpm_winnt>` and `64` when used with the others. **Note** There is a hard limit of `ThreadLimit 20000` (or `ThreadLimit 100000` with `<event>`, `ThreadLimit 15000` with `<mpm_winnt>`) compiled into the server. This is intended to avoid nasty effects caused by typos. To increase it even further past this limit, you will need to modify the value of MAX\_THREAD\_LIMIT in the mpm source file and rebuild the server. ThreadsPerChild Directive ------------------------- | | | | --- | --- | | Description: | Number of threads created by each child process | | Syntax: | ``` ThreadsPerChild number ``` | | Default: | ``` See usage for details ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<mpm_winnt>` | This directive sets the number of threads created by each child process. The child creates these threads at startup and never creates more. If using an MPM like `<mpm_winnt>`, where there is only one child process, this number should be high enough to handle the entire load of the server. If using an MPM like `<worker>`, where there are multiple child processes, the *total* number of threads should be high enough to handle the common load on the server. The default value for `ThreadsPerChild` is `64` when used with `<mpm_winnt>` and `25` when used with the others. The value of `ThreadsPerChild` can not exceed the value of `[ThreadLimit](#threadlimit)`. If a higher value is configured, it will be automatically reduced at start-up and a warning will be logged. The relationship between these 2 directives is explained in `[ThreadLimit](#threadlimit)`. ThreadStackSize Directive ------------------------- | | | | --- | --- | | Description: | The size in bytes of the stack used by threads handling client connections | | Syntax: | ``` ThreadStackSize size ``` | | Default: | ``` 65536 on NetWare; varies on other operating systems ``` | | Context: | server config | | Status: | MPM | | Module: | `<event>`, `<worker>`, `<mpm_winnt>`, `<mpm_netware>`, `<mpmt_os2>` | | Compatibility: | Available in Apache HTTP Server 2.1 and later | The `ThreadStackSize` directive sets the size of the stack (for autodata) of threads which handle client connections and call modules to help process those connections. In most cases the operating system default for stack size is reasonable, but there are some conditions where it may need to be adjusted: * On platforms with a relatively small default thread stack size (e.g., HP-UX), Apache httpd may crash when using some third-party modules which use a relatively large amount of autodata storage. Those same modules may have worked fine on other platforms where the default thread stack size is larger. This type of crash is resolved by setting `ThreadStackSize` to a value higher than the operating system default. This type of adjustment is necessary only if the provider of the third-party module specifies that it is required, or if diagnosis of an Apache httpd crash indicates that the thread stack size was too small. * On platforms where the default thread stack size is significantly larger than necessary for the web server configuration, a higher number of threads per child process will be achievable if `ThreadStackSize` is set to a value lower than the operating system default. This type of adjustment should only be made in a test environment which allows the full set of web server processing to be exercised, as there may be infrequent requests which require more stack to process. The minimum required stack size strongly depends on the modules used, but any change in the web server configuration can invalidate the current `ThreadStackSize` setting. * On Linux, this directive can only be used to increase the default stack size, as the underlying system call uses the value as a *minimum* stack size. The (often large) soft limit for `ulimit -s` (8MB if unlimited) is used as the default stack size. It is recommended to not reduce `ThreadStackSize` unless a high number of threads per child process is needed. On some platforms (including Linux), a setting of 128000 is already too low and causes crashes with some common modules.
programming_docs
apache_http_server Apache Module mod_log_forensic Apache Module mod\_log\_forensic ================================ | | | | --- | --- | | Description: | Forensic Logging of the requests made to the server | | Status: | Extension | | Module Identifier: | log\_forensic\_module | | Source File: | mod\_log\_forensic.c | | Compatibility: | `<mod_unique_id>` is no longer required since version 2.1 | ### Summary This module provides for forensic logging of client requests. Logging is done before and after processing a request, so the forensic log contains two log lines for each request. The forensic logger is very strict, which means: * The format is fixed. You cannot modify the logging format at runtime. * If it cannot write its data, the child process exits immediately and may dump core (depending on your `[CoreDumpDirectory](mpm_common#coredumpdirectory)` configuration). The `check_forensic` script, which can be found in the distribution's support directory, may be helpful in evaluating the forensic log output. Forensic Log Format ------------------- Each request is logged two times. The first time is *before* it's processed further (that is, after receiving the headers). The second log entry is written *after* the request processing at the same time where normal logging occurs. In order to identify each request, a unique request ID is assigned. This forensic ID can be cross logged in the normal transfer log using the `%{forensic-id}n` format string. If you're using `<mod_unique_id>`, its generated ID will be used. The first line logs the forensic ID, the request line and all received headers, separated by pipe characters (`|`). A sample line looks like the following (all on one line): ``` +yQtJf8CoAB4AAFNXBIEAAAAA|GET /manual/de/images/down.gif HTTP/1.1|Host:localhost%3a8080|User-Agent:Mozilla/5.0 (X11; U; Linux i686; en-US; rv%3a1.6) Gecko/20040216 Firefox/0.8|Accept:image/png, etc... ``` The plus character at the beginning indicates that this is the first log line of this request. The second line just contains a minus character and the ID again: `-yQtJf8CoAB4AAFNXBIEAAAAA` The `check_forensic` script takes as its argument the name of the logfile. It looks for those `+`/`-` ID pairs and complains if a request was not completed. Security Considerations ----------------------- See the [security tips](../misc/security_tips#serverroot) document for details on why your security could be compromised if the directory where logfiles are stored is writable by anyone other than the user that starts the server. The log files may contain sensitive data such as the contents of `Authorization:` headers (which can contain passwords), so they should not be readable by anyone except the user that starts the server. ForensicLog Directive --------------------- | | | | --- | --- | | Description: | Sets filename of the forensic log | | Syntax: | ``` ForensicLog filename|pipe ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_log\_forensic | The `ForensicLog` directive is used to log requests to the server for forensic analysis. Each log entry is assigned a unique ID which can be associated with the request using the normal `[CustomLog](mod_log_config#customlog)` directive. `<mod_log_forensic>` creates a token called `forensic-id`, which can be added to the transfer log using the `%{forensic-id}n` format string. The argument, which specifies the location to which the logs will be written, can take one of the following two types of values: filename A filename, relative to the `[ServerRoot](core#serverroot)`. pipe The pipe character "`|`", followed by the path to a program to receive the log information on its standard input. The program name can be specified relative to the `[ServerRoot](core#serverroot)` directive. **Security:** If a program is used, then it will be run as the user who started `[httpd](../programs/httpd)`. This will be root if the server was started by root; be sure that the program is secure or switches to a less privileged user. **Note** When entering a file path on non-Unix platforms, care should be taken to make sure that only forward slashes are used even though the platform may allow the use of back slashes. In general it is a good idea to always use forward slashes throughout the configuration files. apache_http_server Apache Module mod_reqtimeout Apache Module mod\_reqtimeout ============================= | | | | --- | --- | | Description: | Set timeout and minimum data rate for receiving requests | | Status: | Extension | | Module Identifier: | reqtimeout\_module | | Source File: | mod\_reqtimeout.c | | Compatibility: | Available in Apache HTTPD 2.2.15 and later | ### Summary This module provides a convenient way to set timeouts and minimum data rates for receiving requests. Should a timeout occur or a data rate be to low, the corresponding connection will be closed by the server. This is logged at `[LogLevel](core#loglevel)` `info`. If needed, the `[LogLevel](core#loglevel)` directive can be tweaked to explicitly log it: ``` LogLevel reqtimeout:info ``` Examples -------- 1. Allow for 5 seconds to complete the TLS handshake, 10 seconds to receive the request headers and 30 seconds for receiving the request body: ``` RequestReadTimeout handshake=5 header=10 body=30 ``` 2. Allow at least 10 seconds to receive the request body. If the client sends data, increase the timeout by 1 second for every 1000 bytes received, with no upper limit for the timeout (except for the limit given indirectly by `[LimitRequestBody](core#limitrequestbody)`): ``` RequestReadTimeout body=10,MinRate=1000 ``` 3. Allow at least 10 seconds to receive the request headers. If the client sends data, increase the timeout by 1 second for every 500 bytes received. But do not allow more than 30 seconds for the request headers: ``` RequestReadTimeout header=10-30,MinRate=500 ``` 4. Usually, a server should have both header and body timeouts configured. If a common configuration is used for http and https virtual hosts, the timeouts should not be set too low: ``` RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500 ``` RequestReadTimeout Directive ---------------------------- | | | | --- | --- | | Description: | Set timeout values for completing the TLS handshake, receiving the request headers and/or body from client. | | Syntax: | ``` RequestReadTimeout [handshake=timeout[-maxtimeout][,MinRate=rate] [header=timeout[-maxtimeout][,MinRate=rate] [body=timeout[-maxtimeout][,MinRate=rate] ``` | | Default: | ``` RequestReadTimeout handshake=0 header=20-40,MinRate=500 body=20,MinRate=500 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_reqtimeout | | Compatibility: | Available in version 2.2.15 and later; defaulted to disabled in version 2.3.14 and earlier. The `handshake` stage is available since version 2.4.39. | This directive can set various timeouts for completing the TLS handshake, receiving the request headers and/or the request body from the client. If the client fails to complete each of these stages within the configured time, a `408 REQUEST TIME OUT` error is sent. For SSL virtual hosts, the `handshake` timeout values is the time needed to do the initial SSL handshake. If the user's browser is configured to query certificate revocation lists and the CRL server is not reachable, the initial SSL handshake may take a significant time until the browser gives up waiting for the CRL. Therefore the `handshake` timeout should take this possible overhead into consideration for SSL virtual hosts (if necessary). The body timeout values include the time needed for SSL renegotiation (if necessary). When an `[AcceptFilter](core#acceptfilter)` is in use (usually the case on Linux and FreeBSD), the socket is not sent to the server process before at least one byte (or the whole request for `httpready`) is received. The handshake and header timeouts configured with `RequestReadTimeout` are only effective after the server process has received the socket. For each of the three timeout stages (handshake, header or body), there are three ways to specify the timeout: * **Fixed timeout value**: `stage=timeout` The time in seconds allowed for completing the whole stage (handshaking, reading all of the request headers or body). A value of 0 means no limit. * **Disable module for a vhost**: ``` handshake=0 header=0 body=0 ``` This disables `<mod_reqtimeout>` completely (note that `handshake=0` is the default already and could be omitted). * **Timeout value that is increased when data is received**: `stage=timeout,MinRate=data_rate` Same as above, but whenever data is received, the timeout value is increased according to the specified minimum data rate (in bytes per second). * **Timeout value that is increased when data is received, with an upper bound**: `stage=timeout-maxtimeout,MinRate=data_rate` Same as above, but the timeout will not be increased above the second value of the specified timeout range. apache_http_server Apache Module mod_proxy_fcgi Apache Module mod\_proxy\_fcgi ============================== | | | | --- | --- | | Description: | FastCGI support module for `<mod_proxy>` | | Status: | Extension | | Module Identifier: | proxy\_fcgi\_module | | Source File: | mod\_proxy\_fcgi.c | | Compatibility: | Available in version 2.3 and later | ### Summary This module *requires* the service of `<mod_proxy>`. It provides support for the [FastCGI](http://www.fastcgi.com/) protocol. Thus, in order to get the ability of handling the `FastCGI` protocol, `<mod_proxy>` and `<mod_proxy_fcgi>` have to be present in the server. Unlike [mod\_fcgid](http://httpd.apache.org/mod_fcgid/) and [mod\_fastcgi](http://www.fastcgi.com/), `<mod_proxy_fcgi>` has no provision for starting the application process; `[fcgistarter](../programs/fcgistarter)` is provided (on some platforms) for that purpose. Alternatively, external launching or process management may be available in the FastCGI application framework in use. **Warning** Do not enable proxying until you have [secured your server](mod_proxy#access). Open proxy servers are dangerous both to your network and to the Internet at large. Examples -------- Remember, in order to make the following examples work, you have to enable `<mod_proxy>` and `<mod_proxy_fcgi>`. ### Single application instance ``` ProxyPass "/myapp/" "fcgi://localhost:4000/" ``` `<mod_proxy_fcgi>` disables connection reuse by default, so after a request has been completed the connection will NOT be held open by that httpd child process and won't be reused. If the FastCGI application is able to handle concurrent connections from httpd, you can opt-in to connection reuse as shown in the following example: ### Single application instance, connection reuse (2.4.11 and later) ``` ProxyPass "/myapp/" "fcgi://localhost:4000/" enablereuse=on ``` **Enable connection reuse to a FCGI backend like PHP-FPM** Please keep in mind that PHP-FPM (at the time of writing, February 2018) uses a prefork model, namely each of its worker processes can handle one connection at the time. By default mod\_proxy (configured with `enablereuse=on`) allows a connection pool of `[ThreadsPerChild](mpm_common#threadsperchild)` connections to the backend for each httpd process when using a threaded mpm (like `<worker>` or `<event>`), so the following use cases should be taken into account: * Under HTTP/1.1 load it will likely cause the creation of up to `[MaxRequestWorkers](mpm_common#maxrequestworkers)` connections to the FCGI backend. * Under HTTP/2 load, due to how `<mod_http2>` is implemented, there are additional h2 worker threads that may force the creation of other backend connections. The overall count of connections in the pools may raise to more than `[MaxRequestWorkers](mpm_common#maxrequestworkers)`. The maximum number of PHP-FPM worker processes needs to be configured wisely, since there is the chance that they will all end up "busy" handling idle persistent connections, without any room for new ones to be established, and the end user experience will be a pile of HTTP request timeouts. The following example passes the request URI as a filesystem path for the PHP-FPM daemon to run. The request URL is implicitly added to the 2nd parameter. The hostname and port following fcgi:// are where PHP-FPM is listening. Connection pooling/reuse is enabled. ### PHP-FPM ``` ProxyPassMatch "^/myapp/.*\.php(/.*)?$" "fcgi://localhost:9000/var/www/" enablereuse=on ``` The following example passes the request URI as a filesystem path for the PHP-FPM daemon to run. In this case, PHP-FPM is listening on a unix domain socket (UDS). Requires 2.4.9 or later. With this syntax, the hostname and optional port following fcgi:// are ignored. ### PHP-FPM with UDS ``` ProxyPassMatch "^/(.*\.php(/.*)?)$" "unix:/var/run/php5-fpm.sock|fcgi://localhost/var/www/" ``` The balanced gateway needs `<mod_proxy_balancer>` and at least one load balancer algorithm module, such as `<mod_lbmethod_byrequests>`, in addition to the proxy modules listed above. `<mod_lbmethod_byrequests>` is the default, and will be used for this example configuration. ### Balanced gateway to multiple application instances ``` ProxyPass "/myapp/" "balancer://myappcluster/" <Proxy "balancer://myappcluster/"> BalancerMember "fcgi://localhost:4000" BalancerMember "fcgi://localhost:4001" </Proxy> ``` You can also force a request to be handled as a reverse-proxy request, by creating a suitable Handler pass-through. The example configuration below will pass all requests for PHP scripts to the specified FastCGI server using reverse proxy. This feature is available in Apache HTTP Server 2.4.10 and later. For performance reasons, you will want to define a [worker](mod_proxy#workers) representing the same fcgi:// backend. The benefit of this form is that it allows the normal mapping of URI to filename to occur in the server, and the local filesystem result is passed to the backend. When FastCGI is configured this way, the server can calculate the most accurate PATH\_INFO. ### Proxy via Handler ``` <FilesMatch "\.php$"> # Note: The only part that varies is /path/to/app.sock SetHandler "proxy:unix:/path/to/app.sock|fcgi://localhost/" </FilesMatch> # Define a matching worker. # The part that is matched to the SetHandler is the part that # follows the pipe. If you need to distinguish, "localhost; can # be anything unique. <Proxy "fcgi://localhost/" enablereuse=on max=10> </Proxy> <FilesMatch ...> SetHandler "proxy:fcgi://localhost:9000" </FilesMatch> <FilesMatch ...> SetHandler "proxy:balancer://myappcluster/" </FilesMatch> ``` Environment Variables --------------------- In addition to the configuration directives that control the behaviour of `<mod_proxy>`, there are a number of environment variables that control the FCGI protocol provider: proxy-fcgi-pathinfo When configured via `[ProxyPass](mod_proxy#proxypass)` or `[ProxyPassMatch](mod_proxy#proxypassmatch)`, `<mod_proxy_fcgi>` will not set the PATH\_INFO environment variable. This allows the backend FCGI server to correctly determine SCRIPT\_NAME and Script-URI and be compliant with RFC 3875 section 3.3. If instead you need `<mod_proxy_fcgi>` to generate a "best guess" for PATH\_INFO, set this env-var. This is a workaround for a bug in some FCGI implementations. This variable can be set to multiple values to tweak at how the best guess is chosen (In 2.4.11 and later only): first-dot PATH\_INFO is split from the slash following the *first* "." in the URL. last-dot PATH\_INFO is split from the slash following the *last* "." in the URL. full PATH\_INFO is calculated by an attempt to map the URL to the local filesystem. unescape PATH\_INFO is the path component of the URL, unescaped / decoded. any other value PATH\_INFO is the same as the path component of the URL. Originally, this was the only proxy-fcgi-pathinfo option. ProxyFCGIBackendType Directive ------------------------------ | | | | --- | --- | | Description: | Specify the type of backend FastCGI application | | Syntax: | ``` ProxyFCGIBackendType FPM|GENERIC ``` | | Default: | ``` ProxyFCGIBackendType FPM ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_proxy\_fcgi | | Compatibility: | Available in version 2.4.26 and later | This directive allows the type of backend FastCGI application to be specified. Some FastCGI servers, such as PHP-FPM, use historical quirks of environment variables to identify the type of proxy server being used. Set this directive to "GENERIC" if your non PHP-FPM application has trouble interpreting environment variables such as SCRIPT\_FILENAME or PATH\_TRANSLATED as set by the server. One example of values that change based on the setting of this directive is SCRIPT\_FILENAME. When using `<mod_proxy_fcgi>` historically, SCRIPT\_FILENAME was prefixed with the string "proxy:fcgi://". This variable is what some generic FastCGI applications would read as their script input, but PHP-FPM would strip the prefix then remember it was talking to Apache. In 2.4.21 through 2.4.25, this prefix was automatically stripped by the server, breaking the ability of PHP-FPM to detect and interoperate with Apache in some scenarios. ProxyFCGISetEnvIf Directive --------------------------- | | | | --- | --- | | Description: | Allow variables sent to FastCGI servers to be fixed up | | Syntax: | ``` ProxyFCGISetEnvIf conditional-expression [!]environment-variable-name [value-expression] ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_proxy\_fcgi | | Compatibility: | Available in version 2.4.26 and later | Just before passing a request to the configured FastCGI server, the core of the web server sets a number of environment variables based on details of the current request. FastCGI programs often uses these environment variables as inputs that determine what underlying scripts they will process, or what output they directly produce. Examples of noteworthy environment variables are: * SCRIPT\_NAME * SCRIPT\_FILENAME * REQUEST\_URI * PATH\_INFO * PATH\_TRANSLATED This directive allows the environment variables above, or any others of interest, to be overridden. This directive is evaluated after the initial values for these variables are set, so they can be used as input into both the condition expressions and value expressions. Parameter syntax: conditional-expression Specifies an expression that controls whether the environment variable that follows will be modified. For information on the expression syntax, see the examples that follow or the full specification at the [ap\_expr](../expr) documentation. environment-variable-name Specifies the CGI environment variable to change, such as PATH\_INFO. If preceded by an exclamation point, the variable will be unset. value-expression Specifies the replacement value for the preceding environment variable. Backreferences, such as "$1", can be included from regular expression captures in conditional-expression. If omitted, the variable is set (or overridden) to an empty string — but see the Note below. ``` # A basic, unconditional override ProxyFCGISetEnvIf "true" PATH_INFO "/example" # Use an environment variable in the value ProxyFCGISetEnvIf "true" PATH_INFO "%{reqenv:SCRIPT_NAME}" # Use captures in the conditions and backreferences in the replacement ProxyFCGISetEnvIf "reqenv('PATH_TRANSLATED') =~ m|(/.*prefix)(\d+)(.*)|" PATH_TRANSLATED "$1$3" ``` **Note: Unset vs. Empty** The following will unset `VARIABLE`, preventing it from being sent to the FastCGI server: ``` ProxyFCGISetEnvIf true !VARIABLE ``` Whereas the following will erase any existing *value* of `VARIABLE` (by setting it to the empty string), but the empty `VARIABLE` will still be sent to the server: ``` ProxyFCGISetEnvIf true VARIABLE ``` The CGI/1.1 specification [does not distinguish](https://tools.ietf.org/html/rfc3875#section-4.1) between a variable with an empty value and a variable that does not exist. However, many CGI and FastCGI implementations distinguish (or allow scripts to distinguish) between the two. The choice of which to use is dependent upon your implementation and your reason for modifying the variable.
programming_docs
apache_http_server Apache Module mod_asis Apache Module mod\_asis ======================= | | | | --- | --- | | Description: | Sends files that contain their own HTTP headers | | Status: | Base | | Module Identifier: | asis\_module | | Source File: | mod\_asis.c | ### Summary This module provides the handler `send-as-is` which causes Apache HTTP Server to send the document without adding most of the usual HTTP headers. This can be used to send any kind of data from the server, including redirects and other special HTTP responses, without requiring a cgi-script or an nph script. For historical reasons, this module will also process any file with the mime type `httpd/send-as-is`. Usage ----- In the server configuration file, associate files with the `send-as-is` handler *e.g.* ``` AddHandler send-as-is asis ``` The contents of any file with a `.asis` extension will then be sent by Apache httpd to the client with almost no changes. In particular, HTTP headers are derived from the file itself according to `<mod_cgi>` rules, so an asis file must include valid headers, and may also use the CGI `Status:` header to determine the HTTP response code. The `Content-Length:` header will automatically be inserted or, if included, corrected by httpd. Here's an example of a file whose contents are sent *as is* so as to tell the client that a file has redirected. ``` Status: 301 Now where did I leave that URL Location: http://xyz.example.com/foo/bar.html Content-type: text/html <html> <head> <title>Lame excuses'R'us</title> </head> <body> <h1>Fred's exceptionally wonderful page has moved to <a href="http://xyz.example.com/foo/bar.html">Joe's</a> site. </h1> </body> </html> ``` **Notes:** The server always adds a `Date:` and `Server:` header to the data returned to the client, so these should not be included in the file. The server does *not* add a `Last-Modified` header; it probably should. apache_http_server Apache MPM worker Apache MPM worker ================= | | | | --- | --- | | Description: | Multi-Processing Module implementing a hybrid multi-threaded multi-process web server | | Status: | MPM | | Module Identifier: | mpm\_worker\_module | | Source File: | worker.c | ### Summary This Multi-Processing Module (MPM) implements a hybrid multi-process multi-threaded server. By using threads to serve requests, it is able to serve a large number of requests with fewer system resources than a process-based server. However, it retains much of the stability of a process-based server by keeping multiple processes available, each with many threads. The most important directives used to control this MPM are `[ThreadsPerChild](mpm_common#threadsperchild)`, which controls the number of threads deployed by each child process and `[MaxRequestWorkers](mpm_common#maxrequestworkers)`, which controls the maximum total number of threads that may be launched. How it Works ------------ A single control process (the parent) is responsible for launching child processes. Each child process creates a fixed number of server threads as specified in the `[ThreadsPerChild](mpm_common#threadsperchild)` directive, as well as a listener thread which listens for connections and passes them to a server thread for processing when they arrive. Apache HTTP Server always tries to maintain a pool of spare or idle server threads, which stand ready to serve incoming requests. In this way, clients do not need to wait for a new threads or processes to be created before their requests can be served. The number of processes that will initially launch is set by the `[StartServers](mpm_common#startservers)` directive. During operation, the server assesses the total number of idle threads in all processes, and forks or kills processes to keep this number within the boundaries specified by `[MinSpareThreads](mpm_common#minsparethreads)` and `[MaxSpareThreads](mpm_common#maxsparethreads)`. Since this process is very self-regulating, it is rarely necessary to modify these directives from their default values. The maximum number of clients that may be served simultaneously (i.e., the maximum total number of threads in all processes) is determined by the `[MaxRequestWorkers](mpm_common#maxrequestworkers)` directive. The maximum number of active child processes is determined by the `[MaxRequestWorkers](mpm_common#maxrequestworkers)` directive divided by the `[ThreadsPerChild](mpm_common#threadsperchild)` directive. Two directives set hard limits on the number of active child processes and the number of server threads in a child process, and can only be changed by fully stopping the server and then starting it again. `[ServerLimit](mpm_common#serverlimit)` is a hard limit on the number of active child processes, and must be greater than or equal to the `[MaxRequestWorkers](mpm_common#maxrequestworkers)` directive divided by the `[ThreadsPerChild](mpm_common#threadsperchild)` directive. `[ThreadLimit](mpm_common#threadlimit)` is a hard limit of the number of server threads, and must be greater than or equal to the `[ThreadsPerChild](mpm_common#threadsperchild)` directive. In addition to the set of active child processes, there may be additional child processes which are terminating, but where at least one server thread is still handling an existing client connection. Up to `[MaxRequestWorkers](mpm_common#maxrequestworkers)` terminating processes may be present, though the actual number can be expected to be much smaller. This behavior can be avoided by disabling the termination of individual child processes, which is achieved using the following: * set the value of `[MaxConnectionsPerChild](mpm_common#maxconnectionsperchild)` to zero * set the value of `[MaxSpareThreads](mpm_common#maxsparethreads)` to the same value as `[MaxRequestWorkers](mpm_common#maxrequestworkers)` A typical configuration of the process-thread controls in the `<worker>` MPM could look as follows: ``` ServerLimit 16 StartServers 2 MaxRequestWorkers 150 MinSpareThreads 25 MaxSpareThreads 75 ThreadsPerChild 25 ``` While the parent process is usually started as `root` under Unix in order to bind to port 80, the child processes and threads are launched by the server as a less-privileged user. The `[User](mod_unixd#user)` and `[Group](mod_unixd#group)` directives are used to set the privileges of the Apache HTTP Server child processes. The child processes must be able to read all the content that will be served, but should have as few privileges beyond that as possible. In addition, unless `[suexec](../programs/suexec)` is used, these directives also set the privileges which will be inherited by CGI scripts. `[MaxConnectionsPerChild](mpm_common#maxconnectionsperchild)` controls how frequently the server recycles processes by killing old ones and launching new ones. This MPM uses the `mpm-accept` mutex to serialize access to incoming connections when subject to the thundering herd problem (generally, when there are multiple listening sockets). The implementation aspects of this mutex can be configured with the `[Mutex](core#mutex)` directive. The [performance hints](../misc/perf-tuning) documentation has additional information about this mutex. apache_http_server Apache Module mod_version Apache Module mod\_version ========================== | | | | --- | --- | | Description: | Version dependent configuration | | Status: | Extension | | Module Identifier: | version\_module | | Source File: | mod\_version.c | ### Summary This module is designed for the use in test suites and large networks which have to deal with different httpd versions and different configurations. It provides a new container -- `[<IfVersion>](#ifversion)`, which allows a flexible version checking including numeric comparisons and regular expressions. ### Examples ``` <IfVersion 2.4.2> # current httpd version is exactly 2.4.2 </IfVersion> <IfVersion >= 2.5> # use really new features :-) </IfVersion> ``` See below for further possibilities. <IfVersion> Directive --------------------- | | | | --- | --- | | Description: | contains version dependent configuration | | Syntax: | ``` <IfVersion [[!]operator] version> ... </IfVersion> ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | All | | Status: | Extension | | Module: | mod\_version | The `<IfVersion>` section encloses configuration directives which are executed only if the `[httpd](../programs/httpd)` version matches the desired criteria. For normal (numeric) comparisons the version argument has the format `major[.minor[.patch]]`, e.g. `2.1.0` or `2.2`. minor and patch are optional. If these numbers are omitted, they are assumed to be zero. The following numerical operators are possible: | operator | description | | --- | --- | | `=` or `==` | httpd version is equal | | `>` | httpd version is greater than | | `>=` | httpd version is greater or equal | | `<` | httpd version is less than | | `<=` | httpd version is less or equal | ### Example ``` <IfVersion >= 2.3> # this happens only in versions greater or # equal 2.3.0. </IfVersion> ``` Besides the numerical comparison it is possible to match a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") against the httpd version. There are two ways to write it: | operator | description | | --- | --- | | `=` or `==` | version has the form `/regex/` | | `~` | version has the form `regex` | ### Example ``` <IfVersion = /^2.4.[01234]$/> # e.g. workaround for buggy versions </IfVersion> ``` In order to reverse the meaning, all operators can be preceded by an exclamation mark (`!`): ``` <IfVersion !~ ^2.4.[01234]$> # not for those versions </IfVersion> ``` If the operator is omitted, it is assumed to be `=`. apache_http_server Apache Module mod_sed Apache Module mod\_sed ====================== | | | | --- | --- | | Description: | Filter Input (request) and Output (response) content using `sed` syntax | | Status: | Experimental | | Module Identifier: | sed\_module | | Source File: | mod\_sed.c sed0.c sed1.c regexp.c regexp.h sed.h | | Compatibility: | Available in Apache 2.3 and later | ### Summary `<mod_sed>` is an in-process content filter. The `<mod_sed>` filter implements the `sed` editing commands implemented by the Solaris 10 `sed` program as described in the [manual page](http://www.gnu.org/software/sed/manual/sed.txt). However, unlike `sed`, `<mod_sed>` doesn't take data from standard input. Instead, the filter acts on the entity data sent between client and server. `<mod_sed>` can be used as an input or output filter. `<mod_sed>` is a content filter, which means that it cannot be used to modify client or server http headers. The `<mod_sed>` output filter accepts a chunk of data, executes the `sed` scripts on the data, and generates the output which is passed to the next filter in the chain. The `<mod_sed>` input filter reads the data from the next filter in the chain, executes the `sed` scripts, and returns the generated data to the caller filter in the filter chain. Both the input and output filters only process the data if newline characters are seen in the content. At the end of the data, the rest of the data is treated as the last line. Sample Configuration -------------------- ### Adding an output filter ``` # In the following example, the sed filter will change the string # "monday" to "MON" and the string "sunday" to SUN in html documents # before sending to the client. <Directory "/var/www/docs/sed"> AddOutputFilter Sed html OutputSed "s/monday/MON/g" OutputSed "s/sunday/SUN/g" </Directory> ``` ### Adding an input filter ``` # In the following example, the sed filter will change the string # "monday" to "MON" and the string "sunday" to SUN in the POST data # sent to PHP. <Directory "/var/www/docs/sed"> AddInputFilter Sed php InputSed "s/monday/MON/g" InputSed "s/sunday/SUN/g" </Directory> ``` Sed Commands ------------ Complete details of the `sed` command can be found from the [sed manual page](http://www.gnu.org/software/sed/manual/sed.txt). `b` Branch to the label specified (similar to goto). `h` Copy the current line to the hold buffer. `H` Append the current line to the hold buffer. `g` Copy the hold buffer to the current line. `G` Append the hold buffer to the current line. `x` Swap the contents of the hold buffer and the current line. InputSed Directive ------------------ | | | | --- | --- | | Description: | Sed command to filter request data (typically `POST` data) | | Syntax: | ``` InputSed sed-command ``` | | Context: | directory, .htaccess | | Status: | Experimental | | Module: | mod\_sed | The `InputSed` directive specifies the `sed` command to execute on the request data e.g., `POST` data. OutputSed Directive ------------------- | | | | --- | --- | | Description: | Sed command for filtering response content | | Syntax: | ``` OutputSed sed-command ``` | | Context: | directory, .htaccess | | Status: | Experimental | | Module: | mod\_sed | The `OutputSed` directive specifies the `sed` command to execute on the response. apache_http_server Apache Module mod_proxy_scgi Apache Module mod\_proxy\_scgi ============================== | | | | --- | --- | | Description: | SCGI gateway module for `<mod_proxy>` | | Status: | Extension | | Module Identifier: | proxy\_scgi\_module | | Source File: | mod\_proxy\_scgi.c | | Compatibility: | Available in version 2.2.14 and later | ### Summary This module *requires* the service of `<mod_proxy>`. It provides support for the [SCGI protocol, version 1](http://python.ca/scgi/protocol.txt). Thus, in order to get the ability of handling the SCGI protocol, `<mod_proxy>` and `<mod_proxy_scgi>` have to be present in the server. **Warning** Do not enable proxying until you have [secured your server](mod_proxy#access). Open proxy servers are dangerous both to your network and to the Internet at large. Examples -------- Remember, in order to make the following examples work, you have to enable `<mod_proxy>` and `<mod_proxy_scgi>`. ### Simple gateway ``` ProxyPass "/scgi-bin/" "scgi://localhost:4000/" ``` The balanced gateway needs `<mod_proxy_balancer>` and at least one load balancer algorithm module, such as `<mod_lbmethod_byrequests>`, in addition to the proxy modules listed above. `<mod_lbmethod_byrequests>` is the default, and will be used for this example configuration. ### Balanced gateway ``` ProxyPass "/scgi-bin/" "balancer://somecluster/" <Proxy "balancer://somecluster"> BalancerMember "scgi://localhost:4000" BalancerMember "scgi://localhost:4001" </Proxy> ``` Environment Variables --------------------- In addition to the configuration directives that control the behaviour of `<mod_proxy>`, an environment variable may also control the SCGI protocol provider: proxy-scgi-pathinfo By default `<mod_proxy_scgi>` will neither create nor export the PATH\_INFO environment variable. This allows the backend SCGI server to correctly determine SCRIPT\_NAME and Script-URI and be compliant with RFC 3875 section 3.3. If instead you need `<mod_proxy_scgi>` to generate a "best guess" for PATH\_INFO, set this env-var. The variable must be set before `[SetEnv](mod_env#setenv)` is effective. `[SetEnvIf](mod_setenvif#setenvif)` can be used instead: `SetEnvIf Request_URI . proxy-scgi-pathinfo` ProxySCGIInternalRedirect Directive ----------------------------------- | | | | --- | --- | | Description: | Enable or disable internal redirect responses from the backend | | Syntax: | ``` ProxySCGIInternalRedirect On|Off|Headername ``` | | Default: | ``` ProxySCGIInternalRedirect On ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy\_scgi | | Compatibility: | The Headername feature is available in version 2.4.13 and later | The `ProxySCGIInternalRedirect` enables the backend to internally redirect the gateway to a different URL. This feature originates in `<mod_cgi>`, which internally redirects the response if the response status is `OK` (`200`) and the response contains a `Location` (or configured alternate header) and its value starts with a slash (`/`). This value is interpreted as a new local URL that Apache httpd internally redirects to. `<mod_proxy_scgi>` does the same as `<mod_cgi>` in this regard, except that you can turn off the feature or specify the use of a header other than `Location`. ### Example ``` ProxySCGIInternalRedirect Off # Django and some other frameworks will fully qualify "local URLs" # set by the application, so an alternate header must be used. <Location /django-app/> ProxySCGIInternalRedirect X-Location </Location> ``` ProxySCGISendfile Directive --------------------------- | | | | --- | --- | | Description: | Enable evaluation of X-Sendfile pseudo response header | | Syntax: | ``` ProxySCGISendfile On|Off|Headername ``` | | Default: | ``` ProxySCGISendfile Off ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy\_scgi | The `ProxySCGISendfile` directive enables the SCGI backend to let files be served directly by the gateway. This is useful for performance purposes — httpd can use `sendfile` or other optimizations, which are not possible if the file comes over the backend socket. Additionally, the file contents are not transmitted twice. The `ProxySCGISendfile` argument determines the gateway behaviour: `Off` No special handling takes place. `On` The gateway looks for a backend response header called `X-Sendfile` and interprets the value as the filename to serve. The header is removed from the final response headers. This is equivalent to `ProxySCGISendfile X-Sendfile`. anything else Similar to `On`, but instead of the hardcoded header name `X-Sendfile`, the argument is used as the header name. ### Example ``` # Use the default header (X-Sendfile) ProxySCGISendfile On # Use a different header ProxySCGISendfile X-Send-Static ``` apache_http_server Apache Module mod_speling Apache Module mod\_speling ========================== | | | | --- | --- | | Description: | Attempts to correct mistaken URLs by ignoring capitalization, or attempting to correct various minor misspellings. | | Status: | Extension | | Module Identifier: | speling\_module | | Source File: | mod\_speling.c | ### Summary Requests to documents sometimes cannot be served by the core apache server because the request was misspelled or miscapitalized. This module addresses this problem by trying to find a matching document, even after all other modules gave up. It does its work by comparing each document name in the requested directory against the requested document name **without regard to case**, and allowing **up to one misspelling** (character insertion / omission / transposition or wrong character). A list is built with all document names which were matched using this strategy. **Erroneous extension** can also be fixed by this module. If, after scanning the directory, * no matching document was found, Apache will proceed as usual and return an error (`404 - document not found`). * only one document is found that "almost" matches the request, then it is returned in the form of a redirection response (`301 - Moved Permanently`). * more than one document with a close match was found, then the list of the matches is returned to the client, and the client can select the correct candidate (`300 - Multiple Choices`). CheckBasenameMatch Directive ---------------------------- | | | | --- | --- | | Description: | Also match files with differing file name extensions. | | Syntax: | ``` CheckBasenameMatch on|off ``` | | Default: | ``` CheckBasenameMatch On ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Extension | | Module: | mod\_speling | | Compatibility: | Available in httpd 2.4.50 and later | When set, this directive extends the action of the spelling correction to the file name extension. For example a file `foo.gif` will match a request for `foo` or `foo.jpg`. This can be particularly useful in conjunction with [MultiViews](../content-negotiation). CheckCaseOnly Directive ----------------------- | | | | --- | --- | | Description: | Limits the action of the speling module to case corrections | | Syntax: | ``` CheckCaseOnly on|off ``` | | Default: | ``` CheckCaseOnly Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Extension | | Module: | mod\_speling | When set, this directive limits the action of the spelling correction to lower/upper case changes. Other potential corrections are not performed, except when `[CheckBasenameMatch](#checkbasenamematch)` is also set. CheckSpelling Directive ----------------------- | | | | --- | --- | | Description: | Enables the spelling module | | Syntax: | ``` CheckSpelling on|off ``` | | Default: | ``` CheckSpelling Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Extension | | Module: | mod\_speling | This directive enables or disables the spelling module. When enabled, keep in mind that * the directory scan which is necessary for the spelling correction will have an impact on the server's performance when many spelling corrections have to be performed at the same time. * the document trees should not contain sensitive files which could be matched inadvertently by a spelling "correction". * the module is unable to correct misspelled user names (as in `http://my.host/~apahce/`), just file names or directory names. * spelling corrections apply strictly to existing files, so a request for the `<Location /status>` may get incorrectly treated as the negotiated file "`/stats.html`". `<mod_speling>` should not be enabled in [DAV](mod_dav) enabled directories, because it will try to "spell fix" newly created resource names against existing filenames, e.g., when trying to upload a new document `doc43.html` it might redirect to an existing document `doc34.html`, which is not what was intended.
programming_docs
apache_http_server Apache Module mod_rewrite Apache Module mod\_rewrite ========================== | | | | --- | --- | | Description: | Provides a rule-based rewriting engine to rewrite requested URLs on the fly | | Status: | Extension | | Module Identifier: | rewrite\_module | | Source File: | mod\_rewrite.c | ### Summary The `<mod_rewrite>` module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite requested URLs on the fly. By default, `<mod_rewrite>` maps a URL to a filesystem path. However, it can also be used to redirect one URL to another URL, or to invoke an internal proxy fetch. `<mod_rewrite>` provides a flexible and powerful way to manipulate URLs using an unlimited number of rules. Each rule can have an unlimited number of attached rule conditions, to allow you to rewrite URL based on server variables, environment variables, HTTP headers, or time stamps. `<mod_rewrite>` operates on the full URL path, including the path-info section. A rewrite rule can be invoked in `httpd.conf` or in `.htaccess`. The path generated by a rewrite rule can include a query string, or can lead to internal sub-processing, external request redirection, or internal proxy throughput. Further details, discussion, and examples, are provided in the [detailed mod\_rewrite documentation](../rewrite/index). Logging ------- `<mod_rewrite>` offers detailed logging of its actions at the `trace1` to `trace8` log levels. The log level can be set specifically for `<mod_rewrite>` using the `[LogLevel](core#loglevel)` directive: Up to level `debug`, no actions are logged, while `trace8` means that practically all actions are logged. Using a high trace log level for `<mod_rewrite>` will slow down your Apache HTTP Server dramatically! Use a log level higher than `trace2` only for debugging! ### Example ``` LogLevel alert rewrite:trace3 ``` **RewriteLog** Those familiar with earlier versions of `<mod_rewrite>` will no doubt be looking for the `RewriteLog` and `RewriteLogLevel` directives. This functionality has been completely replaced by the new per-module logging configuration mentioned above. To get just the `<mod_rewrite>`-specific log messages, pipe the log file through grep: ``` tail -f error_log|fgrep '[rewrite:' ``` RewriteBase Directive --------------------- | | | | --- | --- | | Description: | Sets the base URL for per-directory rewrites | | Syntax: | ``` RewriteBase URL-path ``` | | Default: | `None` | | Context: | directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_rewrite | The `RewriteBase` directive specifies the URL prefix to be used for per-directory (htaccess) `[RewriteRule](#rewriterule)` directives that substitute a relative path. This directive is *required* when you use a relative path in a substitution in per-directory (htaccess) context unless any of the following conditions are true: * The original request, and the substitution, are underneath the `[DocumentRoot](core#documentroot)` (as opposed to reachable by other means, such as `[Alias](mod_alias#alias)`). * The *filesystem* path to the directory containing the `[RewriteRule](#rewriterule)`, suffixed by the relative substitution is also valid as a URL path on the server (this is rare). * In Apache HTTP Server 2.4.16 and later, this directive may be omitted when the request is mapped via `[Alias](mod_alias#alias)` or `<mod_userdir>`. In the example below, `RewriteBase` is necessary to avoid rewriting to http://example.com/opt/myapp-1.2.3/welcome.html since the resource was not relative to the document root. This misconfiguration would normally cause the server to look for an "opt" directory under the document root. ``` DocumentRoot "/var/www/example.com" AliasMatch "^/myapp" "/opt/myapp-1.2.3" <Directory "/opt/myapp-1.2.3"> RewriteEngine On RewriteBase "/myapp/" RewriteRule "^index\.html$" "welcome.html" </Directory> ``` RewriteCond Directive --------------------- | | | | --- | --- | | Description: | Defines a condition under which rewriting will take place | | Syntax: | ``` RewriteCond TestString CondPattern [flags] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_rewrite | The `RewriteCond` directive defines a rule condition. One or more `RewriteCond` can precede a `[RewriteRule](#rewriterule)` directive. The following rule is then only used if both the current state of the URI matches its pattern, **and** if these conditions are met. *TestString* is a string which can contain the following expanded constructs in addition to plain text: * **RewriteRule backreferences**: These are backreferences of the form **`$N`** (0 <= N <= 9). $1 to $9 provide access to the grouped parts (in parentheses) of the pattern, from the `RewriteRule` which is subject to the current set of `RewriteCond` conditions. $0 provides access to the whole string matched by that pattern. * **RewriteCond backreferences**: These are backreferences of the form **`%N`** (0 <= N <= 9). %1 to %9 provide access to the grouped parts (again, in parentheses) of the pattern, from the last matched `RewriteCond` in the current set of conditions. %0 provides access to the whole string matched by that pattern. * **RewriteMap expansions**: These are expansions of the form **`${mapname:key|default}`**. See [the documentation for RewriteMap](#mapfunc) for more details. * **Server-Variables**: These are variables of the form **`%{` *NAME\_OF\_VARIABLE* `}`** where *NAME\_OF\_VARIABLE* can be a string taken from the following list: | HTTP headers: | connection & request: | | | --- | --- | --- | | HTTP\_ACCEPT HTTP\_COOKIE HTTP\_FORWARDED HTTP\_HOST HTTP\_PROXY\_CONNECTION HTTP\_REFERER HTTP\_USER\_AGENT | AUTH\_TYPE CONN\_REMOTE\_ADDR CONTEXT\_PREFIX CONTEXT\_DOCUMENT\_ROOT IPV6 PATH\_INFO QUERY\_STRING REMOTE\_ADDR REMOTE\_HOST REMOTE\_IDENT REMOTE\_PORT REMOTE\_USER REQUEST\_METHOD SCRIPT\_FILENAME | | | server internals: | date and time: | specials: | | DOCUMENT\_ROOT SCRIPT\_GROUP SCRIPT\_USER SERVER\_ADDR SERVER\_ADMIN SERVER\_NAME SERVER\_PORT SERVER\_PROTOCOL SERVER\_SOFTWARE | TIME\_YEAR TIME\_MON TIME\_DAY TIME\_HOUR TIME\_MIN TIME\_SEC TIME\_WDAY TIME | API\_VERSION CONN\_REMOTE\_ADDR HTTPS IS\_SUBREQ REMOTE\_ADDR REQUEST\_FILENAME REQUEST\_SCHEME REQUEST\_URI THE\_REQUEST | These variables all correspond to the similarly named HTTP MIME-headers, C variables of the Apache HTTP Server or `struct tm` fields of the Unix system. Most are documented [here](../expr#vars) or elsewhere in the Manual or in the CGI specification. SERVER\_NAME and SERVER\_PORT depend on the values of `[UseCanonicalName](core#usecanonicalname)` and `[UseCanonicalPhysicalPort](core#usecanonicalphysicalport)` respectively. Those that are special to `<mod_rewrite>` include those below. `API_VERSION` This is the version of the Apache httpd module API (the internal interface between server and module) in the current httpd build, as defined in include/ap\_mmn.h. The module API version corresponds to the version of Apache httpd in use (in the release version of Apache httpd 1.3.14, for instance, it is 19990320:10), but is mainly of interest to module authors. `CONN_REMOTE_ADDR` Since 2.4.8: The peer IP address of the connection (see the `<mod_remoteip>` module). `HTTPS` Will contain the text "on" if the connection is using SSL/TLS, or "off" otherwise. (This variable can be safely used regardless of whether or not `<mod_ssl>` is loaded). `IS_SUBREQ` Will contain the text "true" if the request currently being processed is a sub-request, "false" otherwise. Sub-requests may be generated by modules that need to resolve additional files or URIs in order to complete their tasks. `REMOTE_ADDR` The IP address of the remote host (see the `<mod_remoteip>` module). `REQUEST_FILENAME` The full local filesystem path to the file or script matching the request, if this has already been determined by the server at the time `REQUEST_FILENAME` is referenced. Otherwise, such as when used in virtual host context, the same value as `REQUEST_URI`. Depending on the value of `[AcceptPathInfo](core#acceptpathinfo)`, the server may have only used some leading components of the `REQUEST_URI` to map the request to a file. `REQUEST_SCHEME` Will contain the scheme of the request (usually "http" or "https"). This value can be influenced with `[ServerName](core#servername)`. `REQUEST_URI` The path component of the requested URI, such as "/index.html". This notably excludes the query string which is available as its own variable named `QUERY_STRING`. `THE_REQUEST` The full HTTP request line sent by the browser to the server (e.g., "`GET /index.html HTTP/1.1`"). This does not include any additional headers sent by the browser. This value has not been unescaped (decoded), unlike most other variables below. If the *TestString* has the special value `expr`, the *CondPattern* will be treated as an [ap\_expr](../expr). HTTP headers referenced in the expression will be added to the Vary header if the `novary` flag is not given. Other things you should be aware of: 1. The variables SCRIPT\_FILENAME and REQUEST\_FILENAME contain the same value - the value of the `filename` field of the internal `request_rec` structure of the Apache HTTP Server. The first name is the commonly known CGI variable name while the second is the appropriate counterpart of REQUEST\_URI (which contains the value of the `uri` field of `request_rec`). If a substitution occurred and the rewriting continues, the value of both variables will be updated accordingly. If used in per-server context (*i.e.*, before the request is mapped to the filesystem) SCRIPT\_FILENAME and REQUEST\_FILENAME cannot contain the full local filesystem path since the path is unknown at this stage of processing. Both variables will initially contain the value of REQUEST\_URI in that case. In order to obtain the full local filesystem path of the request in per-server context, use an URL-based look-ahead `%{LA-U:REQUEST_FILENAME}` to determine the final value of REQUEST\_FILENAME. 2. `%{ENV:variable}`, where *variable* can be any environment variable, is also available. This is looked-up via internal Apache httpd structures and (if not found there) via `getenv()` from the Apache httpd server process. 3. `%{SSL:variable}`, where *variable* is the name of an [SSL environment variable](mod_ssl#envvars), can be used whether or not `<mod_ssl>` is loaded, but will always expand to the empty string if it is not. Example: `%{SSL:SSL_CIPHER_USEKEYSIZE}` may expand to `128`. These variables are available even without setting the `StdEnvVars` option of the `[SSLOptions](mod_ssl#ssloptions)` directive. 4. `%{HTTP:header}`, where *header* can be any HTTP MIME-header name, can always be used to obtain the value of a header sent in the HTTP request. Example: `%{HTTP:Proxy-Connection}` is the value of the HTTP header ```Proxy-Connection:`''. If a HTTP header is used in a condition this header is added to the Vary header of the response in case the condition evaluates to true for the request. It is **not** added if the condition evaluates to false for the request. Adding the HTTP header to the Vary header of the response is needed for proper caching. It has to be kept in mind that conditions follow a short circuit logic in the case of the '**`ornext|OR`**' flag so that certain conditions might not be evaluated at all. 5. `%{LA-U:variable}` can be used for look-aheads which perform an internal (URL-based) sub-request to determine the final value of *variable*. This can be used to access variable for rewriting which is not available at the current stage, but will be set in a later phase. For instance, to rewrite according to the `REMOTE_USER` variable from within the per-server context (`httpd.conf` file) you must use `%{LA-U:REMOTE_USER}` - this variable is set by the authorization phases, which come *after* the URL translation phase (during which `<mod_rewrite>` operates). On the other hand, because `<mod_rewrite>` implements its per-directory context (`.htaccess` file) via the Fixup phase of the API and because the authorization phases come *before* this phase, you just can use `%{REMOTE_USER}` in that context. 6. `%{LA-F:variable}` can be used to perform an internal (filename-based) sub-request, to determine the final value of *variable*. Most of the time, this is the same as LA-U above. *CondPattern* is the condition pattern, a regular expression which is applied to the current instance of the *TestString*. *TestString* is first evaluated, before being matched against *CondPattern*. *CondPattern* is usually a *perl compatible regular expression*, but there is additional syntax available to perform other useful tests against the *Teststring*: 1. You can prefix the pattern string with a '`!`' character (exclamation mark) to negate the result of the condition, no matter what kind of *CondPattern* is used. 2. You can perform lexicographical string comparisons: **<CondPattern** Lexicographically precedes Treats the *CondPattern* as a plain string and compares it lexicographically to *TestString*. True if *TestString* lexicographically precedes *CondPattern*. **>CondPattern** Lexicographically follows Treats the *CondPattern* as a plain string and compares it lexicographically to *TestString*. True if *TestString* lexicographically follows *CondPattern*. **=CondPattern** Lexicographically equal Treats the *CondPattern* as a plain string and compares it lexicographically to *TestString*. True if *TestString* is lexicographically equal to *CondPattern* (the two strings are exactly equal, character for character). If *CondPattern* is `""` (two quotation marks) this compares *TestString* to the empty string. **<=CondPattern** Lexicographically less than or equal to Treats the *CondPattern* as a plain string and compares it lexicographically to *TestString*. True if *TestString* lexicographically precedes *CondPattern*, or is equal to *CondPattern* (the two strings are equal, character for character). **>=CondPattern** Lexicographically greater than or equal to Treats the *CondPattern* as a plain string and compares it lexicographically to *TestString*. True if *TestString* lexicographically follows *CondPattern*, or is equal to *CondPattern* (the two strings are equal, character for character). **Note** The string comparison operator is part of the *CondPattern* argument and must be included in the quotes if those are used. Eg. ``` RewriteCond %{HTTP_USER_AGENT} "=This Robot/1.0" ``` 3. You can perform integer comparisons: **-eq** Is numerically **eq**ual to The *TestString* is treated as an integer, and is numerically compared to the *CondPattern*. True if the two are numerically equal. **-ge** Is numerically **g**reater than or **e**qual to The *TestString* is treated as an integer, and is numerically compared to the *CondPattern*. True if the *TestString* is numerically greater than or equal to the *CondPattern*. **-gt** Is numerically **g**reater **t**han The *TestString* is treated as an integer, and is numerically compared to the *CondPattern*. True if the *TestString* is numerically greater than the *CondPattern*. **-le** Is numerically **l**ess than or **e**qual to The *TestString* is treated as an integer, and is numerically compared to the *CondPattern*. True if the *TestString* is numerically less than or equal to the *CondPattern*. Avoid confusion with the **-l** by using the **-L** or **-h** variant. **-lt** Is numerically **l**ess **t**han The *TestString* is treated as an integer, and is numerically compared to the *CondPattern*. True if the *TestString* is numerically less than the *CondPattern*. Avoid confusion with the **-l** by using the **-L** or **-h** variant. **-ne** Is numerically **n**ot **e**qual to The *TestString* is treated as an integer, and is numerically compared to the *CondPattern*. True if the two are numerically different. This is equivalent to `!-eq`. 4. You can perform various file attribute tests: **-d** Is **d**irectory. Treats the *TestString* as a pathname and tests whether or not it exists, and is a directory. **-f** Is regular **f**ile. Treats the *TestString* as a pathname and tests whether or not it exists, and is a regular file. **-F** Is existing file, via subrequest. Checks whether or not *TestString* is a valid file, accessible via all the server's currently-configured access controls for that path. This uses an internal subrequest to do the check, so use it with care - it can impact your server's performance! **-h** Is symbolic link, bash convention. See **-l**. **-l** Is symbolic **l**ink. Treats the *TestString* as a pathname and tests whether or not it exists, and is a symbolic link. May also use the bash convention of **-L** or **-h** if there's a possibility of confusion such as when using the **-lt** or **-le** tests. **-L** Is symbolic link, bash convention. See **-l**. **-s** Is regular file, with **s**ize. Treats the *TestString* as a pathname and tests whether or not it exists, and is a regular file with size greater than zero. **-U** Is existing URL, via subrequest. Checks whether or not *TestString* is a valid URL, accessible via all the server's currently-configured access controls for that path. This uses an internal subrequest to do the check, so use it with care - it can impact your server's performance! This flag *only* returns information about things like access control, authentication, and authorization. This flag *does not* return information about the status code the configured handler (static file, CGI, proxy, etc.) would have returned. **-x** Has e**x**ecutable permissions. Treats the *TestString* as a pathname and tests whether or not it exists, and has executable permissions. These permissions are determined according to the underlying OS. For example: ``` RewriteCond /var/www/%{REQUEST_URI} !-f RewriteRule ^(.+) /other/archive/$1 [R] ``` 5. If the *TestString* has the special value `expr`, the *CondPattern* will be treated as an [ap\_expr](../expr). In the below example, `-strmatch` is used to compare the `REFERER` against the site hostname, to block unwanted hotlinking. ``` RewriteCond expr "! %{HTTP_REFERER} -strmatch '*://%{HTTP_HOST}/*'" RewriteRule "^/images" "-" [F] ``` You can also set special flags for *CondPattern* by appending **`[`*flags*`]`** as the third argument to the `RewriteCond` directive, where *flags* is a comma-separated list of any of the following flags: * '**`nocase|NC`**' (**n**o **c**ase) This makes the test case-insensitive - differences between 'A-Z' and 'a-z' are ignored, both in the expanded *TestString* and the *CondPattern*. This flag is effective only for comparisons between *TestString* and *CondPattern*. It has no effect on filesystem and subrequest checks. * '**`ornext|OR`**' (**or** next condition) Use this to combine rule conditions with a local OR instead of the implicit AND. Typical example: ``` RewriteCond "%{REMOTE_HOST}" "^host1" [OR] RewriteCond "%{REMOTE_HOST}" "^host2" [OR] RewriteCond "%{REMOTE_HOST}" "^host3" RewriteRule ...some special stuff for any of these hosts... ``` Without this flag you would have to write the condition/rule pair three times. * '**`novary|NV`**' (**n**o **v**ary) If a HTTP header is used in the condition, this flag prevents this header from being added to the Vary header of the response. Using this flag might break proper caching of the response if the representation of this response varies on the value of this header. So this flag should be only used if the meaning of the Vary header is well understood. **Example:** To rewrite the Homepage of a site according to the ```User-Agent:`'' header of the request, you can use the following: ``` RewriteCond "%{HTTP_USER_AGENT}" "(iPhone|Blackberry|Android)" RewriteRule "^/$" "/homepage.mobile.html" [L] RewriteRule "^/$" "/homepage.std.html" [L] ``` Explanation: If you use a browser which identifies itself as a mobile browser (note that the example is incomplete, as there are many other mobile platforms), the mobile version of the homepage is served. Otherwise, the standard page is served. RewriteEngine Directive ----------------------- | | | | --- | --- | | Description: | Enables or disables runtime rewriting engine | | Syntax: | ``` RewriteEngine on|off ``` | | Default: | ``` RewriteEngine off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_rewrite | The `RewriteEngine` directive enables or disables the runtime rewriting engine. If it is set to `off` this module does no runtime processing at all. It does not even update the `SCRIPT_URx` environment variables. Use this directive to disable rules in a particular context, rather than commenting out all the `[RewriteRule](#rewriterule)` directives. Note that rewrite configurations are not inherited by virtual hosts. This means that you need to have a `RewriteEngine on` directive for each virtual host in which you wish to use rewrite rules. `[RewriteMap](#rewritemap)` directives of the type `prg` are not started during server initialization if they're defined in a context that does not have `RewriteEngine` set to `on` RewriteMap Directive -------------------- | | | | --- | --- | | Description: | Defines a mapping function for key-lookup | | Syntax: | ``` RewriteMap MapName MapType:MapSource [MapTypeOptions] ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_rewrite | | Compatibility: | The 3rd parameter, MapTypeOptions, in only available from Apache 2.4.29 and later | The `RewriteMap` directive defines a *Rewriting Map* which can be used inside rule substitution strings by the mapping-functions to insert/substitute fields through a key lookup. The source of this lookup can be of various types. The *MapName* is the name of the map and will be used to specify a mapping-function for the substitution strings of a rewriting rule via one of the following constructs: **`${` *MapName* `:` *LookupKey* `}` `${` *MapName* `:` *LookupKey* `|` *DefaultValue* `}`** When such a construct occurs, the map *MapName* is consulted and the key *LookupKey* is looked-up. If the key is found, the map-function construct is substituted by *SubstValue*. If the key is not found then it is substituted by *DefaultValue* or by the empty string if no *DefaultValue* was specified. Empty values behave as if the key was absent, therefore it is not possible to distinguish between empty-valued keys and absent keys. For example, you might define a `RewriteMap` as: ``` RewriteMap examplemap "txt:/path/to/file/map.txt" ``` You would then be able to use this map in a `[RewriteRule](#rewriterule)` as follows: ``` RewriteRule "^/ex/(.*)" "${examplemap:$1}" ``` The meaning of the *MapTypeOptions* argument depends on particular *MapType*. See the [Using RewriteMap](../rewrite/rewritemap) for more information. The following combinations for *MapType* and *MapSource* can be used: txt A plain text file containing space-separated key-value pairs, one per line. ([Details ...](../rewrite/rewritemap#txt)) rnd Randomly selects an entry from a plain text file ([Details ...](../rewrite/rewritemap#rnd)) dbm Looks up an entry in a dbm file containing name, value pairs. Hash is constructed from a plain text file format using the `[httxt2dbm](../programs/httxt2dbm)` utility. ([Details ...](../rewrite/rewritemap#dbm)) int One of the four available internal functions provided by `RewriteMap`: toupper, tolower, escape or unescape. ([Details ...](../rewrite/rewritemap#int)) prg Calls an external program or script to process the rewriting. ([Details ...](../rewrite/rewritemap#prg)) dbd or fastdbd A SQL SELECT statement to be performed to look up the rewrite target. ([Details ...](../rewrite/rewritemap#dbd)) Further details, and numerous examples, may be found in the [RewriteMap HowTo](../rewrite/rewritemap) RewriteOptions Directive ------------------------ | | | | --- | --- | | Description: | Sets some special options for the rewrite engine | | Syntax: | ``` RewriteOptions Options ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_rewrite | The `RewriteOptions` directive sets some special options for the current per-server or per-directory configuration. The *Option* string can currently only be one of the following: `Inherit` This forces the current configuration to inherit the configuration of the parent. In per-virtual-server context, this means that the maps, conditions and rules of the main server are inherited. In per-directory context this means that conditions and rules of the parent directory's `.htaccess` configuration or `[<Directory>](core#directory)` sections are inherited. The inherited rules are virtually copied to the section where this directive is being used. If used in combination with local rules, the inherited rules are copied behind the local rules. The position of this directive - below or above of local rules - has no influence on this behavior. If local rules forced the rewriting to stop, the inherited rules won't be processed. Rules inherited from the parent scope are applied **after** rules specified in the child scope. `InheritBefore` Like `Inherit` above, but the rules from the parent scope are applied **before** rules specified in the child scope. Available in Apache HTTP Server 2.3.10 and later. `InheritDown` If this option is enabled, all child configurations will inherit the configuration of the current configuration. It is equivalent to specifying `RewriteOptions Inherit` in all child configurations. See the `Inherit` option for more details on how the parent-child relationships are handled. Available in Apache HTTP Server 2.4.8 and later. `InheritDownBefore` Like `InheritDown` above, but the rules from the current scope are applied **before** rules specified in any child's scope. Available in Apache HTTP Server 2.4.8 and later. `IgnoreInherit` This option forces the current and child configurations to ignore all rules that would be inherited from a parent specifying `InheritDown` or `InheritDownBefore`. Available in Apache HTTP Server 2.4.8 and later. `AllowNoSlash` By default, `<mod_rewrite>` will ignore URLs that map to a directory on disk but lack a trailing slash, in the expectation that the `<mod_dir>` module will issue the client with a redirect to the canonical URL with a trailing slash. When the `[DirectorySlash](mod_dir#directoryslash)` directive is set to off, the `AllowNoSlash` option can be enabled to ensure that rewrite rules are no longer ignored. This option makes it possible to apply rewrite rules within .htaccess files that match the directory without a trailing slash, if so desired. Available in Apache HTTP Server 2.4.0 and later. `AllowAnyURI` When `[RewriteRule](#rewriterule)` is used in `VirtualHost` or server context with version 2.2.22 or later of httpd, `<mod_rewrite>` will only process the rewrite rules if the request URI is a URL-path. This avoids some security issues where particular rules could allow "surprising" pattern expansions (see [CVE-2011-3368](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2011-3368) and [CVE-2011-4317](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2011-4317)). To lift the restriction on matching a URL-path, the `AllowAnyURI` option can be enabled, and `<mod_rewrite>` will apply the rule set to any request URI string, regardless of whether that string matches the URL-path grammar required by the HTTP specification. Available in Apache HTTP Server 2.4.3 and later. **Security Warning** Enabling this option will make the server vulnerable to security issues if used with rewrite rules which are not carefully authored. It is **strongly recommended** that this option is not used. In particular, beware of input strings containing the '`@`' character which could change the interpretation of the transformed URI, as per the above CVE names. `MergeBase` With this option, the value of `[RewriteBase](#rewritebase)` is copied from where it's explicitly defined into any sub-directory or sub-location that doesn't define its own `[RewriteBase](#rewritebase)`. This was the default behavior in 2.4.0 through 2.4.3, and the flag to restore it is available Apache HTTP Server 2.4.4 and later. `IgnoreContextInfo` When a relative substitution is made in directory (htaccess) context and `[RewriteBase](#rewritebase)` has not been set, this module uses some extended URL and filesystem context information to change the relative substitution back into a URL. Modules such as `<mod_userdir>` and `<mod_alias>` supply this extended context info. Available in 2.4.16 and later. `LegacyPrefixDocRoot` Prior to 2.4.26, if a substitution was an absolute URL that matched the current virtual host, the URL might first be reduced to a URL-path and then later reduced to a local path. Since the URL can be reduced to a local path, the path should be prefixed with the document root. This prevents a file such as /tmp/myfile from being accessed when a request is made to http://host/file/myfile with the following `[RewriteRule](#rewriterule)`. ``` RewriteRule /file/(.*) http://localhost/tmp/$1 ``` This option allows the old behavior to be used where the document root is not prefixed to a local path that was reduced from a URL. Available in 2.4.26 and later. RewriteRule Directive --------------------- | | | | --- | --- | | Description: | Defines rules for the rewriting engine | | Syntax: | ``` RewriteRule Pattern Substitution [flags] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_rewrite | The `RewriteRule` directive is the real rewriting workhorse. The directive can occur more than once, with each instance defining a single rewrite rule. The order in which these rules are defined is important - this is the order in which they will be applied at run-time. *Pattern* is a perl compatible regular expression. What this pattern is compared against varies depending on where the `RewriteRule` directive is defined. **What is matched?** * In `[VirtualHost](core#virtualhost)` context, The *Pattern* will initially be matched against the part of the URL after the hostname and port, and before the query string (e.g. "/app1/index.html"). This is the (%-decoded) URL-path. * In per-directory context (`[Directory](core#directory)` and .htaccess), the *Pattern* is matched against only a partial path, for example a request of "/app1/index.html" may result in comparison against "app1/index.html" or "index.html" depending on where the `RewriteRule` is defined. The directory path where the rule is defined is stripped from the currently mapped filesystem path before comparison (up to and including a trailing slash). The net result of this per-directory prefix stripping is that rules in this context only match against the portion of the currently mapped filesystem path "below" where the rule is defined. Directives such as `[DocumentRoot](core#documentroot)` and `[Alias](mod_alias#alias)`, or even the result of previous `RewriteRule` substitutions, determine the currently mapped filesystem path. * If you wish to match against the hostname, port, or query string, use a `[RewriteCond](#rewritecond)` with the `%{HTTP_HOST}`, `%{SERVER_PORT}`, or `%{QUERY_STRING}` variables respectively. **Per-directory Rewrites** * The rewrite engine may be used in [.htaccess](../howto/htaccess) files and in `[<Directory>](core#directory)` sections, with some additional complexity. * To enable the rewrite engine in this context, you need to set "`RewriteEngine On`" **and** "`Options FollowSymLinks`" must be enabled. If your administrator has disabled override of `FollowSymLinks` for a user's directory, then you cannot use the rewrite engine. This restriction is required for security reasons. * See the `[RewriteBase](#rewritebase)` directive for more information regarding what prefix will be added back to relative substitutions. * If you wish to match against the full URL-path in a per-directory (htaccess) RewriteRule, use the `%{REQUEST_URI}` variable in a `[RewriteCond](#rewritecond)`. * The removed prefix always ends with a slash, meaning the matching occurs against a string which *never* has a leading slash. Therefore, a *Pattern* with `^/` never matches in per-directory context. * Although rewrite rules are syntactically permitted in `[<Location>](core#location)` and `[<Files>](core#files)` sections (including their regular expression counterparts), this should never be necessary and is unsupported. A likely feature to break in these contexts is relative substitutions. * The `[If](core#if)` blocks follow the rules of the *directory* context. * By default, mod\_rewrite overrides rules when [merging sections](../sections#merging) belonging to the same context. The `[RewriteOptions](rewrite#rewriteoptions)` directive can change this behavior, for example using the *Inherit* setting. * The `[RewriteOptions](rewrite#rewriteoptions)` also regulates the behavior of sections that are stated at the same nesting level of the configuration. In the following example, by default only the RewriteRules stated in the second `[If](core#if)` block are considered, since the first ones are overridden. Using `[RewriteOptions](rewrite#rewriteoptions)` Inherit forces mod\_rewrite to merge the two sections and consider both set of statements, rather than only the last one. ``` <If "true"> # Without RewriteOptions Inherit, this rule is overridden by the next # section and no redirect will happen for URIs containing 'foo' RewriteRule foo http://example.com/foo [R] </If> <If "true"> RewriteRule bar http://example.com/bar [R] </If> ``` For some hints on [regular expressions](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"), see the [mod\_rewrite Introduction](../rewrite/intro#regex). In `<mod_rewrite>`, the NOT character ('`!`') is also available as a possible pattern prefix. This enables you to negate a pattern; to say, for instance: ``*if the current URL does **NOT** match this pattern*''. This can be used for exceptional cases, where it is easier to match the negative pattern, or as a last default rule. **Note** When using the NOT character to negate a pattern, you cannot include grouped wildcard parts in that pattern. This is because, when the pattern does NOT match (ie, the negation matches), there are no contents for the groups. Thus, if negated patterns are used, you cannot use `$N` in the substitution string! The *Substitution* of a rewrite rule is the string that replaces the original URL-path that was matched by *Pattern*. The *Substitution* may be a: file-system path Designates the location on the file-system of the resource to be delivered to the client. Substitutions are only treated as a file-system path when the rule is configured in server (virtualhost) context and the first component of the path in the substitution exists in the file-system URL-path A `[DocumentRoot](core#documentroot)`-relative path to the resource to be served. Note that `<mod_rewrite>` tries to guess whether you have specified a file-system path or a URL-path by checking to see if the first segment of the path exists at the root of the file-system. For example, if you specify a *Substitution* string of `/www/file.html`, then this will be treated as a URL-path *unless* a directory named `www` exists at the root or your file-system (or, in the case of using rewrites in a `.htaccess` file, relative to your document root), in which case it will be treated as a file-system path. If you wish other URL-mapping directives (such as `[Alias](mod_alias#alias)`) to be applied to the resulting URL-path, use the `[PT]` flag as described below. Absolute URL If an absolute URL is specified, `<mod_rewrite>` checks to see whether the hostname matches the current host. If it does, the scheme and hostname are stripped out and the resulting path is treated as a URL-path. Otherwise, an external redirect is performed for the given URL. To force an external redirect back to the current host, see the `[R]` flag below. `-` (dash) A dash indicates that no substitution should be performed (the existing path is passed through untouched). This is used when a flag (see below) needs to be applied without changing the path. In addition to plain text, the *Substitution* string can include 1. back-references (`$N`) to the RewriteRule pattern 2. back-references (`%N`) to the last matched RewriteCond pattern 3. server-variables as in rule condition test-strings (`%{VARNAME}`) 4. [mapping-function](#mapfunc) calls (`${mapname:key|default}`) Back-references are identifiers of the form `$`**N** (**N**=0..9), which will be replaced by the contents of the **N**th group of the matched *Pattern*. The server-variables are the same as for the *TestString* of a `[RewriteCond](#rewritecond)` directive. The mapping-functions come from the `[RewriteMap](#rewritemap)` directive and are explained there. These three types of variables are expanded in the order above. Rewrite rules are applied to the results of previous rewrite rules, in the order in which they are defined in the config file. The URL-path or file-system path (see ["What is matched?"](#what_is_matched), above) is **completely replaced** by the *Substitution* and the rewriting process continues until all rules have been applied, or it is explicitly terminated by an [`L` flag](../rewrite/flags#flag_l), or other flag which implies immediate termination, such as `END` or `F`. **Modifying the Query String** By default, the query string is passed through unchanged. You can, however, create URLs in the substitution string containing a query string part. Simply use a question mark inside the substitution string to indicate that the following text should be re-injected into the query string. When you want to erase an existing query string, end the substitution string with just a question mark. To combine new and old query strings, use the `[QSA]` flag. Additionally you can set special actions to be performed by appending **`[`*flags*`]`** as the third argument to the `RewriteRule` directive. *Flags* is a comma-separated list, surround by square brackets, of any of the flags in the following table. More details, and examples, for each flag, are available in the [Rewrite Flags document](../rewrite/flags). | Flag and syntax | Function | | --- | --- | | B | Escape non-alphanumeric characters in backreferences *before* applying the transformation. *[details ...](../rewrite/flags#flag_b)* | | backrefnoplus|BNP | If backreferences are being escaped, spaces should be escaped to %20 instead of +. Useful when the backreference will be used in the path component rather than the query string.*[details ...](../rewrite/flags#flag_bnp)* | | chain|C | Rule is chained to the following rule. If the rule fails, the rule(s) chained to it will be skipped. *[details ...](../rewrite/flags#flag_c)* | | cookie|CO=*NAME*:*VAL* | Sets a cookie in the client browser. Full syntax is: CO=*NAME*:*VAL*:*domain*[:*lifetime*[:*path*[:*secure*[:*httponly*[*samesite*]]]]] *[details ...](../rewrite/flags#flag_co)* | | discardpath|DPI | Causes the PATH\_INFO portion of the rewritten URI to be discarded. *[details ...](../rewrite/flags#flag_dpi)* | | END | Stop the rewriting process immediately and don't apply any more rules. Also prevents further execution of rewrite rules in per-directory and .htaccess context. (Available in 2.3.9 and later) *[details ...](../rewrite/flags#flag_end)* | | env|E=[!]*VAR*[:*VAL*] | Causes an environment variable *VAR* to be set (to the value *VAL* if provided). The form !*VAR* causes the environment variable *VAR* to be unset. *[details ...](../rewrite/flags#flag_e)* | | forbidden|F | Returns a 403 FORBIDDEN response to the client browser. *[details ...](../rewrite/flags#flag_f)* | | gone|G | Returns a 410 GONE response to the client browser. *[details ...](../rewrite/flags#flag_g)* | | Handler|H=*Content-handler* | Causes the resulting URI to be sent to the specified *Content-handler* for processing. *[details ...](../rewrite/flags#flag_h)* | | last|L | Stop the rewriting process immediately and don't apply any more rules. Especially note caveats for per-directory and .htaccess context (see also the END flag). *[details ...](../rewrite/flags#flag_l)* | | next|N | Re-run the rewriting process, starting again with the first rule, using the result of the ruleset so far as a starting point. *[details ...](../rewrite/flags#flag_n)* | | nocase|NC | Makes the pattern comparison case-insensitive. *[details ...](../rewrite/flags#flag_nc)* | | noescape|NE | Prevent mod\_rewrite from applying hexcode escaping of special characters in the result of the rewrite. *[details ...](../rewrite/flags#flag_ne)* | | nosubreq|NS | Causes a rule to be skipped if the current request is an internal sub-request. *[details ...](../rewrite/flags#flag_ns)* | | proxy|P | Force the substitution URL to be internally sent as a proxy request. *[details ...](../rewrite/flags#flag_p)* | | passthrough|PT | Forces the resulting URI to be passed back to the URL mapping engine for processing of other URI-to-filename translators, such as `Alias` or `Redirect`. *[details ...](../rewrite/flags#flag_pt)* | | qsappend|QSA | Appends any query string from the original request URL to any query string created in the rewrite target.*[details ...](../rewrite/flags#flag_qsa)* | | qsdiscard|QSD | Discard any query string attached to the incoming URI. *[details ...](../rewrite/flags#flag_qsd)* | | qslast|QSL | Interpret the last (right-most) question mark as the query string delimiter, instead of the first (left-most) as normally used. Available in 2.4.19 and later. *[details ...](../rewrite/flags#flag_qsl)* | | redirect|R[=*code*] | Forces an external redirect, optionally with the specified HTTP status code. *[details ...](../rewrite/flags#flag_r)* | | skip|S=*num* | Tells the rewriting engine to skip the next *num* rules if the current rule matches. *[details ...](../rewrite/flags#flag_s)* | | type|T=*MIME-type* | Force the [MIME-type](https://httpd.apache.org/docs/2.4/en/glossary.html#mime-type "see glossary") of the target file to be the specified type. *[details ...](../rewrite/flags#flag_t)* | **Home directory expansion** When the substitution string begins with a string resembling "/~user" (via explicit text or backreferences), `<mod_rewrite>` performs home directory expansion independent of the presence or configuration of `<mod_userdir>`. This expansion does not occur when the *PT* flag is used on the `[RewriteRule](#rewriterule)` directive. Here are all possible substitution combinations and their meanings: **Inside per-server configuration (`httpd.conf`) for request ```GET /somepath/pathinfo`'':** | Given Rule | Resulting Substitution | | --- | --- | | ^/somepath(.\*) otherpath$1 | invalid, not supported | | ^/somepath(.\*) otherpath$1 [R] | invalid, not supported | | ^/somepath(.\*) otherpath$1 [P] | invalid, not supported | | ^/somepath(.\*) /otherpath$1 | /otherpath/pathinfo | | ^/somepath(.\*) /otherpath$1 [R] | http://thishost/otherpath/pathinfo via external redirection | | ^/somepath(.\*) /otherpath$1 [P] | doesn't make sense, not supported | | ^/somepath(.\*) http://thishost/otherpath$1 | /otherpath/pathinfo | | ^/somepath(.\*) http://thishost/otherpath$1 [R] | http://thishost/otherpath/pathinfo via external redirection | | ^/somepath(.\*) http://thishost/otherpath$1 [P] | doesn't make sense, not supported | | ^/somepath(.\*) http://otherhost/otherpath$1 | http://otherhost/otherpath/pathinfo via external redirection | | ^/somepath(.\*) http://otherhost/otherpath$1 [R] | http://otherhost/otherpath/pathinfo via external redirection (the [R] flag is redundant) | | ^/somepath(.\*) http://otherhost/otherpath$1 [P] | http://otherhost/otherpath/pathinfo via internal proxy | **Inside per-directory configuration for `/somepath` (`/physical/path/to/somepath/.htaccess`, with `RewriteBase "/somepath"`) for request ```GET /somepath/localpath/pathinfo`'':** | Given Rule | Resulting Substitution | | --- | --- | | ^localpath(.\*) otherpath$1 | /somepath/otherpath/pathinfo | | ^localpath(.\*) otherpath$1 [R] | http://thishost/somepath/otherpath/pathinfo via external redirection | | ^localpath(.\*) otherpath$1 [P] | doesn't make sense, not supported | | ^localpath(.\*) /otherpath$1 | /otherpath/pathinfo | | ^localpath(.\*) /otherpath$1 [R] | http://thishost/otherpath/pathinfo via external redirection | | ^localpath(.\*) /otherpath$1 [P] | doesn't make sense, not supported | | ^localpath(.\*) http://thishost/otherpath$1 | /otherpath/pathinfo | | ^localpath(.\*) http://thishost/otherpath$1 [R] | http://thishost/otherpath/pathinfo via external redirection | | ^localpath(.\*) http://thishost/otherpath$1 [P] | doesn't make sense, not supported | | ^localpath(.\*) http://otherhost/otherpath$1 | http://otherhost/otherpath/pathinfo via external redirection | | ^localpath(.\*) http://otherhost/otherpath$1 [R] | http://otherhost/otherpath/pathinfo via external redirection (the [R] flag is redundant) | | ^localpath(.\*) http://otherhost/otherpath$1 [P] | http://otherhost/otherpath/pathinfo via internal proxy |
programming_docs
apache_http_server Apache Module mod_auth_basic Apache Module mod\_auth\_basic ============================== | | | | --- | --- | | Description: | Basic HTTP authentication | | Status: | Base | | Module Identifier: | auth\_basic\_module | | Source File: | mod\_auth\_basic.c | | Compatibility: | Available in Apache 2.1 and later | ### Summary This module allows the use of HTTP Basic Authentication to restrict access by looking up users in the given providers. HTTP Digest Authentication is provided by `<mod_auth_digest>`. This module should usually be combined with at least one authentication module such as `<mod_authn_file>` and one authorization module such as `<mod_authz_user>`. AuthBasicAuthoritative Directive -------------------------------- | | | | --- | --- | | Description: | Sets whether authorization and authentication are passed to lower level modules | | Syntax: | ``` AuthBasicAuthoritative On|Off ``` | | Default: | ``` AuthBasicAuthoritative On ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_auth\_basic | Normally, each authorization module listed in `[AuthBasicProvider](#authbasicprovider)` will attempt to verify the user, and if the user is not found in any provider, access will be denied. Setting the `AuthBasicAuthoritative` directive explicitly to `Off` allows for both authentication and authorization to be passed on to other non-provider-based modules if there is **no userID** or **rule** matching the supplied userID. This should only be necessary when combining `<mod_auth_basic>` with third-party modules that are not configured with the `[AuthBasicProvider](#authbasicprovider)` directive. When using such modules, the order of processing is determined in the modules' source code and is not configurable. AuthBasicFake Directive ----------------------- | | | | --- | --- | | Description: | Fake basic authentication using the given expressions for username and password | | Syntax: | ``` AuthBasicFake off|username [password] ``` | | Default: | `none` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_auth\_basic | | Compatibility: | Apache HTTP Server 2.4.5 and later | The username and password specified are combined into an Authorization header, which is passed to the server or service behind the webserver. Both the username and password fields are interpreted using the [expression parser](../expr), which allows both the username and password to be set based on request parameters. If the password is not specified, the default value "password" will be used. To disable fake basic authentication for an URL space, specify "AuthBasicFake off". In this example, we pass a fixed username and password to a backend server. ### Fixed Example ``` <Location "/demo"> AuthBasicFake demo demopass </Location> ``` In this example, we pass the email address extracted from a client certificate, extending the functionality of the FakeBasicAuth option within the `[SSLOptions](mod_ssl#ssloptions)` directive. Like the FakeBasicAuth option, the password is set to the fixed string "password". ### Certificate Example ``` <Location "/secure"> AuthBasicFake "%{SSL_CLIENT_S_DN_Email}" </Location> ``` Extending the above example, we generate a password by hashing the email address with a fixed passphrase, and passing the hash to the backend server. This can be used to gate into legacy systems that do not support client certificates. ### Password Example ``` <Location "/secure"> AuthBasicFake "%{SSL_CLIENT_S_DN_Email}" "%{sha1:passphrase-%{SSL_CLIENT_S_DN_Email}}" </Location> ``` ### Exclusion Example ``` <Location "/public"> AuthBasicFake off </Location> ``` AuthBasicProvider Directive --------------------------- | | | | --- | --- | | Description: | Sets the authentication provider(s) for this location | | Syntax: | ``` AuthBasicProvider provider-name [provider-name] ... ``` | | Default: | ``` AuthBasicProvider file ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_auth\_basic | The `AuthBasicProvider` directive sets which provider is used to authenticate the users for this location. The default `file` provider is implemented by the `<mod_authn_file>` module. Make sure that the chosen provider module is present in the server. ### Example ``` <Location "/secure"> AuthType basic AuthName "private area" AuthBasicProvider dbm AuthDBMType SDBM AuthDBMUserFile "/www/etc/dbmpasswd" Require valid-user </Location> ``` Providers are queried in order until a provider finds a match for the requested username, at which point this sole provider will attempt to check the password. A failure to verify the password does not result in control being passed on to subsequent providers. Providers are implemented by `<mod_authn_dbm>`, `<mod_authn_file>`, `<mod_authn_dbd>`, `<mod_authnz_ldap>` and `<mod_authn_socache>`. AuthBasicUseDigestAlgorithm Directive ------------------------------------- | | | | --- | --- | | Description: | Check passwords against the authentication providers as if Digest Authentication was in force instead of Basic Authentication. | | Syntax: | ``` AuthBasicUseDigestAlgorithm MD5|Off ``` | | Default: | ``` AuthBasicUseDigestAlgorithm Off ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_auth\_basic | | Compatibility: | Apache HTTP Server 2.4.7 and later | Normally, when using Basic Authentication, the providers listed in `[AuthBasicProvider](#authbasicprovider)` attempt to verify a user by checking their data stores for a matching username and associated password. The stored passwords are usually encrypted, but not necessarily so; each provider may choose its own storage scheme for passwords. When using `[AuthDigestProvider](mod_auth_digest#authdigestprovider)` and Digest Authentication, providers perform a similar check to find a matching username in their data stores. However, unlike in the Basic Authentication case, the value associated with each stored username must be an encrypted string composed from the username, realm name, and password. (See [RFC 2617, Section 3.2.2.2](http://tools.ietf.org/html/rfc2617#section-3.2.2.2) for more details on the format used for this encrypted string.) As a consequence of the difference in the stored values between Basic and Digest Authentication, converting from Digest Authentication to Basic Authentication generally requires that all users be assigned new passwords, as their existing passwords cannot be recovered from the password storage scheme imposed on those providers which support Digest Authentication. Setting the `AuthBasicUseDigestAlgorithm` directive to `MD5` will cause the user's Basic Authentication password to be checked using the same encrypted format as for Digest Authentication. First a string composed from the username, realm name, and password is hashed with MD5; then the username and this encrypted string are passed to the providers listed in `[AuthBasicProvider](#authbasicprovider)` as if `[AuthType](mod_authn_core#authtype)` was set to `Digest` and Digest Authentication was in force. Through the use of `AuthBasicUseDigestAlgorithm` a site may switch from Digest to Basic Authentication without requiring users to be assigned new passwords. The inverse process of switching from Basic to Digest Authentication without assigning new passwords is generally not possible. Only if the Basic Authentication passwords have been stored in plain text or with a reversible encryption scheme will it be possible to recover them and generate a new data store following the Digest Authentication password storage scheme. Only providers which support Digest Authentication will be able to authenticate users when `AuthBasicUseDigestAlgorithm` is set to `MD5`. Use of other providers will result in an error response and the client will be denied access. apache_http_server Apache MPM winnt Apache MPM winnt ================ | | | | --- | --- | | Description: | Multi-Processing Module optimized for Windows NT. | | Status: | MPM | | Module Identifier: | mpm\_winnt\_module | | Source File: | mpm\_winnt.c | ### Summary This Multi-Processing Module (MPM) is the default for the Windows NT operating systems. It uses a single control process which launches a single child process which in turn creates threads to handle requests Capacity is configured using the `[ThreadsPerChild](mpm_common#threadsperchild)` directive, which sets the maximum number of concurrent client connections. By default, this MPM uses advanced Windows APIs for accepting new client connections. In some configurations, third-party products may interfere with this implementation, with the following messages written to the web server log: ``` Child: Encountered too many AcceptEx faults accepting client connections. winnt_mpm: falling back to 'AcceptFilter none'. ``` The MPM falls back to a safer implementation, but some client requests were not processed correctly. In order to avoid this error, use `[AcceptFilter](core#acceptfilter)` with accept filter `none`. ``` AcceptFilter http none AcceptFilter https none ``` *In Apache httpd 2.0 and 2.2, `Win32DisableAcceptEx` was used for this purpose.* The WinNT MPM differs from the Unix MPMs such as worker and event in several areas: * When a child process is exiting due to shutdown, restart, or `[MaxConnectionsPerChild](mpm_common#maxconnectionsperchild)`, active requests in the exiting process have `[TimeOut](core#timeout)` seconds to finish before processing is aborted. Alternate types of restart and shutdown are not implemented. * New child processes read the configuration files instead of inheriting the configuration from the parent. The behavior will be the same as on Unix if the child process is created at startup or restart, but if a child process is created because the prior one crashed or reached `[MaxConnectionsPerChild](mpm_common#maxconnectionsperchild)`, any pending changes to the configuration will become active in the child at that point, and the parent and child will be using a different configuration. If planned configuration changes have been partially implemented and the current configuration cannot be parsed, the replacement child process cannot start up and the server will halt. Because of this behavior, configuration files should not be changed until the time of a server restart. * The `monitor` and `fatal_exception` hooks are not currently implemented. * `AcceptFilter` is implemented in the MPM and has a different type of control over handling of new connections. (Refer to the `[AcceptFilter](core#acceptfilter)` documentation for details.) apache_http_server Apache Module mod_unique_id Apache Module mod\_unique\_id ============================= | | | | --- | --- | | Description: | Provides an environment variable with a unique identifier for each request | | Status: | Extension | | Module Identifier: | unique\_id\_module | | Source File: | mod\_unique\_id.c | ### Summary This module provides a magic token for each request which is guaranteed to be unique across "all" requests under very specific conditions. The unique identifier is even unique across multiple machines in a properly configured cluster of machines. The environment variable `UNIQUE_ID` is set to the identifier for each request. Unique identifiers are useful for various reasons which are beyond the scope of this document. Theory ------ First a brief recap of how the Apache server works on Unix machines. This feature currently isn't supported on Windows NT. On Unix machines, Apache creates several children, the children process requests one at a time. Each child can serve multiple requests in its lifetime. For the purpose of this discussion, the children don't share any data with each other. We'll refer to the children as httpd processes. Your website has one or more machines under your administrative control, together we'll call them a cluster of machines. Each machine can possibly run multiple instances of Apache. All of these collectively are considered "the universe", and with certain assumptions we'll show that in this universe we can generate unique identifiers for each request, without extensive communication between machines in the cluster. The machines in your cluster should satisfy these requirements. (Even if you have only one machine you should synchronize its clock with NTP.) * The machines' times are synchronized via NTP or other network time protocol. * The machines' hostnames all differ, such that the module can do a hostname lookup on the hostname and receive a different IP address for each machine in the cluster. As far as operating system assumptions go, we assume that pids (process ids) fit in 32-bits. If the operating system uses more than 32-bits for a pid, the fix is trivial but must be performed in the code. Given those assumptions, at a single point in time we can identify any httpd process on any machine in the cluster from all other httpd processes. The machine's IP address and the pid of the httpd process are sufficient to do this. A httpd process can handle multiple requests simultaneously if you use a multi-threaded MPM. In order to identify threads, we use a thread index Apache httpd uses internally. So in order to generate unique identifiers for requests we need only distinguish between different points in time. To distinguish time we will use a Unix timestamp (seconds since January 1, 1970 UTC), and a 16-bit counter. The timestamp has only one second granularity, so the counter is used to represent up to 65536 values during a single second. The quadruple *( ip\_addr, pid, time\_stamp, counter )* is sufficient to enumerate 65536 requests per second per httpd process. There are issues however with pid reuse over time, and the counter is used to alleviate this issue. When an httpd child is created, the counter is initialized with ( current microseconds divided by 10 ) modulo 65536 (this formula was chosen to eliminate some variance problems with the low order bits of the microsecond timers on some systems). When a unique identifier is generated, the time stamp used is the time the request arrived at the web server. The counter is incremented every time an identifier is generated (and allowed to roll over). The kernel generates a pid for each process as it forks the process, and pids are allowed to roll over (they're 16-bits on many Unixes, but newer systems have expanded to 32-bits). So over time the same pid will be reused. However unless it is reused within the same second, it does not destroy the uniqueness of our quadruple. That is, we assume the system does not spawn 65536 processes in a one second interval (it may even be 32768 processes on some Unixes, but even this isn't likely to happen). Suppose that time repeats itself for some reason. That is, suppose that the system's clock is screwed up and it revisits a past time (or it is too far forward, is reset correctly, and then revisits the future time). In this case we can easily show that we can get pid and time stamp reuse. The choice of initializer for the counter is intended to help defeat this. Note that we really want a random number to initialize the counter, but there aren't any readily available numbers on most systems (*i.e.*, you can't use rand() because you need to seed the generator, and can't seed it with the time because time, at least at one second resolution, has repeated itself). This is not a perfect defense. How good a defense is it? Suppose that one of your machines serves at most 500 requests per second (which is a very reasonable upper bound at this writing, because systems generally do more than just shovel out static files). To do that it will require a number of children which depends on how many concurrent clients you have. But we'll be pessimistic and suppose that a single child is able to serve 500 requests per second. There are 1000 possible starting counter values such that two sequences of 500 requests overlap. So there is a 1.5% chance that if time (at one second resolution) repeats itself this child will repeat a counter value, and uniqueness will be broken. This was a very pessimistic example, and with real world values it's even less likely to occur. If your system is such that it's still likely to occur, then perhaps you should make the counter 32 bits (by editing the code). You may be concerned about the clock being "set back" during summer daylight savings. However this isn't an issue because the times used here are UTC, which "always" go forward. Note that x86 based Unixes may need proper configuration for this to be true -- they should be configured to assume that the motherboard clock is on UTC and compensate appropriately. But even still, if you're running NTP then your UTC time will be correct very shortly after reboot. The `UNIQUE_ID` environment variable is constructed by encoding the 144-bit (32-bit IP address, 32 bit pid, 32 bit time stamp, 16 bit counter, 32 bit thread index) quadruple using the alphabet `[A-Za-z0-9@-]` in a manner similar to MIME base64 encoding, producing 24 characters. The MIME base64 alphabet is actually `[A-Za-z0-9+/]` however `+` and `/` need to be specially encoded in URLs, which makes them less desirable. All values are encoded in network byte ordering so that the encoding is comparable across architectures of different byte ordering. The actual ordering of the encoding is: time stamp, IP address, pid, counter. This ordering has a purpose, but it should be emphasized that applications should not dissect the encoding. Applications should treat the entire encoded `UNIQUE_ID` as an opaque token, which can be compared against other `UNIQUE_ID`s for equality only. The ordering was chosen such that it's possible to change the encoding in the future without worrying about collision with an existing database of `UNIQUE_ID`s. The new encodings should also keep the time stamp as the first element, and can otherwise use the same alphabet and bit length. Since the time stamps are essentially an increasing sequence, it's sufficient to have a *flag second* in which all machines in the cluster stop serving any request, and stop using the old encoding format. Afterwards they can resume requests and begin issuing the new encodings. This we believe is a relatively portable solution to this problem. The identifiers generated have essentially an infinite life-time because future identifiers can be made longer as required. Essentially no communication is required between machines in the cluster (only NTP synchronization is required, which is low overhead), and no communication between httpd processes is required (the communication is implicit in the pid value assigned by the kernel). In very specific situations the identifier can be shortened, but more information needs to be assumed (for example the 32-bit IP address is overkill for any site, but there is no portable shorter replacement for it). apache_http_server Apache MPM event Apache MPM event ================ | | | | --- | --- | | Description: | A variant of the `<worker>` MPM with the goal of consuming threads only for connections with active processing | | Status: | MPM | | Module Identifier: | mpm\_event\_module | | Source File: | event.c | ### Summary The `<event>` Multi-Processing Module (MPM) is designed to allow more requests to be served simultaneously by passing off some processing work to the listeners threads, freeing up the worker threads to serve new requests. To use the `<event>` MPM, add `--with-mpm=event` to the `[configure](../programs/configure)` script's arguments when building the `[httpd](../programs/httpd)`. Relationship with the Worker MPM -------------------------------- `<event>` is based on the `<worker>` MPM, which implements a hybrid multi-process multi-threaded server. A single control process (the parent) is responsible for launching child processes. Each child process creates a fixed number of server threads as specified in the `[ThreadsPerChild](mpm_common#threadsperchild)` directive, as well as a listener thread which listens for connections and passes them to a worker thread for processing when they arrive. Run-time configuration directives are identical to those provided by `<worker>`, with the only addition of the `AsyncRequestWorkerFactor`. How it Works ------------ This MPM tries to fix the 'keep alive problem' in HTTP. After a client completes the first request, it can keep the connection open, sending further requests using the same socket and saving significant overhead in creating TCP connections. However, Apache HTTP Server traditionally keeps an entire child process/thread waiting for data from the client, which brings its own disadvantages. To solve this problem, this MPM uses a dedicated listener thread for each process to handle both the Listening sockets, all sockets that are in a Keep Alive state, sockets where the handler and protocol filters have done their work and the ones where the only remaining thing to do is send the data to the client. This new architecture, leveraging non-blocking sockets and modern kernel features exposed by [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary") (like Linux's epoll), no longer requires the `mpm-accept` `[Mutex](core#mutex)` configured to avoid the thundering herd problem. The total amount of connections that a single process/threads block can handle is regulated by the `AsyncRequestWorkerFactor` directive. ### Async connections Async connections would need a fixed dedicated worker thread with the previous MPMs but not with event. The status page of `<mod_status>` shows new columns under the Async connections section: Writing While sending the response to the client, it might happen that the TCP write buffer fills up because the connection is too slow. Usually in this case, a `write()` to the socket returns `EWOULDBLOCK` or `EAGAIN` to become writable again after an idle time. The worker holding the socket might be able to offload the waiting task to the listener thread, that in turn will re-assign it to the first idle worker thread available once an event will be raised for the socket (for example, "the socket is now writable"). Please check the Limitations section for more information. Keep-alive Keep Alive handling is the most basic improvement from the worker MPM. Once a worker thread finishes to flush the response to the client, it can offload the socket handling to the listener thread, that in turn will wait for any event from the OS, like "the socket is readable". If any new request comes from the client, then the listener will forward it to the first worker thread available. Conversely, if the `[KeepAliveTimeout](core#keepalivetimeout)` occurs then the socket will be closed by the listener. In this way, the worker threads are not responsible for idle sockets, and they can be re-used to serve other requests. Closing Sometimes the MPM needs to perform a lingering close, namely sending back an early error to the client while it is still transmitting data to httpd. Sending the response and then closing the connection immediately is not the correct thing to do since the client (still trying to send the rest of the request) would get a connection reset and could not read the httpd's response. The lingering close is time-bounded, but it can take a relatively long time, so it's offloaded to a worker thread (including the shutdown hooks and real socket close). From 2.4.28 onward, this is also the case when connections finally timeout (the listener thread never handles connections besides waiting for and dispatching their events). These improvements are valid for both HTTP/HTTPS connections. ### Graceful process termination and Scoreboard usage This mpm showed some scalability bottlenecks in the past, leading to the following error: "**scoreboard is full, not at MaxRequestWorkers**". `[MaxRequestWorkers](mpm_common#maxrequestworkers)` limits the number of simultaneous requests that will be served at any given time and also the number of allowed processes (`[MaxRequestWorkers](mpm_common#maxrequestworkers)` / `[ThreadsPerChild](mpm_common#threadsperchild)`); meanwhile, the Scoreboard is a representation of all the running processes and the status of their worker threads. If the scoreboard is full (so all the threads have a state that is not idle) but the number of active requests served is not `[MaxRequestWorkers](mpm_common#maxrequestworkers)`, it means that some of them are blocking new requests that could be served but that are queued instead (up to the limit imposed by `[ListenBacklog](mpm_common#listenbacklog)`). Most of the time, the threads are stuck in the Graceful state, namely they are waiting to finish their work with a TCP connection to safely terminate and free up a scoreboard slot (for example, handling long-running requests, slow clients or connections with keep-alive enabled). Two scenarios are very common: * During a [graceful restart](../stopping#graceful), the parent process signals all its children to complete their work and terminate, while it reloads the config and forks new processes. If the old children keep running for a while before stopping, the scoreboard will be partially occupied until their slots are freed. * The server load goes down in a way that causes httpd to stop some processes (for example, due to `[MaxSpareThreads](mpm_common#maxsparethreads)`). This is particularly problematic because when the load increases again, httpd will try to start new processes. If the pattern repeats, the number of processes can rise quite a bit, ending up in a mixture of old processes trying to stop and new ones trying to do some work. From 2.4.24 onward, mpm-event is smarter and it is able to handle graceful terminations in a much better way. Some of the improvements are: * Allow the use of all the scoreboard slots up to `[ServerLimit](mpm_common#serverlimit)`. `[MaxRequestWorkers](mpm_common#maxrequestworkers)` and `[ThreadsPerChild](mpm_common#threadsperchild)` are used to limit the amount of active processes; meanwhile, `[ServerLimit](mpm_common#serverlimit)` takes also into account the ones doing a graceful close to allow extra slots when needed. The idea is to use `[ServerLimit](mpm_common#serverlimit)` to instruct httpd about how many overall processes are tolerated before impacting the system resources. * Force gracefully finishing processes to close their connections in keep-alive state. * During graceful shutdown, if there are more running worker threads than open connections for a given process, terminate these threads to free resources faster (which may be needed for new processes). * If the scoreboard is full, prevent more processes from finishing gracefully due to reduced load until old processes have terminated (otherwise the situation would get worse once the load increases again). The behavior described in the last point is completely observable via `<mod_status>` in the connection summary table through two new columns: "Slot" and "Stopping". The former indicates the PID and the latter if the process is stopping or not; the extra state "Yes (old gen)" indicates a process still running after a graceful restart. ### Limitations The improved connection handling may not work for certain connection filters that have declared themselves as incompatible with event. In these cases, this MPM will fall back to the behavior of the `<worker>` MPM and reserve one worker thread per connection. All modules shipped with the server are compatible with the event MPM. A similar restriction is currently present for requests involving an output filter that needs to read and/or modify the whole response body. If the connection to the client blocks while the filter is processing the data, and the amount of data produced by the filter is too big to be buffered in memory, the thread used for the request is not freed while httpd waits until the pending data is sent to the client. To illustrate this point, we can think about the following two situations: serving a static asset (like a CSS file) versus serving content retrieved from FCGI/CGI or a proxied server. The former is predictable, namely the event MPM has full visibility on the end of the content and it can use events: the worker thread serving the response content can flush the first bytes until `EWOULDBLOCK` or `EAGAIN` is returned, delegating the rest to the listener. This one in turn waits for an event on the socket and delegates the work to flush the rest of the content to the first idle worker thread. Meanwhile in the latter example (FCGI/CGI/proxied content), the MPM can't predict the end of the response and a worker thread has to finish its work before returning the control to the listener. The only alternative is to buffer the response in memory, but it wouldn't be the safest option for the sake of the server's stability and memory footprint. ### Background material The event model was made possible by the introduction of new APIs into the supported operating systems: * epoll (Linux) * kqueue (BSD) * event ports (Solaris) Before these new APIs where made available, the traditional `select` and `poll` APIs had to be used. Those APIs get slow if used to handle many connections or if the set of connections rate of change is high. The new APIs allow to monitor many more connections, and they perform way better when the set of connections to monitor changes frequently. So these APIs made it possible to write the event MPM, that scales much better with the typical HTTP pattern of many idle connections. The MPM assumes that the underlying `apr_pollset` implementation is reasonably threadsafe. This enables the MPM to avoid excessive high level locking, or having to wake up the listener thread in order to send it a keep-alive socket. This is currently only compatible with KQueue and EPoll. Requirements ------------ This MPM depends on [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary")'s atomic compare-and-swap operations for thread synchronization. If you are compiling for an x86 target and you don't need to support 386s, or you are compiling for a SPARC and you don't need to run on pre-UltraSPARC chips, add `--enable-nonportable-atomics=yes` to the `[configure](../programs/configure)` script's arguments. This will cause APR to implement atomic operations using efficient opcodes not available in older CPUs. This MPM does not perform well on older platforms which lack good threading, but the requirement for EPoll or KQueue makes this moot. * To use this MPM on FreeBSD, FreeBSD 5.3 or higher is recommended. However, it is possible to run this MPM on FreeBSD 5.2.1 if you use `libkse` (see `man libmap.conf`). * For NetBSD, at least version 2.0 is recommended. * For Linux, a 2.6 kernel is recommended. It is also necessary to ensure that your version of `glibc` has been compiled with support for EPoll. AsyncRequestWorkerFactor Directive ---------------------------------- | | | | --- | --- | | Description: | Limit concurrent connections per process | | Syntax: | ``` AsyncRequestWorkerFactor factor ``` | | Default: | `2` | | Context: | server config | | Status: | MPM | | Module: | event | | Compatibility: | Available in version 2.3.13 and later | The event MPM handles some connections in an asynchronous way, where request worker threads are only allocated for short periods of time as needed, and other connections with one request worker thread reserved per connection. This can lead to situations where all workers are tied up and no worker thread is available to handle new work on established async connections. To mitigate this problem, the event MPM does two things: * It limits the number of connections accepted per process, depending on the number of idle request workers; * If all workers are busy, it will close connections in keep-alive state even if the keep-alive timeout has not expired. This allows the respective clients to reconnect to a different process which may still have worker threads available. This directive can be used to fine-tune the per-process connection limit. A **process** will only accept new connections if the current number of connections (not counting connections in the "closing" state) is lower than: **`[ThreadsPerChild](mpm_common#threadsperchild)` + (`AsyncRequestWorkerFactor` \* number of idle workers)** An estimation of the maximum concurrent connections across all the processes given an average value of idle worker threads can be calculated with: **(`[ThreadsPerChild](mpm_common#threadsperchild)` + (`AsyncRequestWorkerFactor` \* number of idle workers)) \* `[ServerLimit](mpm_common#serverlimit)`** **Example** ``` ThreadsPerChild = 10 ServerLimit = 4 AsyncRequestWorkerFactor = 2 MaxRequestWorkers = 40 idle_workers = 4 (average for all the processes to keep it simple) max_connections = (ThreadsPerChild + (AsyncRequestWorkerFactor * idle_workers)) * ServerLimit = (10 + (2 * 4)) * 4 = 72 ``` When all the worker threads are idle, then absolute maximum numbers of concurrent connections can be calculared in a simpler way: **(`AsyncRequestWorkerFactor` + 1) \* `[MaxRequestWorkers](mpm_common#maxrequestworkers)`** **Example** ``` ThreadsPerChild = 10 ServerLimit = 4 MaxRequestWorkers = 40 AsyncRequestWorkerFactor = 2 ``` If all the processes have all threads idle then: ``` idle_workers = 10 ``` We can calculate the absolute maximum numbers of concurrent connections in two ways: ``` max_connections = (ThreadsPerChild + (AsyncRequestWorkerFactor * idle_workers)) * ServerLimit = (10 + (2 * 10)) * 4 = 120 max_connections = (AsyncRequestWorkerFactor + 1) * MaxRequestWorkers = (2 + 1) * 40 = 120 ``` Tuning `AsyncRequestWorkerFactor` requires knowledge about the traffic handled by httpd in each specific use case, so changing the default value requires extensive testing and data gathering from `<mod_status>`. `[MaxRequestWorkers](mpm_common#maxrequestworkers)` was called `MaxClients` prior to version 2.3.13. The above value shows that the old name did not accurately describe its meaning for the event MPM. `AsyncRequestWorkerFactor` can take non-integer arguments, e.g "1.5".
programming_docs
apache_http_server Apache Module mod_authn_socache Apache Module mod\_authn\_socache ================================= | | | | --- | --- | | Description: | Manages a cache of authentication credentials to relieve the load on backends | | Status: | Base | | Module Identifier: | authn\_socache\_module | | Source File: | mod\_authn\_socache.c | | Compatibility: | Version 2.3 and later | ### Summary Maintains a cache of authentication credentials, so that a new backend lookup is not required for every authenticated request. Authentication Caching ---------------------- Some users of more heavyweight authentication such as SQL database lookups (`<mod_authn_dbd>`) have reported it putting an unacceptable load on their authentication provider. A typical case in point is where an HTML page contains hundreds of objects (images, scripts, stylesheets, media, etc), and a request to the page generates hundreds of effectively-immediate requests for authenticated additional contents. `<mod_authn_socache>` provides a solution to this problem by maintaining a cache of authentication credentials. Usage ----- The authentication cache should be used where authentication lookups impose a significant load on the server, or a backend or network. Authentication by file (`<mod_authn_file>`) or dbm (`<mod_authn_dbm>`) are unlikely to benefit, as these are fast and lightweight in their own right (though in some cases, such as a network-mounted file, caching may be worthwhile). Other providers such as SQL or LDAP based authentication are more likely to benefit, particularly where there is an observed performance issue. Amongst the standard modules, `<mod_authnz_ldap>` manages its own cache, so only `<mod_authn_dbd>` will usually benefit from this cache. The basic rules to cache for a provider are: 1. Include the provider you're caching for in an `[AuthnCacheProvideFor](#authncacheprovidefor)` directive. 2. List socache ahead of the provider you're caching for in your `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` or `[AuthDigestProvider](mod_auth_digest#authdigestprovider)` directive. A simple usage example to accelerate `<mod_authn_dbd>` using dbm as a cache engine: ``` #AuthnCacheSOCache is optional. If specified, it is server-wide AuthnCacheSOCache dbm <Directory "/usr/www/myhost/private"> AuthType Basic AuthName "Cached Authentication Example" AuthBasicProvider socache dbd AuthDBDUserPWQuery "SELECT password FROM authn WHERE user = %s" AuthnCacheProvideFor dbd Require valid-user #Optional AuthnCacheContext dbd-authn-example </Directory> ``` Caching with custom modules --------------------------- Module developers should note that their modules must be enabled for caching with `<mod_authn_socache>`. A single optional API function ap\_authn\_cache\_store is provided to cache credentials a provider has just looked up or generated. Usage examples are available in [r957072](http://svn.eu.apache.org/viewvc?view=revision&revision=957072), in which three authn providers are enabled for caching. AuthnCacheContext Directive --------------------------- | | | | --- | --- | | Description: | Specify a context string for use in the cache key | | Syntax: | ``` AuthnCacheContext directory|server|custom-string ``` | | Default: | ``` AuthnCacheContext directory ``` | | Context: | directory | | Status: | Base | | Module: | mod\_authn\_socache | This directive specifies a string to be used along with the supplied username (and realm in the case of Digest Authentication) in constructing a cache key. This serves to disambiguate identical usernames serving different authentication areas on the server. Two special values for this are `directory`, which uses the directory context of the request as a string, and `server` which uses the virtual host name. The default is `directory`, which is also the most conservative setting. This is likely to be less than optimal, as it (for example) causes $app-base, $app-base/images, $app-base/scripts and $app-base/media each to have its own separate cache key. A better policy is to name the `AuthnCacheContext` for the password provider: for example a htpasswd file or database table. Contexts can be shared across different areas of a server, where credentials are shared. However, this has potential to become a vector for cross-site or cross-application security breaches, so this directive is not permitted in .htaccess contexts. AuthnCacheEnable Directive -------------------------- | | | | --- | --- | | Description: | Enable Authn caching configured anywhere | | Syntax: | `AuthnCacheEnable` | | Context: | server config | | Status: | Base | | Module: | mod\_authn\_socache | This directive is not normally necessary: it is implied if authentication caching is enabled anywhere in httpd.conf. However, if it is not enabled anywhere in httpd.conf it will by default not be initialised, and is therefore not available in a .htaccess context. This directive ensures it is initialised so it can be used in .htaccess. AuthnCacheProvideFor Directive ------------------------------ | | | | --- | --- | | Description: | Specify which authn provider(s) to cache for | | Syntax: | ``` AuthnCacheProvideFor authn-provider [...] ``` | | Default: | `None` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_authn\_socache | This directive specifies an authentication provider or providers to cache for. Credentials found by a provider not listed in an `AuthnCacheProvideFor` directive will not be cached. For example, to cache credentials found by `<mod_authn_dbd>` or by a custom provider myprovider, but leave those looked up by lightweight providers like file or dbm lookup alone: ``` AuthnCacheProvideFor dbd myprovider ``` AuthnCacheSOCache Directive --------------------------- | | | | --- | --- | | Description: | Select socache backend provider to use | | Syntax: | ``` AuthnCacheSOCache provider-name[:provider-args] ``` | | Context: | server config | | Status: | Base | | Module: | mod\_authn\_socache | | Compatibility: | Optional provider arguments are available in Apache HTTP Server 2.4.7 and later | This is a server-wide setting to select a provider for the [shared object cache](../socache), followed by optional arguments for that provider. Some possible values for provider-name are "dbm", "dc", "memcache", or "shmcb", each subject to the appropriate module being loaded. If not set, your platform's default will be used. AuthnCacheTimeout Directive --------------------------- | | | | --- | --- | | Description: | Set a timeout for cache entries | | Syntax: | ``` AuthnCacheTimeout timeout (seconds) ``` | | Default: | ``` AuthnCacheTimeout 300 (5 minutes) ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_authn\_socache | Caching authentication data can be a security issue, though short-term caching is unlikely to be a problem. Typically a good solution is to cache credentials for as long as it takes to relieve the load on a backend, but no longer, though if changes to your users and passwords are infrequent then a longer timeout may suit you. The default 300 seconds (5 minutes) is both cautious and ample to keep the load on a backend such as dbd (SQL database queries) down. This should not be confused with session timeout, which is an entirely separate issue. However, you may wish to check your session-management software for whether cached credentials can "accidentally" extend a session, and bear it in mind when setting your timeout. apache_http_server Apache Module mod_mime Apache Module mod\_mime ======================= | | | | --- | --- | | Description: | Associates the requested filename's extensions with the file's behavior (handlers and filters) and content (mime-type, language, character set and encoding) | | Status: | Base | | Module Identifier: | mime\_module | | Source File: | mod\_mime.c | ### Summary This module is used to assign content metadata to the content selected for an HTTP response by mapping patterns in the URI or filenames to the metadata values. For example, the filename extensions of content files often define the content's Internet media type, language, character set, and content-encoding. This information is sent in HTTP messages containing that content and used in content negotiation when selecting alternatives, such that the user's preferences are respected when choosing one of several possible contents to serve. See `<mod_negotiation>` for more information about [content negotiation](../content-negotiation). The directives `[AddCharset](#addcharset)`, `[AddEncoding](#addencoding)`, `[AddLanguage](#addlanguage)` and `[AddType](#addtype)` are all used to map file extensions onto the metadata for that file. Respectively they set the character set, content-encoding, content-language, and [media-type](https://httpd.apache.org/docs/2.4/en/glossary.html#media-type "see glossary") (content-type) of documents. The directive `[TypesConfig](#typesconfig)` is used to specify a file which also maps extensions onto media types. In addition, `<mod_mime>` may define the [handler](../handler) and [filters](../filter) that originate and process content. The directives `[AddHandler](#addhandler)`, `[AddOutputFilter](#addoutputfilter)`, and `[AddInputFilter](#addinputfilter)` control the modules or scripts that serve the document. The `[MultiviewsMatch](#multiviewsmatch)` directive allows `<mod_negotiation>` to consider these file extensions to be included when testing Multiviews matches. While `<mod_mime>` associates metadata with filename extensions, the `<core>` server provides directives that are used to associate all the files in a given container (*e.g.*, `[<Location>](core#location)`, `[<Directory>](core#directory)`, or `[<Files>](core#files)`) with particular metadata. These directives include `[ForceType](core#forcetype)`, `[SetHandler](core#sethandler)`, `[SetInputFilter](core#setinputfilter)`, and `[SetOutputFilter](core#setoutputfilter)`. The core directives override any filename extension mappings defined in `<mod_mime>`. Note that changing the metadata for a file does not change the value of the `Last-Modified` header. Thus, previously cached copies may still be used by a client or proxy, with the previous headers. If you change the metadata (language, content type, character set or encoding) you may need to 'touch' affected files (updating their last modified date) to ensure that all visitors are receive the corrected content headers. Files with Multiple Extensions ------------------------------ Files can have more than one extension; the order of the extensions is *normally* irrelevant. For example, if the file `welcome.html.fr` maps onto content type `text/html` and language French then the file `welcome.fr.html` will map onto exactly the same information. If more than one extension is given that maps onto the same type of metadata, then the one to the right will be used, except for languages and content encodings. For example, if `.gif` maps to the [media-type](https://httpd.apache.org/docs/2.4/en/glossary.html#media-type "see glossary") `image/gif` and `.html` maps to the media-type `text/html`, then the file `welcome.gif.html` will be associated with the media-type `text/html`. [Languages](#charset-lang) and [content encodings](#contentencoding) are treated accumulative, because one can assign more than one language or encoding to a particular resource. For example, the file `welcome.html.en.de` will be delivered with `Content-Language: en, de` and `Content-Type: text/html`. Care should be taken when a file with multiple extensions gets associated with both a [media-type](https://httpd.apache.org/docs/2.4/en/glossary.html#media-type "see glossary") and a handler. This will usually result in the request being handled by the module associated with the handler. For example, if the `.imap` extension is mapped to the handler `imap-file` (from `<mod_imagemap>`) and the `.html` extension is mapped to the media-type `text/html`, then the file `world.imap.html` will be associated with both the `imap-file` handler and `text/html` media-type. When it is processed, the `imap-file` handler will be used, and so it will be treated as a `<mod_imagemap>` imagemap file. If you would prefer only the last dot-separated part of the filename to be mapped to a particular piece of meta-data, then do not use the `Add*` directives. For example, if you wish to have the file `foo.html.cgi` processed as a CGI script, but not the file `bar.cgi.html`, then instead of using `AddHandler cgi-script .cgi`, use ### Configure handler based on final extension only ``` <FilesMatch "[^.]+\.cgi$"> SetHandler cgi-script </FilesMatch> ``` Content encoding ---------------- A file of a particular [media-type](https://httpd.apache.org/docs/2.4/en/glossary.html#media-type "see glossary") can additionally be encoded a particular way to simplify transmission over the Internet. While this usually will refer to compression, such as `gzip`, it can also refer to encryption, such a `pgp` or to an encoding such as UUencoding, which is designed for transmitting a binary file in an ASCII (text) format. The [HTTP/1.1 RFC](http://www.ietf.org/rfc/rfc2616.txt), section 14.11 puts it this way: > The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field. Content-Encoding is primarily used to allow a document to be compressed without losing the identity of its underlying media type. > > By using more than one file extension (see [section above about multiple file extensions](#multipleext)), you can indicate that a file is of a particular *type*, and also has a particular *encoding*. For example, you may have a file which is a Microsoft Word document, which is pkzipped to reduce its size. If the `.doc` extension is associated with the Microsoft Word file type, and the `.zip` extension is associated with the pkzip file encoding, then the file `Resume.doc.zip` would be known to be a pkzip'ed Word document. Apache sends a `Content-encoding` header with the resource, in order to tell the client browser about the encoding method. ``` Content-encoding: pkzip ``` Character sets and languages ---------------------------- In addition to file type and the file encoding, another important piece of information is what language a particular document is in, and in what character set the file should be displayed. For example, the document might be written in the Vietnamese alphabet, or in Cyrillic, and should be displayed as such. This information, also, is transmitted in HTTP headers. The character set, language, encoding and mime type are all used in the process of content negotiation (See `<mod_negotiation>`) to determine which document to give to the client, when there are alternative documents in more than one character set, language, encoding or mime type. All filename extensions associations created with `[AddCharset](#addcharset)`, `[AddEncoding](#addencoding)`, `[AddLanguage](#addlanguage)` and `[AddType](#addtype)` directives (and extensions listed in the `[MimeMagicFile](mod_mime_magic#mimemagicfile)`) participate in this select process. Filename extensions that are only associated using the `[AddHandler](#addhandler)`, `[AddInputFilter](#addinputfilter)` or `[AddOutputFilter](#addoutputfilter)` directives may be included or excluded from matching by using the `[MultiviewsMatch](#multiviewsmatch)` directive. ### Charset To convey this further information, Apache optionally sends a `Content-Language` header, to specify the language that the document is in, and can append additional information onto the `Content-Type` header to indicate the particular character set that should be used to correctly render the information. ``` Content-Language: en, fr Content-Type: text/plain; charset=ISO-8859-1 ``` The language specification is the two-letter abbreviation for the language. The `charset` is the name of the particular character set which should be used. AddCharset Directive -------------------- | | | | --- | --- | | Description: | Maps the given filename extensions to the specified content charset | | Syntax: | ``` AddCharset charset extension [extension] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `AddCharset` directive maps the given filename extensions to the specified content charset (the Internet registered name for a given character encoding). charset is the [media type's charset parameter](http://www.iana.org/assignments/character-sets) for resources with filenames containing extension. This mapping is added to any already in force, overriding any mappings that already exist for the same extension. ### Example ``` AddLanguage ja .ja AddCharset EUC-JP .euc AddCharset ISO-2022-JP .jis AddCharset SHIFT_JIS .sjis ``` Then the document `xxxx.ja.jis` will be treated as being a Japanese document whose charset is `ISO-2022-JP` (as will the document `xxxx.jis.ja`). The `AddCharset` directive is useful for both to inform the client about the character encoding of the document so that the document can be interpreted and displayed appropriately, and for [content negotiation](../content-negotiation), where the server returns one from several documents based on the client's charset preference. The extension argument is case-insensitive and can be specified with or without a leading dot. Filenames may have [multiple extensions](#multipleext) and the extension argument will be compared against each of them. ### See also * `<mod_negotiation>` * `[AddDefaultCharset](core#adddefaultcharset)` AddEncoding Directive --------------------- | | | | --- | --- | | Description: | Maps the given filename extensions to the specified encoding type | | Syntax: | ``` AddEncoding encoding extension [extension] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `AddEncoding` directive maps the given filename extensions to the specified HTTP content-encoding. encoding is the HTTP content coding to append to the value of the Content-Encoding header field for documents named with the extension. This mapping is added to any already in force, overriding any mappings that already exist for the same extension. ### Example ``` AddEncoding x-gzip .gz AddEncoding x-compress .Z ``` This will cause filenames containing the `.gz` extension to be marked as encoded using the `x-gzip` encoding, and filenames containing the `.Z` extension to be marked as encoded with `x-compress`. Old clients expect `x-gzip` and `x-compress`, however the standard dictates that they're equivalent to `gzip` and `compress` respectively. Apache does content encoding comparisons by ignoring any leading `x-`. When responding with an encoding Apache will use whatever form (*i.e.*, `x-foo` or `foo`) the client requested. If the client didn't specifically request a particular form Apache will use the form given by the `AddEncoding` directive. To make this long story short, you should always use `x-gzip` and `x-compress` for these two specific encodings. More recent encodings, such as `deflate`, should be specified without the `x-`. The extension argument is case-insensitive and can be specified with or without a leading dot. Filenames may have [multiple extensions](#multipleext) and the extension argument will be compared against each of them. AddHandler Directive -------------------- | | | | --- | --- | | Description: | Maps the filename extensions to the specified handler | | Syntax: | ``` AddHandler handler-name extension [extension] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | Files having the name extension will be served by the specified [handler-name](../handler). This mapping is added to any already in force, overriding any mappings that already exist for the same extension. For example, to activate CGI scripts with the file extension `.cgi`, you might use: ``` AddHandler cgi-script .cgi ``` Once that has been put into your httpd.conf file, any file containing the `.cgi` extension will be treated as a CGI program. The extension argument is case-insensitive and can be specified with or without a leading dot. Filenames may have [multiple extensions](#multipleext) and the extension argument will be compared against each of them. ### See also * `[SetHandler](core#sethandler)` AddInputFilter Directive ------------------------ | | | | --- | --- | | Description: | Maps filename extensions to the filters that will process client requests | | Syntax: | ``` AddInputFilter filter[;filter...] extension [extension] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | `AddInputFilter` maps the filename extension extension to the [filters](../filter) which will process client requests and POST input when they are received by the server. This is in addition to any filters defined elsewhere, including the `[SetInputFilter](core#setinputfilter)` directive. This mapping is merged over any already in force, overriding any mappings that already exist for the same extension. If more than one filter is specified, they must be separated by semicolons in the order in which they should process the content. The filter is case-insensitive. The extension argument is case-insensitive and can be specified with or without a leading dot. Filenames may have [multiple extensions](#multipleext) and the extension argument will be compared against each of them. ### See also * `[RemoveInputFilter](#removeinputfilter)` * `[SetInputFilter](core#setinputfilter)` AddLanguage Directive --------------------- | | | | --- | --- | | Description: | Maps the given filename extension to the specified content language | | Syntax: | ``` AddLanguage language-tag extension [extension] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `AddLanguage` directive maps the given filename extension to the specified content language. Files with the filename extension are assigned an HTTP Content-Language value of language-tag corresponding to the language identifiers defined by RFC 3066. This directive overrides any mappings that already exist for the same extension. ### Example ``` AddEncoding x-compress .Z AddLanguage en .en AddLanguage fr .fr ``` Then the document `xxxx.en.Z` will be treated as being a compressed English document (as will the document `xxxx.Z.en`). Although the content language is reported to the client, the browser is unlikely to use this information. The `AddLanguage` directive is more useful for [content negotiation](../content-negotiation), where the server returns one from several documents based on the client's language preference. If multiple language assignments are made for the same extension, the last one encountered is the one that is used. That is, for the case of: ``` AddLanguage en .en AddLanguage en-gb .en AddLanguage en-us .en ``` documents with the extension `.en` would be treated as being `en-us`. The extension argument is case-insensitive and can be specified with or without a leading dot. Filenames may have [multiple extensions](#multipleext) and the extension argument will be compared against each of them. ### See also * `<mod_negotiation>` AddOutputFilter Directive ------------------------- | | | | --- | --- | | Description: | Maps filename extensions to the filters that will process responses from the server | | Syntax: | ``` AddOutputFilter filter[;filter...] extension [extension] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `AddOutputFilter` directive maps the filename extension extension to the [filters](../filter) which will process responses from the server before they are sent to the client. This is in addition to any filters defined elsewhere, including `[SetOutputFilter](core#setoutputfilter)` and `[AddOutputFilterByType](mod_filter#addoutputfilterbytype)` directive. This mapping is merged over any already in force, overriding any mappings that already exist for the same extension. For example, the following configuration will process all `.shtml` files for server-side includes and will then compress the output using `<mod_deflate>`. ``` AddOutputFilter INCLUDES;DEFLATE shtml ``` If more than one filter is specified, they must be separated by semicolons in the order in which they should process the content. The filter argument is case-insensitive. The extension argument is case-insensitive and can be specified with or without a leading dot. Filenames may have [multiple extensions](#multipleext) and the extension argument will be compared against each of them. Note that when defining a set of filters using the `[AddOutputFilter](#addoutputfilter)` directive, any definition made will replace any previous definition made by the `[AddOutputFilter](#addoutputfilter)` directive. ``` # Effective filter "DEFLATE" AddOutputFilter DEFLATE shtml <Location "/foo"> # Effective filter "INCLUDES", replacing "DEFLATE" AddOutputFilter INCLUDES shtml </Location> <Location "/bar"> # Effective filter "INCLUDES;DEFLATE", replacing "DEFLATE" AddOutputFilter INCLUDES;DEFLATE shtml </Location> <Location "/bar/baz"> # Effective filter "BUFFER", replacing "INCLUDES;DEFLATE" AddOutputFilter BUFFER shtml </Location> <Location "/bar/baz/buz"> # No effective filter, replacing "BUFFER" RemoveOutputFilter shtml </Location> ``` ### See also * `[RemoveOutputFilter](#removeoutputfilter)` * `[SetOutputFilter](core#setoutputfilter)` AddType Directive ----------------- | | | | --- | --- | | Description: | Maps the given filename extensions onto the specified content type | | Syntax: | ``` AddType media-type extension [extension] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `AddType` directive maps the given filename extensions onto the specified content type. media-type is the [media type](https://httpd.apache.org/docs/2.4/en/glossary.html#media-type "see glossary") to use for filenames containing extension. This mapping is added to any already in force, overriding any mappings that already exist for the same extension. It is recommended that new media types be added using the `AddType` directive rather than changing the `[TypesConfig](#typesconfig)` file. ### Example ``` AddType image/gif .gif ``` Or, to specify multiple file extensions in one directive: ### Example ``` AddType image/jpeg jpeg jpg jpe ``` The extension argument is case-insensitive and can be specified with or without a leading dot. Filenames may have [multiple extensions](#multipleext) and the extension argument will be compared against each of them. A similar effect to `<mod_negotiation>`'s `[LanguagePriority](mod_negotiation#languagepriority)` can be achieved by qualifying a media-type with `qs`: ### Example ``` AddType application/rss+xml;qs=0.8 .xml ``` This is useful in situations, *e.g.* when a client requesting `Accept: */*` can not actually processes the content returned by the server. This directive primarily configures the content types generated for static files served out of the filesystem. For resources other than static files, where the generator of the response typically specifies a Content-Type, this directive has no effect. **Note** If no handler is explicitly set for a request, the specified content type will also be used as the handler name. When explicit directives such as `[SetHandler](core#sethandler)` or `[AddHandler](#addhandler)` do not apply to the current request, the internal handler name normally set by those directives is instead set to the content type specified by this directive. This is a historical behavior that may be used by some third-party modules (such as mod\_php) for taking responsibility for the matching request. Configurations that rely on such "synthetic" types should be avoided. Additionally, configurations that restrict access to `[SetHandler](core#sethandler)` or `[AddHandler](#addhandler)` should restrict access to this directive as well. ### See also * `[ForceType](core#forcetype)` * `<mod_negotiation>` DefaultLanguage Directive ------------------------- | | | | --- | --- | | Description: | Defines a default language-tag to be sent in the Content-Language header field for all resources in the current context that have not been assigned a language-tag by some other means. | | Syntax: | ``` DefaultLanguage language-tag ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `DefaultLanguage` directive tells Apache that all resources in the directive's scope (*e.g.*, all resources covered by the current `[<Directory>](core#directory)` container) that don't have an explicit language extension (such as `.fr` or `.de` as configured by `[AddLanguage](#addlanguage)`) should be assigned a Content-Language of language-tag. This allows entire directory trees to be marked as containing Dutch content, for instance, without having to rename each file. Note that unlike using extensions to specify languages, `DefaultLanguage` can only specify a single language. If no `DefaultLanguage` directive is in force and a file does not have any language extensions as configured by `[AddLanguage](#addlanguage)`, then no Content-Language header field will be generated. ### Example ``` DefaultLanguage en ``` ### See also * `<mod_negotiation>` ModMimeUsePathInfo Directive ---------------------------- | | | | --- | --- | | Description: | Tells `<mod_mime>` to treat `path_info` components as part of the filename | | Syntax: | ``` ModMimeUsePathInfo On|Off ``` | | Default: | ``` ModMimeUsePathInfo Off ``` | | Context: | directory | | Status: | Base | | Module: | mod\_mime | The `ModMimeUsePathInfo` directive is used to combine the filename with the `path_info` URL component to apply `<mod_mime>`'s directives to the request. The default value is `Off` - therefore, the `path_info` component is ignored. This directive is recommended when you have a virtual filesystem. ### Example ``` ModMimeUsePathInfo On ``` If you have a request for `/index.php/foo.shtml` `<mod_mime>` will now treat the incoming request as `/index.php/foo.shtml` and directives like `AddOutputFilter INCLUDES .shtml` will add the `INCLUDES` filter to the request. If `ModMimeUsePathInfo` is not set, the `INCLUDES` filter will not be added. This will work analogously for virtual paths, such as those defined by `<Location>` ### See also * `[AcceptPathInfo](core#acceptpathinfo)` MultiviewsMatch Directive ------------------------- | | | | --- | --- | | Description: | The types of files that will be included when searching for a matching file with MultiViews | | Syntax: | ``` MultiviewsMatch Any|NegotiatedOnly|Filters|Handlers [Handlers|Filters] ``` | | Default: | ``` MultiviewsMatch NegotiatedOnly ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | `MultiviewsMatch` permits three different behaviors for <mod_negotiation>'s Multiviews feature. Multiviews allows a request for a file, *e.g.* `index.html`, to match any negotiated extensions following the base request, *e.g.* `index.html.en`, `index.html.fr`, or `index.html.gz`. The `NegotiatedOnly` option provides that every extension following the base name must correlate to a recognized `<mod_mime>` extension for content negotiation, *e.g.* Charset, Content-Type, Language, or Encoding. This is the strictest implementation with the fewest unexpected side effects, and is the default behavior. To include extensions associated with Handlers and/or Filters, set the `MultiviewsMatch` directive to either `Handlers`, `Filters`, or both option keywords. If all other factors are equal, the smallest file will be served, *e.g.* in deciding between `index.html.cgi` of 500 bytes and `index.html.pl` of 1000 bytes, the `.cgi` file would win in this example. Users of `.asis` files might prefer to use the Handler option, if `.asis` files are associated with the `asis-handler`. You may finally allow `Any` extensions to match, even if `<mod_mime>` doesn't recognize the extension. This can cause unpredictable results, such as serving .old or .bak files the webmaster never expected to be served. For example, the following configuration will allow handlers and filters to participate in Multviews, but will exclude unknown files: ``` MultiviewsMatch Handlers Filters ``` `MultiviewsMatch` is not allowed in a `[<Location>](core#location)` or `[<LocationMatch>](core#locationmatch)` section. ### See also * `[Options](core#options)` * `<mod_negotiation>` RemoveCharset Directive ----------------------- | | | | --- | --- | | Description: | Removes any character set associations for a set of file extensions | | Syntax: | ``` RemoveCharset extension [extension] ... ``` | | Context: | virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `RemoveCharset` directive removes any character set associations for files with the given extensions. This allows `.htaccess` files in subdirectories to undo any associations inherited from parent directories or the server config files. The extension argument is case-insensitive and can be specified with or without a leading dot. ### Example ``` RemoveCharset .html .shtml ``` RemoveEncoding Directive ------------------------ | | | | --- | --- | | Description: | Removes any content encoding associations for a set of file extensions | | Syntax: | ``` RemoveEncoding extension [extension] ... ``` | | Context: | virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `RemoveEncoding` directive removes any encoding associations for files with the given extensions. This allows `.htaccess` files in subdirectories to undo any associations inherited from parent directories or the server config files. An example of its use might be: ### /foo/.htaccess: ``` AddEncoding x-gzip .gz AddType text/plain .asc <Files "*.gz.asc"> RemoveEncoding .gz </Files> ``` This will cause `foo.gz` to be marked as being encoded with the gzip method, but `foo.gz.asc` as an unencoded plaintext file. **Note** `RemoveEncoding` directives are processed *after* any `[AddEncoding](#addencoding)` directives, so it is possible they may undo the effects of the latter if both occur within the same directory configuration. The extension argument is case-insensitive and can be specified with or without a leading dot. RemoveHandler Directive ----------------------- | | | | --- | --- | | Description: | Removes any handler associations for a set of file extensions | | Syntax: | ``` RemoveHandler extension [extension] ... ``` | | Context: | virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `RemoveHandler` directive removes any handler associations for files with the given extensions. This allows `.htaccess` files in subdirectories to undo any associations inherited from parent directories or the server config files. An example of its use might be: ### /foo/.htaccess: ``` AddHandler server-parsed .html ``` ### /foo/bar/.htaccess: ``` RemoveHandler .html ``` This has the effect of returning `.html` files in the `/foo/bar` directory to being treated as normal files, rather than as candidates for parsing (see the `<mod_include>` module). The extension argument is case-insensitive and can be specified with or without a leading dot. RemoveInputFilter Directive --------------------------- | | | | --- | --- | | Description: | Removes any input filter associations for a set of file extensions | | Syntax: | ``` RemoveInputFilter extension [extension] ... ``` | | Context: | virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `RemoveInputFilter` directive removes any input [filter](../filter) associations for files with the given extensions. This allows `.htaccess` files in subdirectories to undo any associations inherited from parent directories or the server config files. The extension argument is case-insensitive and can be specified with or without a leading dot. ### See also * `[AddInputFilter](#addinputfilter)` * `[SetInputFilter](core#setinputfilter)` RemoveLanguage Directive ------------------------ | | | | --- | --- | | Description: | Removes any language associations for a set of file extensions | | Syntax: | ``` RemoveLanguage extension [extension] ... ``` | | Context: | virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `RemoveLanguage` directive removes any language associations for files with the given extensions. This allows `.htaccess` files in subdirectories to undo any associations inherited from parent directories or the server config files. The extension argument is case-insensitive and can be specified with or without a leading dot. RemoveOutputFilter Directive ---------------------------- | | | | --- | --- | | Description: | Removes any output filter associations for a set of file extensions | | Syntax: | ``` RemoveOutputFilter extension [extension] ... ``` | | Context: | virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `RemoveOutputFilter` directive removes any output [filter](../filter) associations for files with the given extensions. This allows `.htaccess` files in subdirectories to undo any associations inherited from parent directories or the server config files. The extension argument is case-insensitive and can be specified with or without a leading dot. ### Example ``` RemoveOutputFilter shtml ``` ### See also * `[AddOutputFilter](#addoutputfilter)` RemoveType Directive -------------------- | | | | --- | --- | | Description: | Removes any content type associations for a set of file extensions | | Syntax: | ``` RemoveType extension [extension] ... ``` | | Context: | virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_mime | The `RemoveType` directive removes any [media type](https://httpd.apache.org/docs/2.4/en/glossary.html#media-type "see glossary") associations for files with the given extensions. This allows `.htaccess` files in subdirectories to undo any associations inherited from parent directories or the server config files. An example of its use might be: ### /foo/.htaccess: ``` RemoveType .cgi ``` This will remove any special handling of `.cgi` files in the `/foo/` directory and any beneath it, causing responses containing those files to omit the HTTP Content-Type header field. **Note** `RemoveType` directives are processed *after* any `[AddType](#addtype)` directives, so it is possible they may undo the effects of the latter if both occur within the same directory configuration. The extension argument is case-insensitive and can be specified with or without a leading dot. TypesConfig Directive --------------------- | | | | --- | --- | | Description: | The location of the `mime.types` file | | Syntax: | ``` TypesConfig file-path ``` | | Default: | ``` TypesConfig conf/mime.types ``` | | Context: | server config | | Status: | Base | | Module: | mod\_mime | The `TypesConfig` directive sets the location of the [media types](https://httpd.apache.org/docs/2.4/en/glossary.html#media-type "see glossary") configuration file. File-path is relative to the `[ServerRoot](core#serverroot)`. This file sets the default list of mappings from filename extensions to content types. Most administrators use the `mime.types` file provided by their OS, which associates common filename extensions with the official list of IANA registered media types maintained at <http://www.iana.org/assignments/media-types/index.html> as well as a large number of unofficial types. This simplifies the `httpd.conf` file by providing the majority of media-type definitions, and may be overridden by `[AddType](#addtype)` directives as needed. You should not edit the `mime.types` file, because it may be replaced when you upgrade your server. The file contains lines in the format of the arguments to an `[AddType](#addtype)` directive: ``` media-type [extension] ... ``` The case of the extension does not matter. Blank lines, and lines beginning with a hash character (`#`) are ignored. Empty lines are there for completeness (of the mime.types file). Apache httpd can still determine these types with `<mod_mime_magic>`. Please do **not** send requests to the Apache HTTP Server Project to add any new entries in the distributed `mime.types` file unless (1) they are already registered with IANA, and (2) they use widely accepted, non-conflicting filename extensions across platforms. `category/x-subtype` requests will be automatically rejected, as will any new two-letter extensions as they will likely conflict later with the already crowded language and character set namespace. ### See also * `<mod_mime_magic>`
programming_docs
apache_http_server Apache Module mod_request Apache Module mod\_request ========================== | | | | --- | --- | | Description: | Filters to handle and make available HTTP request bodies | | Status: | Base | | Module Identifier: | request\_module | | Source File: | mod\_request.c | | Compatibility: | Available in Apache 2.3 and later | KeptBodySize Directive ---------------------- | | | | --- | --- | | Description: | Keep the request body instead of discarding it up to the specified maximum size, for potential use by filters such as mod\_include. | | Syntax: | ``` KeptBodySize maximum size in bytes ``` | | Default: | ``` KeptBodySize 0 ``` | | Context: | directory | | Status: | Base | | Module: | mod\_request | Under normal circumstances, request handlers such as the default handler for static files will discard the request body when it is not needed by the request handler. As a result, filters such as mod\_include are limited to making `GET` requests only when including other URLs as subrequests, even if the original request was a `POST` request, as the discarded request body is no longer available once filter processing is taking place. When this directive has a value greater than zero, request handlers that would otherwise discard request bodies will instead set the request body aside for use by filters up to the maximum size specified. In the case of the mod\_include filter, an attempt to `POST` a request to the static shtml file will cause any subrequests to be `POST` requests, instead of `GET` requests as before. This feature makes it possible to break up complex web pages and web applications into small individual components, and combine the components and the surrounding web page structure together using `<mod_include>`. The components can take the form of CGI programs, scripted languages, or URLs reverse proxied into the URL space from another server using `<mod_proxy>`. **Note:** Each request set aside has to be set aside in temporary RAM until the request is complete. As a result, care should be taken to ensure sufficient RAM is available on the server to support the intended load. Use of this directive should be limited to where needed on targeted parts of your URL space, and with the lowest possible value that is still big enough to hold a request body. If the request size sent by the client exceeds the maximum size allocated by this directive, the server will return `413 Request Entity Too Large`. ### See also * <mod_include> documentation * <mod_auth_form> documentation apache_http_server Apache MPM os2 Apache MPM os2 ============== | | | | --- | --- | | Description: | Hybrid multi-process, multi-threaded MPM for OS/2 | | Status: | MPM | | Module Identifier: | mpm\_mpmt\_os2\_module | | Source File: | mpmt\_os2.c | ### Summary The Server consists of a main, parent process and a small, static number of child processes. The parent process's job is to manage the child processes. This involves spawning children as required to ensure there are always `[StartServers](mpm_common#startservers)` processes accepting connections. Each child process consists of a pool of worker threads and a main thread that accepts connections and passes them to the workers via a work queue. The worker thread pool is dynamic, managed by a maintenance thread so that the number of idle threads is kept between `[MinSpareThreads](mpm_common#minsparethreads)` and `[MaxSpareThreads](mpm_common#maxsparethreads)`. apache_http_server Apache Module mod_socache_shmcb Apache Module mod\_socache\_shmcb ================================= | | | | --- | --- | | Description: | shmcb based shared object cache provider. | | Status: | Extension | | Module Identifier: | socache\_shmcb\_module | | Source File: | mod\_socache\_shmcb.c | ### Summary `mod_socache_shmcb` is a shared object cache provider which provides for creation and access to a cache backed by a high-performance cyclic buffer inside a shared memory segment. `shmcb:/path/to/datafile(512000)` Details of other shared object cache providers can be found [here](../socache). apache_http_server Apache Module mod_expires Apache Module mod\_expires ========================== | | | | --- | --- | | Description: | Generation of `Expires` and `Cache-Control` HTTP headers according to user-specified criteria | | Status: | Extension | | Module Identifier: | expires\_module | | Source File: | mod\_expires.c | ### Summary This module controls the setting of the `Expires` HTTP header and the `max-age` directive of the `Cache-Control` HTTP header in server responses. The expiration date can set to be relative to either the time the source file was last modified, or to the time of the client access. These HTTP headers are an instruction to the client about the document's validity and persistence. If cached, the document may be fetched from the cache rather than from the source until this time has passed. After that, the cache copy is considered "expired" and invalid, and a new copy must be obtained from the source. To modify `Cache-Control` directives other than `max-age` (see [RFC 2616 section 14.9](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9)), you can use the `[Header](mod_headers#header)` directive. When the `Expires` header is already part of the response generated by the server, for example when generated by a CGI script or proxied from an origin server, this module does not change or add an `Expires` or `Cache-Control` header. Alternate Interval Syntax ------------------------- The `[ExpiresDefault](#expiresdefault)` and `[ExpiresByType](#expiresbytype)` directives can also be defined in a more readable syntax of the form: ``` ExpiresDefault "base [plus num type] [num type] ..." ExpiresByType type/encoding "base [plus num type] [num type] ..." ``` where base is one of: * `access` * `now` (equivalent to '`access`') * `modification` The `plus` keyword is optional. num should be an integer value [acceptable to `atoi()`], and type is one of: * `years` * `months` * `weeks` * `days` * `hours` * `minutes` * `seconds` For example, any of the following directives can be used to make documents expire 1 month after being accessed, by default: ``` ExpiresDefault "access plus 1 month" ExpiresDefault "access plus 4 weeks" ExpiresDefault "access plus 30 days" ``` The expiry time can be fine-tuned by adding several 'num type' clauses: ``` ExpiresByType text/html "access plus 1 month 15 days 2 hours" ExpiresByType image/gif "modification plus 5 hours 3 minutes" ``` Note that if you use a modification date based setting, the Expires header will **not** be added to content that does not come from a file on disk. This is due to the fact that there is no modification time for such content. ExpiresActive Directive ----------------------- | | | | --- | --- | | Description: | Enables generation of `Expires` headers | | Syntax: | ``` ExpiresActive On|Off ``` | | Default: | ``` ExpiresActive Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Extension | | Module: | mod\_expires | This directive enables or disables the generation of the `Expires` and `Cache-Control` headers for the document realm in question. (That is, if found in an `.htaccess` file, for instance, it applies only to documents generated from that directory.) If set to `Off`, the headers will not be generated for any document in the realm (unless overridden at a lower level, such as an `.htaccess` file overriding a server config file). If set to `On`, the headers will be added to served documents according to the criteria defined by the `[ExpiresByType](#expiresbytype)` and `[ExpiresDefault](#expiresdefault)` directives (*q.v.*). Note that this directive does not guarantee that an `Expires` or `Cache-Control` header will be generated. If the criteria aren't met, no header will be sent, and the effect will be as though this directive wasn't even specified. ExpiresByType Directive ----------------------- | | | | --- | --- | | Description: | Value of the `Expires` header configured by MIME type | | Syntax: | ``` ExpiresByType MIME-type <code>seconds ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Extension | | Module: | mod\_expires | This directive defines the value of the `Expires` header and the `max-age` directive of the `Cache-Control` header generated for documents of the specified type (*e.g.*, `text/html`). The second argument sets the number of seconds that will be added to a base time to construct the expiration date. The `Cache-Control: max-age` is calculated by subtracting the request time from the expiration date and expressing the result in seconds. The base time is either the last modification time of the file, or the time of the client's access to the document. Which should be used is specified by the `<code>` field; `M` means that the file's last modification time should be used as the base time, and `A` means the client's access time should be used. The difference in effect is subtle. If `M` is used, all current copies of the document in all caches will expire at the same time, which can be good for something like a weekly notice that's always found at the same URL. If `A` is used, the date of expiration is different for each client; this can be good for image files that don't change very often, particularly for a set of related documents that all refer to the same images (*i.e.*, the images will be accessed repeatedly within a relatively short timespan). ### Example: ``` # enable expirations ExpiresActive On # expire GIF images after a month in the client's cache ExpiresByType image/gif A2592000 # HTML documents are good for a week from the # time they were changed ExpiresByType text/html M604800 ``` Note that this directive only has effect if `ExpiresActive On` has been specified. It overrides, for the specified MIME type *only*, any expiration date set by the `[ExpiresDefault](#expiresdefault)` directive. You can also specify the expiration time calculation using an [alternate syntax](#AltSyn), described earlier in this document. ExpiresDefault Directive ------------------------ | | | | --- | --- | | Description: | Default algorithm for calculating expiration time | | Syntax: | ``` ExpiresDefault <code>seconds ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Extension | | Module: | mod\_expires | This directive sets the default algorithm for calculating the expiration time for all documents in the affected realm. It can be overridden on a type-by-type basis by the `[ExpiresByType](#expiresbytype)` directive. See the description of that directive for details about the syntax of the argument, and the [alternate syntax](#AltSyn) description as well. apache_http_server Apache Module mod_authz_dbm Apache Module mod\_authz\_dbm ============================= | | | | --- | --- | | Description: | Group authorization using DBM files | | Status: | Extension | | Module Identifier: | authz\_dbm\_module | | Source File: | mod\_authz\_dbm.c | | Compatibility: | Available in Apache 2.1 and later | ### Summary This module provides authorization capabilities so that authenticated users can be allowed or denied access to portions of the web site by group membership. Similar functionality is provided by `<mod_authz_groupfile>`. The Require Directives ---------------------- Apache's `[Require](mod_authz_core#require)` directives are used during the authorization phase to ensure that a user is allowed to access a resource. mod\_authz\_dbm extends the authorization types with `dbm-group`. Since v2.4.8, [expressions](../expr) are supported within the DBM require directives. ### Require dbm-group This directive specifies group membership that is required for the user to gain access. ``` Require dbm-group admin ``` ### Require dbm-file-group When this directive is specified, the user must be a member of the group assigned to the file being accessed. ``` Require dbm-file-group ``` Example usage ------------- *Note that using mod\_authz\_dbm requires you to require `dbm-group` instead of `group`:* ``` <Directory "/foo/bar"> AuthType Basic AuthName "Secure Area" AuthBasicProvider dbm AuthDBMUserFile "site/data/users" AuthDBMGroupFile "site/data/users" Require dbm-group admin </Directory> ``` AuthDBMGroupFile Directive -------------------------- | | | | --- | --- | | Description: | Sets the name of the database file containing the list of user groups for authorization | | Syntax: | ``` AuthDBMGroupFile file-path ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authz\_dbm | The `AuthDBMGroupFile` directive sets the name of a DBM file containing the list of user groups for user authorization. File-path is the absolute path to the group file. The group file is keyed on the username. The value for a user is a comma-separated list of the groups to which the users belongs. There must be no whitespace within the value, and it must never contain any colons. **Security** Make sure that the `AuthDBMGroupFile` is stored outside the document tree of the web-server. Do **not** put it in the directory that it protects. Otherwise, clients will be able to download the `AuthDBMGroupFile` unless otherwise protected. Combining Group and Password DBM files: In some cases it is easier to manage a single database which contains both the password and group details for each user. This simplifies any support programs that need to be written: they now only have to deal with writing to and locking a single DBM file. This can be accomplished by first setting the group and password files to point to the same DBM: ``` AuthDBMGroupFile "/www/userbase" AuthDBMUserFile "/www/userbase" ``` The key for the single DBM is the username. The value consists of ``` Encrypted Password : List of Groups [ : (ignored) ] ``` The password section contains the encrypted password as before. This is followed by a colon and the comma separated list of groups. Other data may optionally be left in the DBM file after another colon; it is ignored by the authorization module. This is what www.telescope.org uses for its combined password and group database. AuthzDBMType Directive ---------------------- | | | | --- | --- | | Description: | Sets the type of database file that is used to store list of user groups | | Syntax: | ``` AuthzDBMType default|SDBM|GDBM|NDBM|DB ``` | | Default: | ``` AuthzDBMType default ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authz\_dbm | Sets the type of database file that is used to store the list of user groups. The default database type is determined at compile time. The availability of other types of database files also depends on [compile-time settings](../install#dbm). It is crucial that whatever program you use to create your group files is configured to use the same type of database. apache_http_server Apache Module mod_cache_socache Apache Module mod\_cache\_socache ================================= | | | | --- | --- | | Description: | Shared object cache (socache) based storage module for the HTTP caching filter. | | Status: | Extension | | Module Identifier: | cache\_socache\_module | | Source File: | mod\_cache\_socache.c | ### Summary `<mod_cache_socache>` implements a shared object cache (socache) based storage manager for `<mod_cache>`. The headers and bodies of cached responses are combined, and stored underneath a single key in the shared object cache. A [number of implementations](../socache) of shared object caches are available to choose from. Multiple content negotiated responses can be stored concurrently, however the caching of partial content is not yet supported by this module. ``` # Turn on caching CacheSocache shmcb CacheSocacheMaxSize 102400 <Location "/foo"> CacheEnable socache </Location> # Fall back to the disk cache CacheSocache shmcb CacheSocacheMaxSize 102400 <Location "/foo"> CacheEnable socache CacheEnable disk </Location> ``` **Note:** `<mod_cache_socache>` requires the services of `<mod_cache>`, which must be loaded before `<mod_cache_socache>`. CacheSocache Directive ---------------------- | | | | --- | --- | | Description: | The shared object cache implementation to use | | Syntax: | ``` CacheSocache type[:args] ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_cache\_socache | | Compatibility: | Available in Apache 2.4.5 and later | The `CacheSocache` directive defines the name of the shared object cache implementation to use, followed by optional arguments for that implementation. A [number of implementations](../socache) of shared object caches are available to choose from. ``` CacheSocache shmcb ``` CacheSocacheMaxSize Directive ----------------------------- | | | | --- | --- | | Description: | The maximum size (in bytes) of an entry to be placed in the cache | | Syntax: | ``` CacheSocacheMaxSize bytes ``` | | Default: | ``` CacheSocacheMaxSize 102400 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache\_socache | | Compatibility: | Available in Apache 2.4.5 and later | The `CacheSocacheMaxSize` directive sets the maximum size, in bytes, for the combined headers and body of a document to be considered for storage in the cache. The larger the headers that are stored alongside the body, the smaller the body may be. The `<mod_cache_socache>` module will only attempt to cache responses that have an explicit content length, or that are small enough to be written in one pass. This is done to allow the `<mod_cache_disk>` module to have an opportunity to cache responses larger than those cacheable within `<mod_cache_socache>`. ``` CacheSocacheMaxSize 102400 ``` CacheSocacheMaxTime Directive ----------------------------- | | | | --- | --- | | Description: | The maximum time (in seconds) for a document to be placed in the cache | | Syntax: | ``` CacheSocacheMaxTime seconds ``` | | Default: | ``` CacheSocacheMaxTime 86400 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache\_socache | | Compatibility: | Available in Apache 2.4.5 and later | The `CacheSocacheMaxTime` directive sets the maximum freshness lifetime, in seconds, for a document to be stored in the cache. This value overrides the freshness lifetime defined for the document by the HTTP protocol. ``` CacheSocacheMaxTime 86400 ``` CacheSocacheMinTime Directive ----------------------------- | | | | --- | --- | | Description: | The minimum time (in seconds) for a document to be placed in the cache | | Syntax: | ``` CacheSocacheMinTime seconds ``` | | Default: | ``` CacheSocacheMinTime 600 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache\_socache | | Compatibility: | Available in Apache 2.4.5 and later | The `CacheSocacheMinTime` directive sets the amount of seconds beyond the freshness lifetime of the response that the response should be cached for in the shared object cache. If a response is only stored for its freshness lifetime, there will be no opportunity to revalidate the response to make it fresh again. ``` CacheSocacheMinTime 600 ``` CacheSocacheReadSize Directive ------------------------------ | | | | --- | --- | | Description: | The minimum size (in bytes) of the document to read and be cached before sending the data downstream | | Syntax: | ``` CacheSocacheReadSize bytes ``` | | Default: | ``` CacheSocacheReadSize 0 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache\_socache | | Compatibility: | Available in Apache 2.4.5 and later | The `CacheSocacheReadSize` directive sets the minimum amount of data, in bytes, to be read from the backend before the data is sent to the client. The default of zero causes all data read of any size to be passed downstream to the client immediately as it arrives. Setting this to a higher value causes the disk cache to buffer at least this amount before sending the result to the client. This can improve performance when caching content from a slow reverse proxy. This directive only takes effect when the data is being saved to the cache, as opposed to data being served from the cache. ``` CacheSocacheReadSize 102400 ``` CacheSocacheReadTime Directive ------------------------------ | | | | --- | --- | | Description: | The minimum time (in milliseconds) that should elapse while reading before data is sent downstream | | Syntax: | ``` CacheSocacheReadTime milliseconds ``` | | Default: | ``` CacheSocacheReadTime 0 ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_cache\_socache | | Compatibility: | Available in Apache 2.4.5 and later | The `CacheSocacheReadTime` directive sets the minimum amount of elapsed time that should pass before making an attempt to send data downstream to the client. During the time period, data will be buffered before sending the result to the client. This can improve performance when caching content from a reverse proxy. The default of zero disables this option. This directive only takes effect when the data is being saved to the cache, as opposed to data being served from the cache. It is recommended that this option be used alongside the `[CacheSocacheReadSize](#cachesocachereadsize)` directive to ensure that the server does not buffer excessively should data arrive faster than expected. ``` CacheSocacheReadTime 1000 ```
programming_docs
apache_http_server Apache Module mod_authz_host Apache Module mod\_authz\_host ============================== | | | | --- | --- | | Description: | Group authorizations based on host (name or IP address) | | Status: | Base | | Module Identifier: | authz\_host\_module | | Source File: | mod\_authz\_host.c | | Compatibility: | The `forward-dns` provider was added in 2.4.19 | ### Summary The authorization providers implemented by `<mod_authz_host>` are registered using the `[Require](mod_authz_core#require)` directive. The directive can be referenced within a `[<Directory>](core#directory)`, `[<Files>](core#files)`, or `[<Location>](core#location)` section as well as `[.htaccess](core#accessfilename)` files to control access to particular parts of the server. Access can be controlled based on the client hostname or IP address. In general, access restriction directives apply to all access methods (`GET`, `PUT`, `POST`, etc). This is the desired behavior in most cases. However, it is possible to restrict some methods, while leaving other methods unrestricted, by enclosing the directives in a `[<Limit>](core#limit)` section. The Require Directives ---------------------- Apache's `[Require](mod_authz_core#require)` directive is used during the authorization phase to ensure that a user is allowed or denied access to a resource. mod\_authz\_host extends the authorization types with `ip`, `host`, `forward-dns` and `local`. Other authorization types may also be used but may require that additional authorization modules be loaded. These authorization providers affect which hosts can access an area of the server. Access can be controlled by hostname, IP Address, or IP Address range. Since v2.4.8, [expressions](../expr) are supported within the host require directives. ### Require ip The `ip` provider allows access to the server to be controlled based on the IP address of the remote client. When `Require ip ip-address` is specified, then the request is allowed access if the IP address matches. A full IP address: ``` Require ip 10.1.2.3 Require ip 192.168.1.104 192.168.1.205 ``` An IP address of a host allowed access A partial IP address: ``` Require ip 10.1 Require ip 10 172.20 192.168.2 ``` The first 1 to 3 bytes of an IP address, for subnet restriction. A network/netmask pair: ``` Require ip 10.1.0.0/255.255.0.0 ``` A network a.b.c.d, and a netmask w.x.y.z. For more fine-grained subnet restriction. A network/nnn CIDR specification: ``` Require ip 10.1.0.0/16 ``` Similar to the previous case, except the netmask consists of nnn high-order 1 bits. Note that the last three examples above match exactly the same set of hosts. IPv6 addresses and IPv6 subnets can be specified as shown below: ``` Require ip 2001:db8::a00:20ff:fea7:ccea Require ip 2001:db8:1:1::a Require ip 2001:db8:2:1::/64 Require ip 2001:db8:3::/48 ``` Note: As the IP addresses are parsed on startup, expressions are not evaluated at request time. ### Require host The `host` provider allows access to the server to be controlled based on the host name of the remote client. When `Require host host-name` is specified, then the request is allowed access if the host name matches. A (partial) domain-name ``` Require host example.org Require host .net example.edu ``` Hosts whose names match, or end in, this string are allowed access. Only complete components are matched, so the above example will match `foo.example.org` but it will not match `fooexample.org`. This configuration will cause Apache to perform a double reverse DNS lookup on the client IP address, regardless of the setting of the `[HostnameLookups](core#hostnamelookups)` directive. It will do a reverse DNS lookup on the IP address to find the associated hostname, and then do a forward lookup on the hostname to assure that it matches the original IP address. Only if the forward and reverse DNS are consistent and the hostname matches will access be allowed. ### Require forward-dns The `forward-dns` provider allows access to the server to be controlled based on simple host names. When `Require forward-dns host-name` is specified, all IP addresses corresponding to `host-name` are allowed access. In contrast to the `host` provider, this provider does not rely on reverse DNS lookups: it simply queries the DNS for the host name and allows a client if its IP matches. As a consequence, it will only work with host names, not domain names. However, as the reverse DNS is not used, it will work with clients which use a dynamic DNS service. ``` Require forward-dns dynamic.example.org ``` A client the IP of which is resolved from the name `dynamic.example.org` will be granted access. The `forward-dns` provider was added in 2.4.19. ### Require local The `local` provider allows access to the server if any of the following conditions is true: * the client address matches 127.0.0.0/8 * the client address is ::1 * both the client and the server address of the connection are the same This allows a convenient way to match connections that originate from the local host: ``` Require local ``` ### Security Note If you are proxying content to your server, you need to be aware that the client address will be the address of your proxy server, not the address of the client, and so using the `Require` directive in this context may not do what you mean. See `<mod_remoteip>` for one possible solution to this problem. apache_http_server Apache Module mod_session_dbd Apache Module mod\_session\_dbd =============================== | | | | --- | --- | | Description: | DBD/SQL based session support | | Status: | Extension | | Module Identifier: | session\_dbd\_module | | Source File: | mod\_session\_dbd.c | | Compatibility: | Available in Apache 2.3 and later | ### Summary **Warning** The session modules make use of HTTP cookies, and as such can fall victim to Cross Site Scripting attacks, or expose potentially private information to clients. Please ensure that the relevant risks have been taken into account before enabling the session functionality on your server. This submodule of `<mod_session>` provides support for the storage of user sessions within a SQL database using the `<mod_dbd>` module. Sessions can either be **anonymous**, where the session is keyed by a unique UUID string stored on the browser in a cookie, or **per user**, where the session is keyed against the userid of the logged in user. SQL based sessions are hidden from the browser, and so offer a measure of privacy without the need for encryption. Different webservers within a server farm may choose to share a database, and so share sessions with one another. For more details on the session interface, see the documentation for the `<mod_session>` module. DBD Configuration ----------------- Before the `<mod_session_dbd>` module can be configured to maintain a session, the `<mod_dbd>` module must be configured to make the various database queries available to the server. There are four queries required to keep a session maintained, to select an existing session, to update an existing session, to insert a new session, and to delete an expired or empty session. These queries are configured as per the example below. ### Sample DBD configuration ``` DBDriver pgsql DBDParams "dbname=apachesession user=apache password=xxxxx host=localhost" DBDPrepareSQL "delete from session where key = %s" deletesession DBDPrepareSQL "update session set value = %s, expiry = %lld, key = %s where key = %s" updatesession DBDPrepareSQL "insert into session (value, expiry, key) values (%s, %lld, %s)" insertsession DBDPrepareSQL "select value from session where key = %s and (expiry = 0 or expiry > %lld)" selectsession DBDPrepareSQL "delete from session where expiry != 0 and expiry < %lld" cleansession ``` Anonymous Sessions ------------------ Anonymous sessions are keyed against a unique UUID, and stored on the browser within an HTTP cookie. This method is similar to that used by most application servers to store session information. To create a simple anonymous session and store it in a postgres database table called apachesession, and save the session ID in a cookie called session, configure the session as follows: ### SQL based anonymous session ``` Session On SessionDBDCookieName session path=/ ``` For more examples on how the session can be configured to be read from and written to by a CGI application, see the `<mod_session>` examples section. For documentation on how the session can be used to store username and password details, see the `<mod_auth_form>` module. Per User Sessions ----------------- Per user sessions are keyed against the username of a successfully authenticated user. It offers the most privacy, as no external handle to the session exists outside of the authenticated realm. Per user sessions work within a correctly configured authenticated environment, be that using basic authentication, digest authentication or SSL client certificates. Due to the limitations of who came first, the chicken or the egg, per user sessions cannot be used to store authentication credentials from a module like `<mod_auth_form>`. To create a simple per user session and store it in a postgres database table called apachesession, and with the session keyed to the userid, configure the session as follows: ### SQL based per user session ``` Session On SessionDBDPerUser On ``` Database Housekeeping --------------------- Over the course of time, the database can be expected to start accumulating expired sessions. At this point, the `<mod_session_dbd>` module is not yet able to handle session expiry automatically. **Warning** The administrator will need to set up an external process via cron to clean out expired sessions. SessionDBDCookieName Directive ------------------------------ | | | | --- | --- | | Description: | Name and attributes for the RFC2109 cookie storing the session ID | | Syntax: | ``` SessionDBDCookieName name attributes ``` | | Default: | `none` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session\_dbd | The `SessionDBDCookieName` directive specifies the name and optional attributes of an RFC2109 compliant cookie inside which the session ID will be stored. RFC2109 cookies are set using the `Set-Cookie` HTTP header. An optional list of cookie attributes can be specified, as per the example below. These attributes are inserted into the cookie as is, and are not interpreted by Apache. Ensure that your attributes are defined correctly as per the cookie specification. ### Cookie with attributes ``` Session On SessionDBDCookieName session path=/private;domain=example.com;httponly;secure;version=1; ``` SessionDBDCookieName2 Directive ------------------------------- | | | | --- | --- | | Description: | Name and attributes for the RFC2965 cookie storing the session ID | | Syntax: | ``` SessionDBDCookieName2 name attributes ``` | | Default: | `none` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session\_dbd | The `SessionDBDCookieName2` directive specifies the name and optional attributes of an RFC2965 compliant cookie inside which the session ID will be stored. RFC2965 cookies are set using the `Set-Cookie2` HTTP header. An optional list of cookie attributes can be specified, as per the example below. These attributes are inserted into the cookie as is, and are not interpreted by Apache. Ensure that your attributes are defined correctly as per the cookie specification. ### Cookie2 with attributes ``` Session On SessionDBDCookieName2 session path=/private;domain=example.com;httponly;secure;version=1; ``` SessionDBDCookieRemove Directive -------------------------------- | | | | --- | --- | | Description: | Control for whether session ID cookies should be removed from incoming HTTP headers | | Syntax: | ``` SessionDBDCookieRemove On|Off ``` | | Default: | ``` SessionDBDCookieRemove On ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session\_dbd | The `SessionDBDCookieRemove` flag controls whether the cookies containing the session ID will be removed from the headers during request processing. In a reverse proxy situation where the Apache server acts as a server frontend for a backend origin server, revealing the contents of the session ID cookie to the backend could be a potential privacy violation. When set to on, the session ID cookie will be removed from the incoming HTTP headers. SessionDBDDeleteLabel Directive ------------------------------- | | | | --- | --- | | Description: | The SQL query to use to remove sessions from the database | | Syntax: | ``` SessionDBDDeleteLabel label ``` | | Default: | ``` SessionDBDDeleteLabel deletesession ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session\_dbd | The `SessionDBDDeleteLabel` directive sets the default delete query label to be used to delete an expired or empty session. This label must have been previously defined using the `[DBDPrepareSQL](mod_dbd#dbdpreparesql)` directive. SessionDBDInsertLabel Directive ------------------------------- | | | | --- | --- | | Description: | The SQL query to use to insert sessions into the database | | Syntax: | ``` SessionDBDInsertLabel label ``` | | Default: | ``` SessionDBDInsertLabel insertsession ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session\_dbd | The `SessionDBDInsertLabel` directive sets the default insert query label to be used to load in a session. This label must have been previously defined using the `[DBDPrepareSQL](mod_dbd#dbdpreparesql)` directive. If an attempt to update the session affects no rows, this query will be called to insert the session into the database. SessionDBDPerUser Directive --------------------------- | | | | --- | --- | | Description: | Enable a per user session | | Syntax: | ``` SessionDBDPerUser On|Off ``` | | Default: | ``` SessionDBDPerUser Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session\_dbd | The `SessionDBDPerUser` flag enables a per user session keyed against the user's login name. If the user is not logged in, this directive will be ignored. SessionDBDSelectLabel Directive ------------------------------- | | | | --- | --- | | Description: | The SQL query to use to select sessions from the database | | Syntax: | ``` SessionDBDSelectLabel label ``` | | Default: | ``` SessionDBDSelectLabel selectsession ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session\_dbd | The `SessionDBDSelectLabel` directive sets the default select query label to be used to load in a session. This label must have been previously defined using the `[DBDPrepareSQL](mod_dbd#dbdpreparesql)` directive. SessionDBDUpdateLabel Directive ------------------------------- | | | | --- | --- | | Description: | The SQL query to use to update existing sessions in the database | | Syntax: | ``` SessionDBDUpdateLabel label ``` | | Default: | ``` SessionDBDUpdateLabel updatesession ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session\_dbd | The `SessionDBDUpdateLabel` directive sets the default update query label to be used to load in a session. This label must have been previously defined using the `[DBDPrepareSQL](mod_dbd#dbdpreparesql)` directive. If an attempt to update the session affects no rows, the insert query will be called to insert the session into the database. If the database supports InsertOrUpdate, override this query to perform the update in one query instead of two. apache_http_server Apache Module mod_negotiation Apache Module mod\_negotiation ============================== | | | | --- | --- | | Description: | Provides for [content negotiation](../content-negotiation) | | Status: | Base | | Module Identifier: | negotiation\_module | | Source File: | mod\_negotiation.c | ### Summary Content negotiation, or more accurately content selection, is the selection of the document that best matches the clients capabilities, from one of several available documents. There are two implementations of this. * A type map (a file with the handler `type-map`) which explicitly lists the files containing the variants. * A Multiviews search (enabled by the `Multiviews` `[Options](core#options)`), where the server does an implicit filename pattern match, and choose from amongst the results. Type maps --------- A type map has a format similar to RFC822 mail headers. It contains document descriptions separated by blank lines, with lines beginning with a hash character ('#') treated as comments. A document description consists of several header records; records may be continued on multiple lines if the continuation lines start with spaces. The leading space will be deleted and the lines concatenated. A header record consists of a keyword name, which always ends in a colon, followed by a value. Whitespace is allowed between the header name and value, and between the tokens of value. The headers allowed are: `Content-Encoding:` The encoding of the file. Apache only recognizes encodings that are defined by an `[AddEncoding](mod_mime#addencoding)` directive. This normally includes the encodings `x-compress` for compress'd files, and `x-gzip` for gzip'd files. The `x-` prefix is ignored for encoding comparisons. `Content-Language:` The language(s) of the variant, as an Internet standard language tag ([RFC 1766](http://www.ietf.org/rfc/rfc1766.txt)). An example is `en`, meaning English. If the variant contains more than one language, they are separated by a comma. `Content-Length:` The length of the file, in bytes. If this header is not present, then the actual length of the file is used. `Content-Type:` The [MIME media type](https://httpd.apache.org/docs/2.4/en/glossary.html#mime-type "see glossary") of the document, with optional parameters. Parameters are separated from the media type and from one another by a semi-colon, with a syntax of `name=value`. Common parameters include: `level` an integer specifying the version of the media type. For `text/html` this defaults to 2, otherwise 0. `qs` a floating-point number with a value in the range 0[.000] to 1[.000], indicating the relative 'quality' of this variant compared to the other available variants, independent of the client's capabilities. For example, a jpeg file is usually of higher source quality than an ascii file if it is attempting to represent a photograph. However, if the resource being represented is ascii art, then an ascii file would have a higher source quality than a jpeg file. All `qs` values are therefore specific to a given resource. ### Example ``` Content-Type: image/jpeg; qs=0.8 ``` `URI:` uri of the file containing the variant (of the given media type, encoded with the given content encoding). These are interpreted as URLs relative to the map file; they must be on the same server, and they must refer to files to which the client would be granted access if they were to be requested directly. `Body:` The actual content of the resource may be included in the type-map file using the Body header. This header must contain a string that designates a delimiter for the body content. Then all following lines in the type map file will be considered part of the resource body until the delimiter string is found. ### Example: ``` Body:----xyz---- <html> <body> <p>Content of the page.</p> </body> </html> ----xyz---- ``` Consider, for example, a resource called `document.html` which is available in English, French, and German. The files for each of these are called `document.html.en`, `document.html.fr`, and `document.html.de`, respectively. The type map file will be called `document.html.var`, and will contain the following: ``` URI: document.html Content-language: en Content-type: text/html URI: document.html.en Content-language: fr Content-type: text/html URI: document.html.fr Content-language: de Content-type: text/html URI: document.html.de ``` All four of these files should be placed in the same directory, and the `.var` file should be associated with the `type-map` handler with an `[AddHandler](mod_mime#addhandler)` directive: ``` AddHandler type-map .var ``` A request for `document.html.var` in this directory will result in choosing the variant which most closely matches the language preference specified in the user's `Accept-Language` request header. If `Multiviews` is enabled, and `[MultiviewsMatch](mod_mime#multiviewsmatch)` is set to "handlers" or "any", a request to `document.html` will discover `document.html.var` and continue negotiating with the explicit type map. Other configuration directives, such as `[Alias](mod_alias#alias)` can be used to map `document.html` to `document.html.var`. Multiviews ---------- A Multiviews search is enabled by the `Multiviews` `[Options](core#options)`. If the server receives a request for `/some/dir/foo` and `/some/dir/foo` does *not* exist, then the server reads the directory looking for all files named `foo.*`, and effectively fakes up a type map which names all those files, assigning them the same media types and content-encodings it would have if the client had asked for one of them by name. It then chooses the best match to the client's requirements, and returns that document. The `[MultiviewsMatch](mod_mime#multiviewsmatch)` directive configures whether Apache will consider files that do not have content negotiation meta-information assigned to them when choosing files. CacheNegotiatedDocs Directive ----------------------------- | | | | --- | --- | | Description: | Allows content-negotiated documents to be cached by proxy servers | | Syntax: | ``` CacheNegotiatedDocs On|Off ``` | | Default: | ``` CacheNegotiatedDocs Off ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_negotiation | If set, this directive allows content-negotiated documents to be cached by proxy servers. This could mean that clients behind those proxys could retrieve versions of the documents that are not the best match for their abilities, but it will make caching more efficient. This directive only applies to requests which come from HTTP/1.0 browsers. HTTP/1.1 provides much better control over the caching of negotiated documents, and this directive has no effect in responses to HTTP/1.1 requests. ForceLanguagePriority Directive ------------------------------- | | | | --- | --- | | Description: | Action to take if a single acceptable document is not found | | Syntax: | ``` ForceLanguagePriority None|Prefer|Fallback [Prefer|Fallback] ``` | | Default: | ``` ForceLanguagePriority Prefer ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_negotiation | The `ForceLanguagePriority` directive uses the given `[LanguagePriority](#languagepriority)` to satisfy negotiation where the server could otherwise not return a single matching document. `ForceLanguagePriority Prefer` uses `LanguagePriority` to serve a one valid result, rather than returning an HTTP result 300 (MULTIPLE CHOICES) when there are several equally valid choices. If the directives below were given, and the user's `Accept-Language` header assigned `en` and `de` each as quality `.500` (equally acceptable) then the first matching variant, `en`, will be served. ``` LanguagePriority en fr de ForceLanguagePriority Prefer ``` `ForceLanguagePriority Fallback` uses `[LanguagePriority](#languagepriority)` to serve a valid result, rather than returning an HTTP result 406 (NOT ACCEPTABLE). If the directives below were given, and the user's `Accept-Language` only permitted an `es` language response, but such a variant isn't found, then the first variant from the `[LanguagePriority](#languagepriority)` list below will be served. ``` LanguagePriority en fr de ForceLanguagePriority Fallback ``` Both options, `Prefer` and `Fallback`, may be specified, so either the first matching variant from `[LanguagePriority](#languagepriority)` will be served if more than one variant is acceptable, or first available document will be served if none of the variants matched the client's acceptable list of languages. ### See also * `[AddLanguage](mod_mime#addlanguage)` LanguagePriority Directive -------------------------- | | | | --- | --- | | Description: | The precedence of language variants for cases where the client does not express a preference | | Syntax: | ``` LanguagePriority MIME-lang [MIME-lang] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_negotiation | The `LanguagePriority` sets the precedence of language variants for the case where the client does not express a preference, when handling a Multiviews request. The list of MIME-lang are in order of decreasing preference. ``` LanguagePriority en fr de ``` For a request for `foo.html`, where `foo.html.fr` and `foo.html.de` both existed, but the browser did not express a language preference, then `foo.html.fr` would be returned. Note that this directive only has an effect if a 'best' language cannot be determined by any other means or the `[ForceLanguagePriority](#forcelanguagepriority)` directive is not `None`. In general, the client determines the language preference, not the server. ### See also * `[AddLanguage](mod_mime#addlanguage)`
programming_docs
apache_http_server Apache Module mod_authn_file Apache Module mod\_authn\_file ============================== | | | | --- | --- | | Description: | User authentication using text files | | Status: | Base | | Module Identifier: | authn\_file\_module | | Source File: | mod\_authn\_file.c | | Compatibility: | Available in Apache 2.1 and later | ### Summary This module provides authentication front-ends such as `<mod_auth_digest>` and `<mod_auth_basic>` to authenticate users by looking up users in plain text password files. Similar functionality is provided by `<mod_authn_dbm>`. When using `<mod_auth_basic>` or `<mod_auth_digest>`, this module is invoked via the `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` or `[AuthDigestProvider](mod_auth_digest#authdigestprovider)` with the `file` value. AuthUserFile Directive ---------------------- | | | | --- | --- | | Description: | Sets the name of a text file containing the list of users and passwords for authentication | | Syntax: | ``` AuthUserFile file-path ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Base | | Module: | mod\_authn\_file | The `AuthUserFile` directive sets the name of a textual file containing the list of users and passwords for user authentication. File-path is the path to the user file. If it is not absolute, it is treated as relative to the `[ServerRoot](core#serverroot)`. Each line of the user file contains a username followed by a colon, followed by the encrypted password. If the same user ID is defined multiple times, `<mod_authn_file>` will use the first occurrence to verify the password. The encrypted password format depends on which authentication frontend (e.g. `<mod_auth_basic>` or `<mod_auth_digest>`) is being used. See [Password Formats](../misc/password_encryptions) for more information. For `<mod_auth_basic>`, use the utility `[htpasswd](../programs/htpasswd)` which is installed as part of the binary distribution, or which can be found in `src/support`. See the [man page](../programs/htpasswd) for more details. In short: Create a password file `Filename` with `username` as the initial ID. It will prompt for the password: ``` htpasswd -c Filename username ``` Add or modify `username2` in the password file `Filename`: ``` htpasswd Filename username2 ``` Note that searching large text files is *very* inefficient; `[AuthDBMUserFile](mod_authn_dbm#authdbmuserfile)` should be used instead. For `<mod_auth_digest>`, use `[htdigest](../programs/htdigest)` instead. Note that you cannot mix user data for Digest Authentication and Basic Authentication within the same file. **Security** Make sure that the `AuthUserFile` is stored outside the document tree of the web-server. Do **not** put it in the directory that it protects. Otherwise, clients may be able to download the `AuthUserFile`. apache_http_server Override Class Index for .htaccess Override Class Index for .htaccess ================================== This is an index of the directives that are allowed in .htaccess files for various `[AllowOverride](core#allowoverride)` settings, organized by class. Its intended purpose is to help server administrators verify the privileges they're granting to .htaccess users. For an overview of how .htaccess works, see the [.htaccess tutorial](../howto/htaccess). To determine the set of directives that your server configuration allows .htaccess users to use: 1. Start with the set of directives in the `AllowOverrideList` for the directory in question. (By default, this is set to `None`.) 2. Find the `AllowOverride` setting for the directory in question. (By default, it is set to `None`.) There are two special cases: 1. If your `AllowOverride` setting is `All`, add every directive listed on this page to the list. 2. If your `AllowOverride` setting is `None`, you're done. Only the directives in the `AllowOverrideList` (if any) will be allowed. 3. For each override class listed in `AllowOverride`, look up the corresponding set of directives below and add them to the list. 4. Finally, add the set of directives that is always allowed in .htaccess (these are listed in the [All section](#override-all), below). Several of the override classes are quite powerful and give .htaccess users a large amount of control over the server. For a stricter approach, set `AllowOverride None` and use `[AllowOverrideList](core#allowoverridelist)` to specify the exact list of directives that .htaccess users are allowed to use. All --- The following directives are allowed in any .htaccess file, as long as overrides are enabled in the server configuration. | | | | --- | --- | | [<Else>](core#else) | <core> | | Contains directives that apply only if the condition of a previous `[<If>](core#if)` or `[<ElseIf>](core#elseif)` section is not satisfied by a request at runtime | | [<ElseIf>](core#elseif) | <core> | | Contains directives that apply only if a condition is satisfied by a request at runtime while the condition of a previous `[<If>](core#if)` or `<ElseIf>` section is not satisfied | | [<Files>](core#files) | <core> | | Contains directives that apply to matched filenames | | [<FilesMatch>](core#filesmatch) | <core> | | Contains directives that apply to regular-expression matched filenames | | [<If>](core#if) | <core> | | Contains directives that apply only if a condition is satisfied by a request at runtime | | [<IfDefine>](core#ifdefine) | <core> | | Encloses directives that will be processed only if a test is true at startup | | [<IfDirective>](core#ifdirective) | <core> | | Encloses directives that are processed conditional on the presence or absence of a specific directive | | [<IfFile>](core#iffile) | <core> | | Encloses directives that will be processed only if file exists at startup | | [<IfModule>](core#ifmodule) | <core> | | Encloses directives that are processed conditional on the presence or absence of a specific module | | [<IfSection>](core#ifsection) | <core> | | Encloses directives that are processed conditional on the presence or absence of a specific section directive | | [<IfVersion>](mod_version#ifversion) | <mod_version> | | contains version dependent configuration | | [LimitRequestBody](core#limitrequestbody) | <core> | | Restricts the total size of the HTTP request body sent from the client | | [LimitXMLRequestBody](core#limitxmlrequestbody) | <core> | | Limits the size of an XML-based request body | | [LogIOTrackTTFB](mod_logio#logiotrackttfb) | <mod_logio> | | Enable tracking of time to first byte (TTFB) | | [LuaCodeCache](mod_lua#luacodecache) | <mod_lua> | | Configure the compiled code cache. | | [LuaHookAccessChecker](mod_lua#luahookaccesschecker) | <mod_lua> | | Provide a hook for the access\_checker phase of request processing | | [LuaHookAuthChecker](mod_lua#luahookauthchecker) | <mod_lua> | | Provide a hook for the auth\_checker phase of request processing | | [LuaHookCheckUserID](mod_lua#luahookcheckuserid) | <mod_lua> | | Provide a hook for the check\_user\_id phase of request processing | | [LuaHookFixups](mod_lua#luahookfixups) | <mod_lua> | | Provide a hook for the fixups phase of a request processing | | [LuaHookInsertFilter](mod_lua#luahookinsertfilter) | <mod_lua> | | Provide a hook for the insert\_filter phase of request processing | | [LuaHookLog](mod_lua#luahooklog) | <mod_lua> | | Provide a hook for the access log phase of a request processing | | [LuaHookMapToStorage](mod_lua#luahookmaptostorage) | <mod_lua> | | Provide a hook for the map\_to\_storage phase of request processing | | [LuaHookPreTranslate](mod_lua#luahookpretranslate) | <mod_lua> | | Provide a hook for the pre\_translate phase of a request processing | | [LuaHookTranslateName](mod_lua#luahooktranslatename) | <mod_lua> | | Provide a hook for the translate name phase of request processing | | [LuaHookTypeChecker](mod_lua#luahooktypechecker) | <mod_lua> | | Provide a hook for the type\_checker phase of request processing | | [LuaInherit](mod_lua#luainherit) | <mod_lua> | | Controls how parent configuration sections are merged into children | | [LuaMapHandler](mod_lua#luamaphandler) | <mod_lua> | | Map a path to a lua handler | | [LuaPackageCPath](mod_lua#luapackagecpath) | <mod_lua> | | Add a directory to lua's package.cpath | | [LuaPackagePath](mod_lua#luapackagepath) | <mod_lua> | | Add a directory to lua's package.path | | [LuaQuickHandler](mod_lua#luaquickhandler) | <mod_lua> | | Provide a hook for the quick handler of request processing | | [LuaRoot](mod_lua#luaroot) | <mod_lua> | | Specify the base path for resolving relative paths for mod\_lua directives | | [LuaScope](mod_lua#luascope) | <mod_lua> | | One of once, request, conn, thread -- default is once | | [RLimitCPU](core#rlimitcpu) | <core> | | Limits the CPU consumption of processes launched by Apache httpd children | | [RLimitMEM](core#rlimitmem) | <core> | | Limits the memory consumption of processes launched by Apache httpd children | | [RLimitNPROC](core#rlimitnproc) | <core> | | Limits the number of processes that can be launched by processes launched by Apache httpd children | | [ServerSignature](core#serversignature) | <core> | | Configures the footer on server-generated documents | | [SSIErrorMsg](mod_include#ssierrormsg) | <mod_include> | | Error message displayed when there is an SSI error | | [SSITimeFormat](mod_include#ssitimeformat) | <mod_include> | | Configures the format in which date strings are displayed | | [SSIUndefinedEcho](mod_include#ssiundefinedecho) | <mod_include> | | String displayed when an unset variable is echoed | AuthConfig ---------- The following directives are allowed in .htaccess files when `AllowOverride AuthConfig` is in effect. They give .htaccess users control over the authentication and authorization methods that are applied to their directory subtrees, including several related utility directives for session handling and TLS settings. | | | | --- | --- | | [Anonymous](mod_authn_anon#anonymous) | <mod_authn_anon> | | Specifies userIDs that are allowed access without password verification | | [Anonymous\_LogEmail](mod_authn_anon#anonymous_logemail) | <mod_authn_anon> | | Sets whether the password entered will be logged in the error log | | [Anonymous\_MustGiveEmail](mod_authn_anon#anonymous_mustgiveemail) | <mod_authn_anon> | | Specifies whether blank passwords are allowed | | [Anonymous\_NoUserID](mod_authn_anon#anonymous_nouserid) | <mod_authn_anon> | | Sets whether the userID field may be empty | | [Anonymous\_VerifyEmail](mod_authn_anon#anonymous_verifyemail) | <mod_authn_anon> | | Sets whether to check the password field for a correctly formatted email address | | [AuthBasicAuthoritative](mod_auth_basic#authbasicauthoritative) | <mod_auth_basic> | | Sets whether authorization and authentication are passed to lower level modules | | [AuthBasicFake](mod_auth_basic#authbasicfake) | <mod_auth_basic> | | Fake basic authentication using the given expressions for username and password | | [AuthBasicProvider](mod_auth_basic#authbasicprovider) | <mod_auth_basic> | | Sets the authentication provider(s) for this location | | [AuthBasicUseDigestAlgorithm](mod_auth_basic#authbasicusedigestalgorithm) | <mod_auth_basic> | | Check passwords against the authentication providers as if Digest Authentication was in force instead of Basic Authentication. | | [AuthDBMGroupFile](mod_authz_dbm#authdbmgroupfile) | <mod_authz_dbm> | | Sets the name of the database file containing the list of user groups for authorization | | [AuthDBMType](mod_authn_dbm#authdbmtype) | <mod_authn_dbm> | | Sets the type of database file that is used to store passwords | | [AuthDBMUserFile](mod_authn_dbm#authdbmuserfile) | <mod_authn_dbm> | | Sets the name of a database file containing the list of users and passwords for authentication | | [AuthDigestAlgorithm](mod_auth_digest#authdigestalgorithm) | <mod_auth_digest> | | Selects the algorithm used to calculate the challenge and response hashes in digest authentication | | [AuthDigestDomain](mod_auth_digest#authdigestdomain) | <mod_auth_digest> | | URIs that are in the same protection space for digest authentication | | [AuthDigestNonceLifetime](mod_auth_digest#authdigestnoncelifetime) | <mod_auth_digest> | | How long the server nonce is valid | | [AuthDigestProvider](mod_auth_digest#authdigestprovider) | <mod_auth_digest> | | Sets the authentication provider(s) for this location | | [AuthDigestQop](mod_auth_digest#authdigestqop) | <mod_auth_digest> | | Determines the quality-of-protection to use in digest authentication | | [AuthFormAuthoritative](mod_auth_form#authformauthoritative) | <mod_auth_form> | | Sets whether authorization and authentication are passed to lower level modules | | [AuthFormProvider](mod_auth_form#authformprovider) | <mod_auth_form> | | Sets the authentication provider(s) for this location | | [AuthGroupFile](mod_authz_groupfile#authgroupfile) | <mod_authz_groupfile> | | Sets the name of a text file containing the list of user groups for authorization | | [AuthLDAPAuthorizePrefix](mod_authnz_ldap#authldapauthorizeprefix) | <mod_authnz_ldap> | | Specifies the prefix for environment variables set during authorization | | [AuthLDAPBindAuthoritative](mod_authnz_ldap#authldapbindauthoritative) | <mod_authnz_ldap> | | Determines if other authentication providers are used when a user can be mapped to a DN but the server cannot successfully bind with the user's credentials. | | [AuthLDAPBindDN](mod_authnz_ldap#authldapbinddn) | <mod_authnz_ldap> | | Optional DN to use in binding to the LDAP server | | [AuthLDAPBindPassword](mod_authnz_ldap#authldapbindpassword) | <mod_authnz_ldap> | | Password used in conjunction with the bind DN | | [AuthLDAPCompareAsUser](mod_authnz_ldap#authldapcompareasuser) | <mod_authnz_ldap> | | Use the authenticated user's credentials to perform authorization comparisons | | [AuthLDAPCompareDNOnServer](mod_authnz_ldap#authldapcomparednonserver) | <mod_authnz_ldap> | | Use the LDAP server to compare the DNs | | [AuthLDAPDereferenceAliases](mod_authnz_ldap#authldapdereferencealiases) | <mod_authnz_ldap> | | When will the module de-reference aliases | | [AuthLDAPGroupAttribute](mod_authnz_ldap#authldapgroupattribute) | <mod_authnz_ldap> | | LDAP attributes used to identify the user members of groups. | | [AuthLDAPGroupAttributeIsDN](mod_authnz_ldap#authldapgroupattributeisdn) | <mod_authnz_ldap> | | Use the DN of the client username when checking for group membership | | [AuthLDAPInitialBindAsUser](mod_authnz_ldap#authldapinitialbindasuser) | <mod_authnz_ldap> | | Determines if the server does the initial DN lookup using the basic authentication users' own username, instead of anonymously or with hard-coded credentials for the server | | [AuthLDAPInitialBindPattern](mod_authnz_ldap#authldapinitialbindpattern) | <mod_authnz_ldap> | | Specifies the transformation of the basic authentication username to be used when binding to the LDAP server to perform a DN lookup | | [AuthLDAPMaxSubGroupDepth](mod_authnz_ldap#authldapmaxsubgroupdepth) | <mod_authnz_ldap> | | Specifies the maximum sub-group nesting depth that will be evaluated before the user search is discontinued. | | [AuthLDAPRemoteUserAttribute](mod_authnz_ldap#authldapremoteuserattribute) | <mod_authnz_ldap> | | Use the value of the attribute returned during the user query to set the REMOTE\_USER environment variable | | [AuthLDAPRemoteUserIsDN](mod_authnz_ldap#authldapremoteuserisdn) | <mod_authnz_ldap> | | Use the DN of the client username to set the REMOTE\_USER environment variable | | [AuthLDAPSearchAsUser](mod_authnz_ldap#authldapsearchasuser) | <mod_authnz_ldap> | | Use the authenticated user's credentials to perform authorization searches | | [AuthLDAPSubGroupAttribute](mod_authnz_ldap#authldapsubgroupattribute) | <mod_authnz_ldap> | | Specifies the attribute labels, one value per directive line, used to distinguish the members of the current group that are groups. | | [AuthLDAPSubGroupClass](mod_authnz_ldap#authldapsubgroupclass) | <mod_authnz_ldap> | | Specifies which LDAP objectClass values identify directory objects that are groups during sub-group processing. | | [AuthLDAPURL](mod_authnz_ldap#authldapurl) | <mod_authnz_ldap> | | URL specifying the LDAP search parameters | | [AuthMerging](mod_authz_core#authmerging) | <mod_authz_core> | | Controls the manner in which each configuration section's authorization logic is combined with that of preceding configuration sections. | | [AuthName](mod_authn_core#authname) | <mod_authn_core> | | Authorization realm for use in HTTP authentication | | [AuthnCacheProvideFor](mod_authn_socache#authncacheprovidefor) | <mod_authn_socache> | | Specify which authn provider(s) to cache for | | [AuthnCacheTimeout](mod_authn_socache#authncachetimeout) | <mod_authn_socache> | | Set a timeout for cache entries | | [AuthType](mod_authn_core#authtype) | <mod_authn_core> | | Type of user authentication | | [AuthUserFile](mod_authn_file#authuserfile) | <mod_authn_file> | | Sets the name of a text file containing the list of users and passwords for authentication | | [AuthzDBMType](mod_authz_dbm#authzdbmtype) | <mod_authz_dbm> | | Sets the type of database file that is used to store list of user groups | | [CGIPassAuth](core#cgipassauth) | <core> | | Enables passing HTTP authorization headers to scripts as CGI variables | | [LDAPReferralHopLimit](mod_ldap#ldapreferralhoplimit) | <mod_ldap> | | The maximum number of referral hops to chase before terminating an LDAP query. | | [LDAPReferrals](mod_ldap#ldapreferrals) | <mod_ldap> | | Enable referral chasing during queries to the LDAP server. | | [<Limit>](core#limit) | <core> | | Restrict enclosed access controls to only certain HTTP methods | | [<LimitExcept>](core#limitexcept) | <core> | | Restrict access controls to all HTTP methods except the named ones | | [Require](mod_authz_core#require) | <mod_authz_core> | | Tests whether an authenticated user is authorized by an authorization provider. | | [<RequireAll>](mod_authz_core#requireall) | <mod_authz_core> | | Enclose a group of authorization directives of which none must fail and at least one must succeed for the enclosing directive to succeed. | | [<RequireAny>](mod_authz_core#requireany) | <mod_authz_core> | | Enclose a group of authorization directives of which one must succeed for the enclosing directive to succeed. | | [<RequireNone>](mod_authz_core#requirenone) | <mod_authz_core> | | Enclose a group of authorization directives of which none must succeed for the enclosing directive to not fail. | | [Satisfy](mod_access_compat#satisfy) | <mod_access_compat> | | Interaction between host-level access control and user authentication | | [Session](mod_session#session) | <mod_session> | | Enables a session for the current directory or location | | [SessionEnv](mod_session#sessionenv) | <mod_session> | | Control whether the contents of the session are written to the HTTP\_SESSION environment variable | | [SessionHeader](mod_session#sessionheader) | <mod_session> | | Import session updates from a given HTTP response header | | [SessionInclude](mod_session#sessioninclude) | <mod_session> | | Define URL prefixes for which a session is valid | | [SessionMaxAge](mod_session#sessionmaxage) | <mod_session> | | Define a maximum age in seconds for a session | | [SSLCipherSuite](mod_ssl#sslciphersuite) | <mod_ssl> | | Cipher Suite available for negotiation in SSL handshake | | [SSLRenegBufferSize](mod_ssl#sslrenegbuffersize) | <mod_ssl> | | Set the size for the SSL renegotiation buffer | | [SSLRequire](mod_ssl#sslrequire) | <mod_ssl> | | Allow access only when an arbitrarily complex boolean expression is true | | [SSLRequireSSL](mod_ssl#sslrequiressl) | <mod_ssl> | | Deny access when SSL is not used for the HTTP request | | [SSLUserName](mod_ssl#sslusername) | <mod_ssl> | | Variable name to determine user name | | [SSLVerifyClient](mod_ssl#sslverifyclient) | <mod_ssl> | | Type of Client Certificate verification | | [SSLVerifyDepth](mod_ssl#sslverifydepth) | <mod_ssl> | | Maximum depth of CA Certificates in Client Certificate verification | FileInfo -------- The following directives are allowed in .htaccess files when `AllowOverride FileInfo` is in effect. They give .htaccess users a wide range of control over the responses and metadata given by the server. | | | | --- | --- | | [AcceptPathInfo](core#acceptpathinfo) | <core> | | Resources accept trailing pathname information | | [Action](mod_actions#action) | <mod_actions> | | Activates a CGI script for a particular handler or content-type | | [AddCharset](mod_mime#addcharset) | <mod_mime> | | Maps the given filename extensions to the specified content charset | | [AddDefaultCharset](core#adddefaultcharset) | <core> | | Default charset parameter to be added when a response content-type is `text/plain` or `text/html` | | [AddEncoding](mod_mime#addencoding) | <mod_mime> | | Maps the given filename extensions to the specified encoding type | | [AddHandler](mod_mime#addhandler) | <mod_mime> | | Maps the filename extensions to the specified handler | | [AddInputFilter](mod_mime#addinputfilter) | <mod_mime> | | Maps filename extensions to the filters that will process client requests | | [AddLanguage](mod_mime#addlanguage) | <mod_mime> | | Maps the given filename extension to the specified content language | | [AddOutputFilter](mod_mime#addoutputfilter) | <mod_mime> | | Maps filename extensions to the filters that will process responses from the server | | [AddOutputFilterByType](mod_filter#addoutputfilterbytype) | <mod_filter> | | assigns an output filter to a particular media-type | | [AddType](mod_mime#addtype) | <mod_mime> | | Maps the given filename extensions onto the specified content type | | [BrowserMatch](mod_setenvif#browsermatch) | <mod_setenvif> | | Sets environment variables conditional on HTTP User-Agent | | [BrowserMatchNoCase](mod_setenvif#browsermatchnocase) | <mod_setenvif> | | Sets environment variables conditional on User-Agent without respect to case | | [CGIMapExtension](core#cgimapextension) | <core> | | Technique for locating the interpreter for CGI scripts | | [CGIVar](core#cgivar) | <core> | | Controls how some CGI variables are set | | [CharsetDefault](mod_charset_lite#charsetdefault) | <mod_charset_lite> | | Charset to translate into | | [CharsetOptions](mod_charset_lite#charsetoptions) | <mod_charset_lite> | | Configures charset translation behavior | | [CharsetSourceEnc](mod_charset_lite#charsetsourceenc) | <mod_charset_lite> | | Source charset of files | | [CookieDomain](mod_usertrack#cookiedomain) | <mod_usertrack> | | The domain to which the tracking cookie applies | | [CookieExpires](mod_usertrack#cookieexpires) | <mod_usertrack> | | Expiry time for the tracking cookie | | [CookieHTTPOnly](mod_usertrack#cookiehttponly) | <mod_usertrack> | | Adds the 'HTTPOnly' attribute to the cookie | | [CookieName](mod_usertrack#cookiename) | <mod_usertrack> | | Name of the tracking cookie | | [CookieSameSite](mod_usertrack#cookiesamesite) | <mod_usertrack> | | Adds the 'SameSite' attribute to the cookie | | [CookieSecure](mod_usertrack#cookiesecure) | <mod_usertrack> | | Adds the 'Secure' attribute to the cookie | | [CookieStyle](mod_usertrack#cookiestyle) | <mod_usertrack> | | Format of the cookie header field | | [CookieTracking](mod_usertrack#cookietracking) | <mod_usertrack> | | Enables tracking cookie | | [DefaultLanguage](mod_mime#defaultlanguage) | <mod_mime> | | Defines a default language-tag to be sent in the Content-Language header field for all resources in the current context that have not been assigned a language-tag by some other means. | | [DefaultType](core#defaulttype) | <core> | | This directive has no effect other than to emit warnings if the value is not `none`. In prior versions, DefaultType would specify a default media type to assign to response content for which no other media type configuration could be found. | | [EnableMMAP](core#enablemmap) | <core> | | Use memory-mapping to read files during delivery | | [EnableSendfile](core#enablesendfile) | <core> | | Use the kernel sendfile support to deliver files to the client | | [ErrorDocument](core#errordocument) | <core> | | What the server will return to the client in case of an error | | [FileETag](core#fileetag) | <core> | | File attributes used to create the ETag HTTP response header for static files | | [ForceLanguagePriority](mod_negotiation#forcelanguagepriority) | <mod_negotiation> | | Action to take if a single acceptable document is not found | | [ForceType](core#forcetype) | <core> | | Forces all matching files to be served with the specified media type in the HTTP Content-Type header field | | [Header](mod_headers#header) | <mod_headers> | | Configure HTTP response headers | | [ISAPIAppendLogToErrors](mod_isapi#isapiappendlogtoerrors) | <mod_isapi> | | Record `HSE_APPEND_LOG_PARAMETER` requests from ISAPI extensions to the error log | | [ISAPIAppendLogToQuery](mod_isapi#isapiappendlogtoquery) | <mod_isapi> | | Record `HSE_APPEND_LOG_PARAMETER` requests from ISAPI extensions to the query field | | [ISAPIFakeAsync](mod_isapi#isapifakeasync) | <mod_isapi> | | Fake asynchronous support for ISAPI callbacks | | [ISAPILogNotSupported](mod_isapi#isapilognotsupported) | <mod_isapi> | | Log unsupported feature requests from ISAPI extensions | | [ISAPIReadAheadBuffer](mod_isapi#isapireadaheadbuffer) | <mod_isapi> | | Size of the Read Ahead Buffer sent to ISAPI extensions | | [LanguagePriority](mod_negotiation#languagepriority) | <mod_negotiation> | | The precedence of language variants for cases where the client does not express a preference | | [MultiviewsMatch](mod_mime#multiviewsmatch) | <mod_mime> | | The types of files that will be included when searching for a matching file with MultiViews | | [PassEnv](mod_env#passenv) | <mod_env> | | Passes environment variables from the shell | | [QualifyRedirectURL](core#qualifyredirecturl) | <core> | | Controls whether the REDIRECT\_URL environment variable is fully qualified | | [Redirect](mod_alias#redirect) | <mod_alias> | | Sends an external redirect asking the client to fetch a different URL | | [RedirectMatch](mod_alias#redirectmatch) | <mod_alias> | | Sends an external redirect based on a regular expression match of the current URL | | [RedirectPermanent](mod_alias#redirectpermanent) | <mod_alias> | | Sends an external permanent redirect asking the client to fetch a different URL | | [RedirectTemp](mod_alias#redirecttemp) | <mod_alias> | | Sends an external temporary redirect asking the client to fetch a different URL | | [RemoveCharset](mod_mime#removecharset) | <mod_mime> | | Removes any character set associations for a set of file extensions | | [RemoveEncoding](mod_mime#removeencoding) | <mod_mime> | | Removes any content encoding associations for a set of file extensions | | [RemoveHandler](mod_mime#removehandler) | <mod_mime> | | Removes any handler associations for a set of file extensions | | [RemoveInputFilter](mod_mime#removeinputfilter) | <mod_mime> | | Removes any input filter associations for a set of file extensions | | [RemoveLanguage](mod_mime#removelanguage) | <mod_mime> | | Removes any language associations for a set of file extensions | | [RemoveOutputFilter](mod_mime#removeoutputfilter) | <mod_mime> | | Removes any output filter associations for a set of file extensions | | [RemoveType](mod_mime#removetype) | <mod_mime> | | Removes any content type associations for a set of file extensions | | [RequestHeader](mod_headers#requestheader) | <mod_headers> | | Configure HTTP request headers | | [RewriteBase](mod_rewrite#rewritebase) | <mod_rewrite> | | Sets the base URL for per-directory rewrites | | [RewriteCond](mod_rewrite#rewritecond) | <mod_rewrite> | | Defines a condition under which rewriting will take place | | [RewriteEngine](mod_rewrite#rewriteengine) | <mod_rewrite> | | Enables or disables runtime rewriting engine | | [RewriteOptions](mod_rewrite#rewriteoptions) | <mod_rewrite> | | Sets some special options for the rewrite engine | | [RewriteRule](mod_rewrite#rewriterule) | <mod_rewrite> | | Defines rules for the rewriting engine | | [ScriptInterpreterSource](core#scriptinterpretersource) | <core> | | Technique for locating the interpreter for CGI scripts | | [SetEnv](mod_env#setenv) | <mod_env> | | Sets environment variables | | [SetEnvIf](mod_setenvif#setenvif) | <mod_setenvif> | | Sets environment variables based on attributes of the request | | [SetEnvIfExpr](mod_setenvif#setenvifexpr) | <mod_setenvif> | | Sets environment variables based on an ap\_expr expression | | [SetEnvIfNoCase](mod_setenvif#setenvifnocase) | <mod_setenvif> | | Sets environment variables based on attributes of the request without respect to case | | [SetHandler](core#sethandler) | <core> | | Forces all matching files to be processed by a handler | | [SetInputFilter](core#setinputfilter) | <core> | | Sets the filters that will process client requests and POST input | | [SetOutputFilter](core#setoutputfilter) | <core> | | Sets the filters that will process responses from the server | | [Substitute](mod_substitute#substitute) | <mod_substitute> | | Pattern to filter the response content | | [SubstituteInheritBefore](mod_substitute#substituteinheritbefore) | <mod_substitute> | | Change the merge order of inherited patterns | | [SubstituteMaxLineLength](mod_substitute#substitutemaxlinelength) | <mod_substitute> | | Set the maximum line size | | [UnsetEnv](mod_env#unsetenv) | <mod_env> | | Removes variables from the environment | Indexes ------- The following directives are allowed in .htaccess files when `AllowOverride Indexes` is in effect. They allow .htaccess users to control aspects of the directory index pages provided by the server, including autoindex generation. | | | | --- | --- | | [AddAlt](mod_autoindex#addalt) | <mod_autoindex> | | Alternate text to display for a file, instead of an icon selected by filename | | [AddAltByEncoding](mod_autoindex#addaltbyencoding) | <mod_autoindex> | | Alternate text to display for a file instead of an icon selected by MIME-encoding | | [AddAltByType](mod_autoindex#addaltbytype) | <mod_autoindex> | | Alternate text to display for a file, instead of an icon selected by MIME content-type | | [AddDescription](mod_autoindex#adddescription) | <mod_autoindex> | | Description to display for a file | | [AddIcon](mod_autoindex#addicon) | <mod_autoindex> | | Icon to display for a file selected by name | | [AddIconByEncoding](mod_autoindex#addiconbyencoding) | <mod_autoindex> | | Icon to display next to files selected by MIME content-encoding | | [AddIconByType](mod_autoindex#addiconbytype) | <mod_autoindex> | | Icon to display next to files selected by MIME content-type | | [DefaultIcon](mod_autoindex#defaulticon) | <mod_autoindex> | | Icon to display for files when no specific icon is configured | | [DirectoryCheckHandler](mod_dir#directorycheckhandler) | <mod_dir> | | Toggle how this module responds when another handler is configured | | [DirectoryIndex](mod_dir#directoryindex) | <mod_dir> | | List of resources to look for when the client requests a directory | | [DirectoryIndexRedirect](mod_dir#directoryindexredirect) | <mod_dir> | | Configures an external redirect for directory indexes. | | [DirectorySlash](mod_dir#directoryslash) | <mod_dir> | | Toggle trailing slash redirects on or off | | [ExpiresActive](mod_expires#expiresactive) | <mod_expires> | | Enables generation of `Expires` headers | | [ExpiresByType](mod_expires#expiresbytype) | <mod_expires> | | Value of the `Expires` header configured by MIME type | | [ExpiresDefault](mod_expires#expiresdefault) | <mod_expires> | | Default algorithm for calculating expiration time | | [FallbackResource](mod_dir#fallbackresource) | <mod_dir> | | Define a default URL for requests that don't map to a file | | [HeaderName](mod_autoindex#headername) | <mod_autoindex> | | Name of the file that will be inserted at the top of the index listing | | [ImapBase](mod_imagemap#imapbase) | <mod_imagemap> | | Default `base` for imagemap files | | [ImapDefault](mod_imagemap#imapdefault) | <mod_imagemap> | | Default action when an imagemap is called with coordinates that are not explicitly mapped | | [ImapMenu](mod_imagemap#imapmenu) | <mod_imagemap> | | Action if no coordinates are given when calling an imagemap | | [IndexHeadInsert](mod_autoindex#indexheadinsert) | <mod_autoindex> | | Inserts text in the HEAD section of an index page. | | [IndexIgnore](mod_autoindex#indexignore) | <mod_autoindex> | | Adds to the list of files to hide when listing a directory | | [IndexIgnoreReset](mod_autoindex#indexignorereset) | <mod_autoindex> | | Empties the list of files to hide when listing a directory | | [IndexOptions](mod_autoindex#indexoptions) | <mod_autoindex> | | Various configuration settings for directory indexing | | [IndexOrderDefault](mod_autoindex#indexorderdefault) | <mod_autoindex> | | Sets the default ordering of the directory index | | [IndexStyleSheet](mod_autoindex#indexstylesheet) | <mod_autoindex> | | Adds a CSS stylesheet to the directory index | | [MetaDir](mod_cern_meta#metadir) | <mod_cern_meta> | | Name of the directory to find CERN-style meta information files | | [MetaFiles](mod_cern_meta#metafiles) | <mod_cern_meta> | | Activates CERN meta-file processing | | [MetaSuffix](mod_cern_meta#metasuffix) | <mod_cern_meta> | | File name suffix for the file containing CERN-style meta information | | [ReadmeName](mod_autoindex#readmename) | <mod_autoindex> | | Name of the file that will be inserted at the end of the index listing | Limit ----- The following directives are allowed in .htaccess files when `AllowOverride Limit` is in effect. This extremely narrow override type mostly allows the use of the legacy authorization directives provided by `<mod_access_compat>`. | | | | --- | --- | | [Allow](mod_access_compat#allow) | <mod_access_compat> | | Controls which hosts can access an area of the server | | [Deny](mod_access_compat#deny) | <mod_access_compat> | | Controls which hosts are denied access to the server | | [<Limit>](core#limit) | <core> | | Restrict enclosed access controls to only certain HTTP methods | | [<LimitExcept>](core#limitexcept) | <core> | | Restrict access controls to all HTTP methods except the named ones | | [Order](mod_access_compat#order) | <mod_access_compat> | | Controls the default access state and the order in which `Allow` and `Deny` are evaluated. | Options ------- The following directives are allowed in .htaccess files when `AllowOverride Options` is in effect. They give .htaccess users access to `Options` and similar directives, as well as directives that control the filter chain. | | | | --- | --- | | [CheckBasenameMatch](mod_speling#checkbasenamematch) | <mod_speling> | | Also match files with differing file name extensions. | | [CheckCaseOnly](mod_speling#checkcaseonly) | <mod_speling> | | Limits the action of the speling module to case corrections | | [CheckSpelling](mod_speling#checkspelling) | <mod_speling> | | Enables the spelling module | | [ContentDigest](core#contentdigest) | <core> | | Enables the generation of `Content-MD5` HTTP Response headers | | [FilterChain](mod_filter#filterchain) | <mod_filter> | | Configure the filter chain | | [FilterDeclare](mod_filter#filterdeclare) | <mod_filter> | | Declare a smart filter | | [FilterProtocol](mod_filter#filterprotocol) | <mod_filter> | | Deal with correct HTTP protocol handling | | [FilterProvider](mod_filter#filterprovider) | <mod_filter> | | Register a content filter | | [Options](core#options) | <core> | | Configures what features are available in a particular directory | | [ReflectorHeader](mod_reflector#reflectorheader) | <mod_reflector> | | Reflect an input header to the output headers | | [SSLOptions](mod_ssl#ssloptions) | <mod_ssl> | | Configure various SSL engine run-time options | | [XBitHack](mod_include#xbithack) | <mod_include> | | Parse SSI directives in files with the execute bit set |
programming_docs
apache_http_server Apache Module mod_ssl Apache Module mod\_ssl ====================== | | | | --- | --- | | Description: | Strong cryptography using the Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols | | Status: | Extension | | Module Identifier: | ssl\_module | | Source File: | mod\_ssl.c | ### Summary This module provides SSL v3 and TLS v1.x support for the Apache HTTP Server. SSL v2 is no longer supported. This module relies on [OpenSSL](http://www.openssl.org/) to provide the cryptography engine. Further details, discussion, and examples are provided in the [SSL documentation](../ssl/index). Environment Variables --------------------- This module can be configured to provide several items of SSL information as additional environment variables to the SSI and CGI namespace. Except for `HTTPS` and `SSL_TLS_SNI` which are always defined, this information is not provided by default for performance reasons. (See `[SSLOptions](#ssloptions)` `StdEnvVars`, below) The generated variables are listed in the table below. For backward compatibility the information can be made available under different names, too. Look in the [Compatibility](../ssl/ssl_compat) chapter for details on the compatibility variables. | Variable Name | Value Type | Description | | --- | --- | --- | | `HTTPS` | flag | HTTPS is being used. | | `SSL_PROTOCOL` | string | The SSL protocol version (SSLv3, TLSv1, TLSv1.1, TLSv1.2) | | `SSL_SESSION_ID` | string | The hex-encoded SSL session id | | `SSL_SESSION_RESUMED` | string | Initial or Resumed SSL Session. Note: multiple requests may be served over the same (Initial or Resumed) SSL session if HTTP KeepAlive is in use | | `SSL_SECURE_RENEG` | string | `true` if secure renegotiation is supported, else `false` | | `SSL_CIPHER` | string | The cipher specification name | | `SSL_CIPHER_EXPORT` | string | `true` if cipher is an export cipher | | `SSL_CIPHER_USEKEYSIZE` | number | Number of cipher bits (actually used) | | `SSL_CIPHER_ALGKEYSIZE` | number | Number of cipher bits (possible) | | `SSL_COMPRESS_METHOD` | string | SSL compression method negotiated | | `SSL_VERSION_INTERFACE` | string | The mod\_ssl program version | | `SSL_VERSION_LIBRARY` | string | The OpenSSL program version | | `SSL_CLIENT_M_VERSION` | string | The version of the client certificate | | `SSL_CLIENT_M_SERIAL` | string | The serial of the client certificate | | `SSL_CLIENT_S_DN` | string | Subject DN in client's certificate | | `SSL_CLIENT_S_DN_`*x509* | string | Component of client's Subject DN | | `SSL_CLIENT_SAN_Email_`*n* | string | Client certificate's subjectAltName extension entries of type rfc822Name | | `SSL_CLIENT_SAN_DNS_`*n* | string | Client certificate's subjectAltName extension entries of type dNSName | | `SSL_CLIENT_SAN_OTHER_msUPN_`*n* | string | Client certificate's subjectAltName extension entries of type otherName, Microsoft User Principal Name form (OID 1.3.6.1.4.1.311.20.2.3) | | `SSL_CLIENT_I_DN` | string | Issuer DN of client's certificate | | `SSL_CLIENT_I_DN_`*x509* | string | Component of client's Issuer DN | | `SSL_CLIENT_V_START` | string | Validity of client's certificate (start time) | | `SSL_CLIENT_V_END` | string | Validity of client's certificate (end time) | | `SSL_CLIENT_V_REMAIN` | string | Number of days until client's certificate expires | | `SSL_CLIENT_A_SIG` | string | Algorithm used for the signature of client's certificate | | `SSL_CLIENT_A_KEY` | string | Algorithm used for the public key of client's certificate | | `SSL_CLIENT_CERT` | string | PEM-encoded client certificate | | `SSL_CLIENT_CERT_CHAIN_`*n* | string | PEM-encoded certificates in client certificate chain | | `SSL_CLIENT_CERT_RFC4523_CEA` | string | Serial number and issuer of the certificate. The format matches that of the CertificateExactAssertion in RFC4523 | | `SSL_CLIENT_VERIFY` | string | `NONE`, `SUCCESS`, `GENEROUS` or `FAILED:`*reason* | | `SSL_SERVER_M_VERSION` | string | The version of the server certificate | | `SSL_SERVER_M_SERIAL` | string | The serial of the server certificate | | `SSL_SERVER_S_DN` | string | Subject DN in server's certificate | | `SSL_SERVER_SAN_Email_`*n* | string | Server certificate's subjectAltName extension entries of type rfc822Name | | `SSL_SERVER_SAN_DNS_`*n* | string | Server certificate's subjectAltName extension entries of type dNSName | | `SSL_SERVER_SAN_OTHER_dnsSRV_`*n* | string | Server certificate's subjectAltName extension entries of type otherName, SRVName form (OID 1.3.6.1.5.5.7.8.7, RFC 4985) | | `SSL_SERVER_S_DN_`*x509* | string | Component of server's Subject DN | | `SSL_SERVER_I_DN` | string | Issuer DN of server's certificate | | `SSL_SERVER_I_DN_`*x509* | string | Component of server's Issuer DN | | `SSL_SERVER_V_START` | string | Validity of server's certificate (start time) | | `SSL_SERVER_V_END` | string | Validity of server's certificate (end time) | | `SSL_SERVER_A_SIG` | string | Algorithm used for the signature of server's certificate | | `SSL_SERVER_A_KEY` | string | Algorithm used for the public key of server's certificate | | `SSL_SERVER_CERT` | string | PEM-encoded server certificate | | `SSL_SRP_USER` | string | SRP username | | `SSL_SRP_USERINFO` | string | SRP user info | | `SSL_TLS_SNI` | string | Contents of the SNI TLS extension (if supplied with ClientHello) | *x509* specifies a component of an X.509 DN; one of `C,ST,L,O,OU,CN,T,I,G,S,D,UID,Email`. In httpd 2.2.0 and later, *x509* may also include a numeric `_n` suffix. If the DN in question contains multiple attributes of the same name, this suffix is used as a zero-based index to select a particular attribute. For example, where the server certificate subject DN included two OU attributes, `SSL_SERVER_S_DN_OU_0` and `SSL_SERVER_S_DN_OU_1` could be used to reference each. A variable name without a `_n` suffix is equivalent to that name with a `_0` suffix; the first (or only) attribute. When the environment table is populated using the `StdEnvVars` option of the `[SSLOptions](#ssloptions)` directive, the first (or only) attribute of any DN is added only under a non-suffixed name; i.e. no `_0` suffixed entries are added. In httpd 2.4.32 and later, an optional *\_RAW* suffix may be added to *x509* in a DN component, to suppress conversion of the attribute value to UTF-8. This must be placed after the index suffix (if any). For example, `SSL_SERVER_S_DN_OU_RAW` or `SSL_SERVER_S_DN_OU_0_RAW` could be used. The format of the *\*\_DN* variables has changed in Apache HTTPD 2.3.11. See the `LegacyDNStringFormat` option for `[SSLOptions](#ssloptions)` for details. `SSL_CLIENT_V_REMAIN` is only available in version 2.1 and later. A number of additional environment variables can also be used in `SSLRequire` expressions, or in custom log formats: ``` HTTP_USER_AGENT PATH_INFO AUTH_TYPE HTTP_REFERER QUERY_STRING SERVER_SOFTWARE HTTP_COOKIE REMOTE_HOST API_VERSION HTTP_FORWARDED REMOTE_IDENT TIME_YEAR HTTP_HOST IS_SUBREQ TIME_MON HTTP_PROXY_CONNECTION DOCUMENT_ROOT TIME_DAY HTTP_ACCEPT SERVER_ADMIN TIME_HOUR THE_REQUEST SERVER_NAME TIME_MIN REQUEST_FILENAME SERVER_PORT TIME_SEC REQUEST_METHOD SERVER_PROTOCOL TIME_WDAY REQUEST_SCHEME REMOTE_ADDR TIME REQUEST_URI REMOTE_USER ``` In these contexts, two special formats can also be used: `ENV:*variablename*` This will expand to the standard environment variable *variablename*. `HTTP:*headername*` This will expand to the value of the request header with name *headername*. Custom Log Formats ------------------ When `<mod_ssl>` is built into Apache or at least loaded (under DSO situation) additional functions exist for the [Custom Log Format](mod_log_config#formats) of `<mod_log_config>`. First there is an additional ```%{`*varname*`}x`'' eXtension format function which can be used to expand any variables provided by any module, especially those provided by mod\_ssl which can you find in the above table. For backward compatibility there is additionally a special ```%{`*name*`}c`'' cryptography format function provided. Information about this function is provided in the [Compatibility](../ssl/ssl_compat) chapter. ### Example ``` CustomLog "logs/ssl_request_log" "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b" ``` These formats even work without setting the `StdEnvVars` option of the `[SSLOptions](#ssloptions)` directive. Request Notes ------------- `<mod_ssl>` sets "notes" for the request which can be used in logging with the `%{*name*}n` format string in `<mod_log_config>`. The notes supported are as follows: `ssl-access-forbidden` This note is set to the value `1` if access was denied due to an `SSLRequire` or `SSLRequireSSL` directive. `ssl-secure-reneg` If `<mod_ssl>` is built against a version of OpenSSL which supports the secure renegotiation extension, this note is set to the value `1` if SSL is in used for the current connection, and the client also supports the secure renegotiation extension. If the client does not support the secure renegotiation extension, the note is set to the value `0`. If `<mod_ssl>` is not built against a version of OpenSSL which supports secure renegotiation, or if SSL is not in use for the current connection, the note is not set. Expression Parser Extension --------------------------- When `<mod_ssl>` is built into Apache or at least loaded (under DSO situation) any variables provided by `<mod_ssl>` can be used in expressions for the [ap\_expr Expression Parser](../expr). The variables can be referenced using the syntax ```%{`*varname*`}`''. Starting with version 2.4.18 one can also use the `<mod_rewrite>` style syntax ```%{SSL:`*varname*`}`'' or the function style syntax ```ssl(`*varname*`)`''. ### Example (using `<mod_headers>`) ``` Header set X-SSL-PROTOCOL "expr=%{SSL_PROTOCOL}" Header set X-SSL-CIPHER "expr=%{SSL:SSL_CIPHER}" ``` This feature even works without setting the `StdEnvVars` option of the `[SSLOptions](#ssloptions)` directive. Authorization providers for use with Require -------------------------------------------- `<mod_ssl>` provides a few authentication providers for use with `<mod_authz_core>`'s `[Require](mod_authz_core#require)` directive. ### Require ssl The `ssl` provider denies access if a connection is not encrypted with SSL. This is similar to the `SSLRequireSSL` directive. ``` Require ssl ``` ### Require ssl-verify-client The `ssl` provider allows access if the user is authenticated with a valid client certificate. This is only useful if `SSLVerifyClient optional` is in effect. The following example grants access if the user is authenticated either with a client certificate or by username and password. ``` Require ssl-verify-client Require valid-user ``` SSLCACertificateFile Directive ------------------------------ | | | | --- | --- | | Description: | File of concatenated PEM-encoded CA Certificates for Client Auth | | Syntax: | ``` SSLCACertificateFile file-path ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This directive sets the *all-in-one* file where you can assemble the Certificates of Certification Authorities (CA) whose *clients* you deal with. These are used for Client Authentication. Such a file is simply the concatenation of the various PEM-encoded Certificate files, in order of preference. This can be used alternatively and/or additionally to `[SSLCACertificatePath](#sslcacertificatepath)`. ### Example ``` SSLCACertificateFile "/usr/local/apache2/conf/ssl.crt/ca-bundle-client.crt" ``` SSLCACertificatePath Directive ------------------------------ | | | | --- | --- | | Description: | Directory of PEM-encoded CA Certificates for Client Auth | | Syntax: | ``` SSLCACertificatePath directory-path ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This directive sets the directory where you keep the Certificates of Certification Authorities (CAs) whose clients you deal with. These are used to verify the client certificate on Client Authentication. The files in this directory have to be PEM-encoded and are accessed through hash filenames. So usually you can't just place the Certificate files there: you also have to create symbolic links named *hash-value*`.N`. And you should always make sure this directory contains the appropriate symbolic links. ### Example ``` SSLCACertificatePath "/usr/local/apache2/conf/ssl.crt/" ``` SSLCADNRequestFile Directive ---------------------------- | | | | --- | --- | | Description: | File of concatenated PEM-encoded CA Certificates for defining acceptable CA names | | Syntax: | ``` SSLCADNRequestFile file-path ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | When a client certificate is requested by mod\_ssl, a list of *acceptable Certificate Authority names* is sent to the client in the SSL handshake. These CA names can be used by the client to select an appropriate client certificate out of those it has available. If neither of the directives `[SSLCADNRequestPath](#sslcadnrequestpath)` or `[SSLCADNRequestFile](#sslcadnrequestfile)` are given, then the set of acceptable CA names sent to the client is the names of all the CA certificates given by the `[SSLCACertificateFile](#sslcacertificatefile)` and `[SSLCACertificatePath](#sslcacertificatepath)` directives; in other words, the names of the CAs which will actually be used to verify the client certificate. In some circumstances, it is useful to be able to send a set of acceptable CA names which differs from the actual CAs used to verify the client certificate - for example, if the client certificates are signed by intermediate CAs. In such cases, `[SSLCADNRequestPath](#sslcadnrequestpath)` and/or `[SSLCADNRequestFile](#sslcadnrequestfile)` can be used; the acceptable CA names are then taken from the complete set of certificates in the directory and/or file specified by this pair of directives. `[SSLCADNRequestFile](#sslcadnrequestfile)` must specify an *all-in-one* file containing a concatenation of PEM-encoded CA certificates. ### Example ``` SSLCADNRequestFile "/usr/local/apache2/conf/ca-names.crt" ``` SSLCADNRequestPath Directive ---------------------------- | | | | --- | --- | | Description: | Directory of PEM-encoded CA Certificates for defining acceptable CA names | | Syntax: | ``` SSLCADNRequestPath directory-path ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This optional directive can be used to specify the set of *acceptable CA names* which will be sent to the client when a client certificate is requested. See the `[SSLCADNRequestFile](#sslcadnrequestfile)` directive for more details. The files in this directory have to be PEM-encoded and are accessed through hash filenames. So usually you can't just place the Certificate files there: you also have to create symbolic links named *hash-value*`.N`. And you should always make sure this directory contains the appropriate symbolic links. ### Example ``` SSLCADNRequestPath "/usr/local/apache2/conf/ca-names.crt/" ``` SSLCARevocationCheck Directive ------------------------------ | | | | --- | --- | | Description: | Enable CRL-based revocation checking | | Syntax: | ``` SSLCARevocationCheck chain|leaf|none [flags ...] ``` | | Default: | ``` SSLCARevocationCheck none ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Optional *flag*s available in httpd 2.4.21 or later | Enables certificate revocation list (CRL) checking. At least one of `[SSLCARevocationFile](#sslcarevocationfile)` or `[SSLCARevocationPath](#sslcarevocationpath)` must be configured. When set to `chain` (recommended setting), CRL checks are applied to all certificates in the chain, while setting it to `leaf` limits the checks to the end-entity cert. The available *flag*s are: * `no_crl_for_cert_ok` Prior to version 2.3.15, CRL checking in mod\_ssl also succeeded when no CRL(s) for the checked certificate(s) were found in any of the locations configured with `[SSLCARevocationFile](#sslcarevocationfile)` or `[SSLCARevocationPath](#sslcarevocationpath)`. With the introduction of `SSLCARevocationFile`, the behavior has been changed: by default with `chain` or `leaf`, CRLs **must** be present for the validation to succeed - otherwise it will fail with an `"unable to get certificate CRL"` error. The *flag* `no_crl_for_cert_ok` allows to restore previous behaviour. ### Example ``` SSLCARevocationCheck chain ``` ### Compatibility with versions 2.2 ``` SSLCARevocationCheck chain no_crl_for_cert_ok ``` SSLCARevocationFile Directive ----------------------------- | | | | --- | --- | | Description: | File of concatenated PEM-encoded CA CRLs for Client Auth | | Syntax: | ``` SSLCARevocationFile file-path ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This directive sets the *all-in-one* file where you can assemble the Certificate Revocation Lists (CRL) of Certification Authorities (CA) whose *clients* you deal with. These are used for Client Authentication. Such a file is simply the concatenation of the various PEM-encoded CRL files, in order of preference. This can be used alternatively and/or additionally to `[SSLCARevocationPath](#sslcarevocationpath)`. ### Example ``` SSLCARevocationFile "/usr/local/apache2/conf/ssl.crl/ca-bundle-client.crl" ``` SSLCARevocationPath Directive ----------------------------- | | | | --- | --- | | Description: | Directory of PEM-encoded CA CRLs for Client Auth | | Syntax: | ``` SSLCARevocationPath directory-path ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This directive sets the directory where you keep the Certificate Revocation Lists (CRL) of Certification Authorities (CAs) whose clients you deal with. These are used to revoke the client certificate on Client Authentication. The files in this directory have to be PEM-encoded and are accessed through hash filenames. So usually you have not only to place the CRL files there. Additionally you have to create symbolic links named *hash-value*`.rN`. And you should always make sure this directory contains the appropriate symbolic links. ### Example ``` SSLCARevocationPath "/usr/local/apache2/conf/ssl.crl/" ``` SSLCertificateChainFile Directive --------------------------------- | | | | --- | --- | | Description: | File of PEM-encoded Server CA Certificates | | Syntax: | ``` SSLCertificateChainFile file-path ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | **SSLCertificateChainFile is deprecated** `SSLCertificateChainFile` became obsolete with version 2.4.8, when `[SSLCertificateFile](#sslcertificatefile)` was extended to also load intermediate CA certificates from the server certificate file. This directive sets the optional *all-in-one* file where you can assemble the certificates of Certification Authorities (CA) which form the certificate chain of the server certificate. This starts with the issuing CA certificate of the server certificate and can range up to the root CA certificate. Such a file is simply the concatenation of the various PEM-encoded CA Certificate files, usually in certificate chain order. This should be used alternatively and/or additionally to `[SSLCACertificatePath](#sslcacertificatepath)` for explicitly constructing the server certificate chain which is sent to the browser in addition to the server certificate. It is especially useful to avoid conflicts with CA certificates when using client authentication. Because although placing a CA certificate of the server certificate chain into `[SSLCACertificatePath](#sslcacertificatepath)` has the same effect for the certificate chain construction, it has the side-effect that client certificates issued by this same CA certificate are also accepted on client authentication. But be careful: Providing the certificate chain works only if you are using a *single* RSA *or* DSA based server certificate. If you are using a coupled RSA+DSA certificate pair, this will work only if actually both certificates use the *same* certificate chain. Else the browsers will be confused in this situation. ### Example ``` SSLCertificateChainFile "/usr/local/apache2/conf/ssl.crt/ca.crt" ``` SSLCertificateFile Directive ---------------------------- | | | | --- | --- | | Description: | Server PEM-encoded X.509 certificate data file or token identifier | | Syntax: | ``` SSLCertificateFile file-path|certid ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | certid available in 2.4.42 and later. | This directive points to a file with certificate data in PEM format, or the certificate identifier through a configured cryptographic token. If using a PEM file, at minimum, the file must include an end-entity (leaf) certificate. The directive can be used multiple times (referencing different filenames) to support multiple algorithms for server authentication - typically RSA, DSA, and ECC. The number of supported algorithms depends on the OpenSSL version being used for mod\_ssl: with version 1.0.0 or later, `openssl list-public-key-algorithms` will output a list of supported algorithms, see also the note below about limitations of OpenSSL versions prior to 1.0.2 and the ways to work around them. The files may also include intermediate CA certificates, sorted from leaf to root. This is supported with version 2.4.8 and later, and obsoletes `[SSLCertificateChainFile](#sslcertificatechainfile)`. When running with OpenSSL 1.0.2 or later, this allows to configure the intermediate CA chain on a per-certificate basis. Custom DH parameters and an EC curve name for ephemeral keys, can also be added to end of the first file configured using `[SSLCertificateFile](#sslcertificatefile)`. This is supported in version 2.4.7 or later. Such parameters can be generated using the commands `openssl dhparam` and `openssl ecparam`. The parameters can be added as-is to the end of the first certificate file. Only the first file can be used for custom parameters, as they are applied independently of the authentication algorithm type. Finally the end-entity certificate's private key can also be added to the certificate file instead of using a separate `[SSLCertificateKeyFile](#sslcertificatekeyfile)` directive. This practice is highly discouraged. If it is used, the certificate files using such an embedded key must be configured after the certificates using a separate key file. If the private key is encrypted, the pass phrase dialog is forced at startup time. As an alternative to storing certificates and private keys in files, a certificate identifier can be used to identify a certificate stored in a token. Currently, only [PKCS#11 URIs](https://tools.ietf.org/html/rfc7512) are recognized as certificate identifiers, and can be used in conjunction with the OpenSSL `pkcs11` engine. If `[SSLCertificateKeyFile](#sslcertificatekeyfile)` is omitted, the certificate and private key can be loaded through the single identifier specified with `[SSLCertificateFile](#sslcertificatefile)`. **DH parameter interoperability with primes > 1024 bit** Beginning with version 2.4.7, mod\_ssl makes use of standardized DH parameters with prime lengths of 2048, 3072 and 4096 bits and with additional prime lengths of 6144 and 8192 bits beginning with version 2.4.10 (from [RFC 3526](http://www.ietf.org/rfc/rfc3526.txt)), and hands them out to clients based on the length of the certificate's RSA/DSA key. With Java-based clients in particular (Java 7 or earlier), this may lead to handshake failures - see this [FAQ answer](../ssl/ssl_faq#javadh) for working around such issues. **Default DH parameters when using multiple certificates and OpenSSL versions prior to 1.0.2** When using multiple certificates to support different authentication algorithms (like RSA, DSA, but mainly ECC) and OpenSSL prior to 1.0.2, it is recommended to either use custom DH parameters (preferably) by adding them to the first certificate file (as described above), or to order the `SSLCertificateFile` directives such that RSA/DSA certificates are placed **after** the ECC one. This is due to a limitation in older versions of OpenSSL which don't let the Apache HTTP Server determine the currently selected certificate at handshake time (when the DH parameters must be sent to the peer) but instead always provide the last configured certificate. Consequently, the server may select default DH parameters based on the length of the wrong certificate's key (ECC keys are much smaller than RSA/DSA ones and their length is not relevant for selecting DH primes). Since custom DH parameters always take precedence over the default ones, this issue can be avoided by creating and configuring them (as described above), thus using a custom/suitable length. ### Example ``` # Example using a PEM-encoded file. SSLCertificateFile "/usr/local/apache2/conf/ssl.crt/server.crt" # Example use of a certificate and private key from a PKCS#11 token: SSLCertificateFile "pkcs11:token=My%20Token%20Name;id=45" ``` SSLCertificateKeyFile Directive ------------------------------- | | | | --- | --- | | Description: | Server PEM-encoded private key file | | Syntax: | ``` SSLCertificateKeyFile file-path|keyid ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | keyid available in 2.4.42 and later. | This directive points to the PEM-encoded private key file for the server, or the key ID through a configured cryptographic token. If the contained private key is encrypted, the pass phrase dialog is forced at startup time. The directive can be used multiple times (referencing different filenames) to support multiple algorithms for server authentication. For each `[SSLCertificateKeyFile](#sslcertificatekeyfile)` directive, there must be a matching `SSLCertificateFile` directive. The private key may also be combined with the certificate in the file given by `[SSLCertificateFile](#sslcertificatefile)`, but this practice is highly discouraged. If it is used, the certificate files using such an embedded key must be configured after the certificates using a separate key file. As an alternative to storing private keys in files, a key identifier can be used to identify a private key stored in a token. Currently, only [PKCS#11 URIs](https://tools.ietf.org/html/rfc7512) are recognized as private key identifiers, and can be used in conjunction with the OpenSSL `pkcs11` engine. ### Example ``` # To use a private key from a PEM-encoded file: SSLCertificateKeyFile "/usr/local/apache2/conf/ssl.key/server.key" # To use a private key from a PKCS#11 token: SSLCertificateKeyFile "pkcs11:token=My%20Token%20Name;id=45" ``` SSLCipherSuite Directive ------------------------ | | | | --- | --- | | Description: | Cipher Suite available for negotiation in SSL handshake | | Syntax: | ``` SSLCipherSuite [protocol] cipher-spec ``` | | Default: | ``` SSLCipherSuite DEFAULT (depends on OpenSSL version) ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_ssl | This complex directive uses a colon-separated *cipher-spec* string consisting of OpenSSL cipher specifications to configure the Cipher Suite the client is permitted to negotiate in the SSL handshake phase. The optional protocol specifier can configure the Cipher Suite for a specific SSL version. Possible values include "SSL" for all SSL Protocols up to and including TLSv1.2. Notice that this directive can be used both in per-server and per-directory context. In per-server context it applies to the standard SSL handshake when a connection is established. In per-directory context it forces a SSL renegotiation with the reconfigured Cipher Suite after the HTTP request was read but before the HTTP response is sent. If the SSL library supports TLSv1.3 (OpenSSL 1.1.1 and later), the protocol specifier "TLSv1.3" can be used to configure the cipher suites for that protocol. Since TLSv1.3 does not offer renegotiations, specifying ciphers for it in a directory context is not allowed. For a list of TLSv1.3 cipher names, see [the OpenSSL documentation](https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_ciphersuites.html). An SSL cipher specification in *cipher-spec* is composed of 4 major attributes plus a few extra minor ones: * *Key Exchange Algorithm*: RSA, Diffie-Hellman, Elliptic Curve Diffie-Hellman, Secure Remote Password * *Authentication Algorithm*: RSA, Diffie-Hellman, DSS, ECDSA, or none. * *Cipher/Encryption Algorithm*: AES, DES, Triple-DES, RC4, RC2, IDEA, etc. * *MAC Digest Algorithm*: MD5, SHA or SHA1, SHA256, SHA384. An SSL cipher can also be an export cipher. SSLv2 ciphers are no longer supported. To specify which ciphers to use, one can either specify all the Ciphers, one at a time, or use aliases to specify the preference and order for the ciphers (see [Table 1](#table1)). The actually available ciphers and aliases depends on the used openssl version. Newer openssl versions may include additional ciphers. | Tag | Description | | --- | --- | | *Key Exchange Algorithm:* | | `kRSA` | RSA key exchange | | `kDHr` | Diffie-Hellman key exchange with RSA key | | `kDHd` | Diffie-Hellman key exchange with DSA key | | `kEDH` | Ephemeral (temp.key) Diffie-Hellman key exchange (no cert) | | `kSRP` | Secure Remote Password (SRP) key exchange | | *Authentication Algorithm:* | | `aNULL` | No authentication | | `aRSA` | RSA authentication | | `aDSS` | DSS authentication | | `aDH` | Diffie-Hellman authentication | | *Cipher Encoding Algorithm:* | | `eNULL` | No encryption | | `NULL` | alias for eNULL | | `AES` | AES encryption | | `DES` | DES encryption | | `3DES` | Triple-DES encryption | | `RC4` | RC4 encryption | | `RC2` | RC2 encryption | | `IDEA` | IDEA encryption | | *MAC Digest Algorithm*: | | `MD5` | MD5 hash function | | `SHA1` | SHA1 hash function | | `SHA` | alias for SHA1 | | `SHA256` | SHA256 hash function | | `SHA384` | SHA384 hash function | | *Aliases:* | | `SSLv3` | all SSL version 3.0 ciphers | | `TLSv1` | all TLS version 1.0 ciphers | | `EXP` | all export ciphers | | `EXPORT40` | all 40-bit export ciphers only | | `EXPORT56` | all 56-bit export ciphers only | | `LOW` | all low strength ciphers (no export, single DES) | | `MEDIUM` | all ciphers with 128 bit encryption | | `HIGH` | all ciphers using Triple-DES | | `RSA` | all ciphers using RSA key exchange | | `DH` | all ciphers using Diffie-Hellman key exchange | | `EDH` | all ciphers using Ephemeral Diffie-Hellman key exchange | | `ECDH` | Elliptic Curve Diffie-Hellman key exchange | | `ADH` | all ciphers using Anonymous Diffie-Hellman key exchange | | `AECDH` | all ciphers using Anonymous Elliptic Curve Diffie-Hellman key exchange | | `SRP` | all ciphers using Secure Remote Password (SRP) key exchange | | `DSS` | all ciphers using DSS authentication | | `ECDSA` | all ciphers using ECDSA authentication | | `aNULL` | all ciphers using no authentication | Now where this becomes interesting is that these can be put together to specify the order and ciphers you wish to use. To speed this up there are also aliases (`SSLv3, TLSv1, EXP, LOW, MEDIUM, HIGH`) for certain groups of ciphers. These tags can be joined together with prefixes to form the *cipher-spec*. Available prefixes are: * none: add cipher to list * `+`: move matching ciphers to the current location in list * `-`: remove cipher from list (can be added later again) * `!`: kill cipher from list completely (can **not** be added later again) **`aNULL`, `eNULL` and `EXP` ciphers are always disabled** Beginning with version 2.4.7, null and export-grade ciphers are always disabled, as mod\_ssl unconditionally adds `!aNULL:!eNULL:!EXP` to any cipher string at initialization. A simpler way to look at all of this is to use the ```openssl ciphers -v`'' command which provides a nice way to successively create the correct *cipher-spec* string. The default *cipher-spec* string depends on the version of the OpenSSL libraries used. Let's suppose it is ```RC4-SHA:AES128-SHA:HIGH:MEDIUM:!aNULL:!MD5`'' which means the following: Put `RC4-SHA` and `AES128-SHA` at the beginning. We do this, because these ciphers offer a good compromise between speed and security. Next, include high and medium security ciphers. Finally, remove all ciphers which do not authenticate, i.e. for SSL the Anonymous Diffie-Hellman ciphers, as well as all ciphers which use `MD5` as hash algorithm, because it has been proven insufficient. ``` $ openssl ciphers -v 'RC4-SHA:AES128-SHA:HIGH:MEDIUM:!aNULL:!MD5' RC4-SHA SSLv3 Kx=RSA Au=RSA Enc=RC4(128) Mac=SHA1 AES128-SHA SSLv3 Kx=RSA Au=RSA Enc=AES(128) Mac=SHA1 DHE-RSA-AES256-SHA SSLv3 Kx=DH Au=RSA Enc=AES(256) Mac=SHA1 ... ... ... ... ... SEED-SHA SSLv3 Kx=RSA Au=RSA Enc=SEED(128) Mac=SHA1 PSK-RC4-SHA SSLv3 Kx=PSK Au=PSK Enc=RC4(128) Mac=SHA1 KRB5-RC4-SHA SSLv3 Kx=KRB5 Au=KRB5 Enc=RC4(128) Mac=SHA1 ``` The complete list of particular RSA & DH ciphers for SSL is given in [Table 2](#table2). ### Example ``` SSLCipherSuite RSA:!EXP:!NULL:+HIGH:+MEDIUM:-LOW ``` | Cipher-Tag | Protocol | Key Ex. | Auth. | Enc. | MAC | Type | | --- | --- | --- | --- | --- | --- | --- | | *RSA Ciphers:* | | `DES-CBC3-SHA` | SSLv3 | RSA | RSA | 3DES(168) | SHA1 | | | `IDEA-CBC-SHA` | SSLv3 | RSA | RSA | IDEA(128) | SHA1 | | | `RC4-SHA` | SSLv3 | RSA | RSA | RC4(128) | SHA1 | | | `RC4-MD5` | SSLv3 | RSA | RSA | RC4(128) | MD5 | | | `DES-CBC-SHA` | SSLv3 | RSA | RSA | DES(56) | SHA1 | | | `EXP-DES-CBC-SHA` | SSLv3 | RSA(512) | RSA | DES(40) | SHA1 | export | | `EXP-RC2-CBC-MD5` | SSLv3 | RSA(512) | RSA | RC2(40) | MD5 | export | | `EXP-RC4-MD5` | SSLv3 | RSA(512) | RSA | RC4(40) | MD5 | export | | `NULL-SHA` | SSLv3 | RSA | RSA | None | SHA1 | | | `NULL-MD5` | SSLv3 | RSA | RSA | None | MD5 | | | *Diffie-Hellman Ciphers:* | | `ADH-DES-CBC3-SHA` | SSLv3 | DH | None | 3DES(168) | SHA1 | | | `ADH-DES-CBC-SHA` | SSLv3 | DH | None | DES(56) | SHA1 | | | `ADH-RC4-MD5` | SSLv3 | DH | None | RC4(128) | MD5 | | | `EDH-RSA-DES-CBC3-SHA` | SSLv3 | DH | RSA | 3DES(168) | SHA1 | | | `EDH-DSS-DES-CBC3-SHA` | SSLv3 | DH | DSS | 3DES(168) | SHA1 | | | `EDH-RSA-DES-CBC-SHA` | SSLv3 | DH | RSA | DES(56) | SHA1 | | | `EDH-DSS-DES-CBC-SHA` | SSLv3 | DH | DSS | DES(56) | SHA1 | | | `EXP-EDH-RSA-DES-CBC-SHA` | SSLv3 | DH(512) | RSA | DES(40) | SHA1 | export | | `EXP-EDH-DSS-DES-CBC-SHA` | SSLv3 | DH(512) | DSS | DES(40) | SHA1 | export | | `EXP-ADH-DES-CBC-SHA` | SSLv3 | DH(512) | None | DES(40) | SHA1 | export | | `EXP-ADH-RC4-MD5` | SSLv3 | DH(512) | None | RC4(40) | MD5 | export | SSLCompression Directive ------------------------ | | | | --- | --- | | Description: | Enable compression on the SSL level | | Syntax: | ``` SSLCompression on|off ``` | | Default: | ``` SSLCompression off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in httpd 2.4.3 and later, if using OpenSSL 0.9.8 or later; virtual host scope available if using OpenSSL 1.0.0 or later. The default used to be `on` in version 2.4.3. | This directive allows to enable compression on the SSL level. Enabling compression causes security issues in most setups (the so called CRIME attack). SSLCryptoDevice Directive ------------------------- | | | | --- | --- | | Description: | Enable use of a cryptographic hardware accelerator | | Syntax: | ``` SSLCryptoDevice engine ``` | | Default: | ``` SSLCryptoDevice builtin ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ssl | This directive enables use of a cryptographic hardware accelerator board to offload some of the SSL processing overhead. This directive can only be used if the SSL toolkit is built with "engine" support; OpenSSL 0.9.7 and later releases have "engine" support by default, the separate "-engine" releases of OpenSSL 0.9.6 must be used. To discover which engine names are supported, run the command "`openssl engine`". ### Example ``` # For a Broadcom accelerator: SSLCryptoDevice ubsec ``` SSLEngine Directive ------------------- | | | | --- | --- | | Description: | SSL Engine Operation Switch | | Syntax: | ``` SSLEngine on|off|optional ``` | | Default: | ``` SSLEngine off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This directive toggles the usage of the SSL/TLS Protocol Engine. This is should be used inside a `[<VirtualHost>](core#virtualhost)` section to enable SSL/TLS for a that virtual host. By default the SSL/TLS Protocol Engine is disabled for both the main server and all configured virtual hosts. ### Example ``` <VirtualHost _default_:443> SSLEngine on #... </VirtualHost> ``` In Apache 2.1 and later, `SSLEngine` can be set to `optional`. This enables support for [RFC 2817](http://www.ietf.org/rfc/rfc2817.txt), Upgrading to TLS Within HTTP/1.1. At this time no web browsers support RFC 2817. SSLFIPS Directive ----------------- | | | | --- | --- | | Description: | SSL FIPS mode Switch | | Syntax: | ``` SSLFIPS on|off ``` | | Default: | ``` SSLFIPS off ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ssl | This directive toggles the usage of the SSL library FIPS\_mode flag. It must be set in the global server context and cannot be configured with conflicting settings (SSLFIPS on followed by SSLFIPS off or similar). The mode applies to all SSL library operations. If httpd was compiled against an SSL library which did not support the FIPS\_mode flag, `SSLFIPS on` will fail. Refer to the FIPS 140-2 Security Policy document of the SSL provider library for specific requirements to use mod\_ssl in a FIPS 140-2 approved mode of operation; note that mod\_ssl itself is not validated, but may be described as using FIPS 140-2 validated cryptographic module, when all components are assembled and operated under the guidelines imposed by the applicable Security Policy. SSLHonorCipherOrder Directive ----------------------------- | | | | --- | --- | | Description: | Option to prefer the server's cipher preference order | | Syntax: | ``` SSLHonorCipherOrder on|off ``` | | Default: | ``` SSLHonorCipherOrder off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | When choosing a cipher during an SSLv3 or TLSv1 handshake, normally the client's preference is used. If this directive is enabled, the server's preference will be used instead. ### Example ``` SSLHonorCipherOrder on ``` SSLInsecureRenegotiation Directive ---------------------------------- | | | | --- | --- | | Description: | Option to enable support for insecure renegotiation | | Syntax: | ``` SSLInsecureRenegotiation on|off ``` | | Default: | ``` SSLInsecureRenegotiation off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in httpd 2.2.15 and later, if using OpenSSL 0.9.8m or later | As originally specified, all versions of the SSL and TLS protocols (up to and including TLS/1.2) were vulnerable to a Man-in-the-Middle attack ([CVE-2009-3555](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2009-3555)) during a renegotiation. This vulnerability allowed an attacker to "prefix" a chosen plaintext to the HTTP request as seen by the web server. A protocol extension was developed which fixed this vulnerability if supported by both client and server. If `<mod_ssl>` is linked against OpenSSL version 0.9.8m or later, by default renegotiation is only supported with clients supporting the new protocol extension. If this directive is enabled, renegotiation will be allowed with old (unpatched) clients, albeit insecurely. **Security warning** If this directive is enabled, SSL connections will be vulnerable to the Man-in-the-Middle prefix attack as described in [CVE-2009-3555](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2009-3555). ### Example ``` SSLInsecureRenegotiation on ``` The `SSL_SECURE_RENEG` environment variable can be used from an SSI or CGI script to determine whether secure renegotiation is supported for a given SSL connection. SSLOCSPDefaultResponder Directive --------------------------------- | | | | --- | --- | | Description: | Set the default responder URI for OCSP validation | | Syntax: | ``` SSLOCSPDefaultResponder uri ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This option sets the default OCSP responder to use. If `[SSLOCSPOverrideResponder](#sslocspoverrideresponder)` is not enabled, the URI given will be used only if no responder URI is specified in the certificate being verified. SSLOCSPEnable Directive ----------------------- | | | | --- | --- | | Description: | Enable OCSP validation of the client certificate chain | | Syntax: | ``` SSLOCSPEnable on|leaf|off ``` | | Default: | ``` SSLOCSPEnable off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Mode *leaf* available in httpd 2.4.34 and later | This option enables OCSP validation of the client certificate chain. If this option is enabled, certificates in the client's certificate chain will be validated against an OCSP responder after normal verification (including CRL checks) have taken place. In mode 'leaf', only the client certificate itself will be validated. The OCSP responder used is either extracted from the certificate itself, or derived by configuration; see the `[SSLOCSPDefaultResponder](#sslocspdefaultresponder)` and `[SSLOCSPOverrideResponder](#sslocspoverrideresponder)` directives. ### Example ``` SSLVerifyClient on SSLOCSPEnable on SSLOCSPDefaultResponder "http://responder.example.com:8888/responder" SSLOCSPOverrideResponder on ``` SSLOCSPNoverify Directive ------------------------- | | | | --- | --- | | Description: | skip the OCSP responder certificates verification | | Syntax: | ``` SSLOCSPNoverify on|off ``` | | Default: | ``` SSLOCSPNoverify off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in httpd 2.4.26 and later, if using OpenSSL 0.9.7 or later | Skip the OCSP responder certificates verification, mostly useful when testing an OCSP server. SSLOCSPOverrideResponder Directive ---------------------------------- | | | | --- | --- | | Description: | Force use of the default responder URI for OCSP validation | | Syntax: | ``` SSLOCSPOverrideResponder on|off ``` | | Default: | ``` SSLOCSPOverrideResponder off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This option forces the configured default OCSP responder to be used during OCSP certificate validation, regardless of whether the certificate being validated references an OCSP responder. SSLOCSPProxyURL Directive ------------------------- | | | | --- | --- | | Description: | Proxy URL to use for OCSP requests | | Syntax: | ``` SSLOCSPProxyURL url ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in httpd 2.4.19 and later | This option allows to set the URL of a HTTP proxy that should be used for all queries to OCSP responders. SSLOCSPResponderCertificateFile Directive ----------------------------------------- | | | | --- | --- | | Description: | Set of trusted PEM encoded OCSP responder certificates | | Syntax: | ``` SSLOCSPResponderCertificateFile file ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in httpd 2.4.26 and later, if using OpenSSL 0.9.7 or later | This supplies a list of trusted OCSP responder certificates to be used during OCSP responder certificate validation. The supplied certificates are implicitly trusted without any further validation. This is typically used where the OCSP responder certificate is self signed or omitted from the OCSP response. SSLOCSPResponderTimeout Directive --------------------------------- | | | | --- | --- | | Description: | Timeout for OCSP queries | | Syntax: | ``` SSLOCSPResponderTimeout seconds ``` | | Default: | ``` SSLOCSPResponderTimeout 10 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This option sets the timeout for queries to OCSP responders, when `[SSLOCSPEnable](#sslocspenable)` is turned on. SSLOCSPResponseMaxAge Directive ------------------------------- | | | | --- | --- | | Description: | Maximum allowable age for OCSP responses | | Syntax: | ``` SSLOCSPResponseMaxAge seconds ``` | | Default: | ``` SSLOCSPResponseMaxAge -1 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This option sets the maximum allowable age ("freshness") for OCSP responses. The default value (`-1`) does not enforce a maximum age, which means that OCSP responses are considered valid as long as their `nextUpdate` field is in the future. SSLOCSPResponseTimeSkew Directive --------------------------------- | | | | --- | --- | | Description: | Maximum allowable time skew for OCSP response validation | | Syntax: | ``` SSLOCSPResponseTimeSkew seconds ``` | | Default: | ``` SSLOCSPResponseTimeSkew 300 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This option sets the maximum allowable time skew for OCSP responses (when checking their `thisUpdate` and `nextUpdate` fields). SSLOCSPUseRequestNonce Directive -------------------------------- | | | | --- | --- | | Description: | Use a nonce within OCSP queries | | Syntax: | ``` SSLOCSPUseRequestNonce on|off ``` | | Default: | ``` SSLOCSPUseRequestNonce on ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in httpd 2.4.10 and later | This option determines whether queries to OCSP responders should contain a nonce or not. By default, a query nonce is always used and checked against the response's one. When the responder does not use nonces (e.g. Microsoft OCSP Responder), this option should be turned `off`. SSLOpenSSLConfCmd Directive --------------------------- | | | | --- | --- | | Description: | Configure OpenSSL parameters through its *SSL\_CONF* API | | Syntax: | ``` SSLOpenSSLConfCmd command-name command-value ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in httpd 2.4.8 and later, if using OpenSSL 1.0.2 or later | This directive exposes OpenSSL's *SSL\_CONF* API to mod\_ssl, allowing a flexible configuration of OpenSSL parameters without the need of implementing additional `<mod_ssl>` directives when new features are added to OpenSSL. The set of available `SSLOpenSSLConfCmd` commands depends on the OpenSSL version being used for `<mod_ssl>` (at least version 1.0.2 is required). For a list of supported command names, see the section *Supported configuration file commands* in the [SSL\_CONF\_cmd(3)](http://www.openssl.org/docs/man1.0.2/ssl/SSL_CONF_cmd.html#SUPPORTED-CONFIGURATION-FILE-COMMANDS) manual page for OpenSSL. Some of the `SSLOpenSSLConfCmd` commands can be used as an alternative to existing directives (such as `[SSLCipherSuite](#sslciphersuite)` or `[SSLProtocol](#sslprotocol)`), though it should be noted that the syntax / allowable values for the parameters may sometimes differ. ### Examples ``` SSLOpenSSLConfCmd Options -SessionTicket,ServerPreference SSLOpenSSLConfCmd ECDHParameters brainpoolP256r1 SSLOpenSSLConfCmd ServerInfoFile "/usr/local/apache2/conf/server-info.pem" SSLOpenSSLConfCmd Protocol "-ALL, TLSv1.2" SSLOpenSSLConfCmd SignatureAlgorithms RSA+SHA384:ECDSA+SHA256 ``` SSLOptions Directive -------------------- | | | | --- | --- | | Description: | Configure various SSL engine run-time options | | Syntax: | ``` SSLOptions [+|-]option ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Extension | | Module: | mod\_ssl | This directive can be used to control various run-time options on a per-directory basis. Normally, if multiple `SSLOptions` could apply to a directory, then the most specific one is taken completely; the options are not merged. However if *all* the options on the `SSLOptions` directive are preceded by a plus (`+`) or minus (`-`) symbol, the options are merged. Any options preceded by a `+` are added to the options currently in force, and any options preceded by a `-` are removed from the options currently in force. The available *option*s are: * `StdEnvVars` When this option is enabled, the standard set of SSL related CGI/SSI environment variables are created. This per default is disabled for performance reasons, because the information extraction step is a rather expensive operation. So one usually enables this option for CGI and SSI requests only. * `ExportCertData` When this option is enabled, additional CGI/SSI environment variables are created: `SSL_SERVER_CERT`, `SSL_CLIENT_CERT` and `SSL_CLIENT_CERT_CHAIN_`*n* (with *n* = 0,1,2,..). These contain the PEM-encoded X.509 Certificates of server and client for the current HTTPS connection and can be used by CGI scripts for deeper Certificate checking. Additionally all other certificates of the client certificate chain are provided, too. This bloats up the environment a little bit which is why you have to use this option to enable it on demand. * `FakeBasicAuth` When this option is enabled, the Subject Distinguished Name (DN) of the Client X509 Certificate is translated into a HTTP Basic Authorization username. This means that the standard Apache authentication methods can be used for access control. The user name is just the Subject of the Client's X509 Certificate (can be determined by running OpenSSL's `openssl x509` command: `openssl x509 -noout -subject -in`*certificate*`.crt`). Note that no password is obtained from the user. Every entry in the user file needs this password: ```xxj31ZMTZzkVA`'', which is the DES-encrypted version of the word ``password`''. Those who live under MD5-based encryption (for instance under FreeBSD or BSD/OS, etc.) should use the following MD5 hash of the same word: ```$1$OXLyS...$Owx8s2/m9/gfkcRVXzgoE/`''. Note that the `[AuthBasicFake](mod_auth_basic#authbasicfake)` directive within `<mod_auth_basic>` can be used as a more general mechanism for faking basic authentication, giving control over the structure of both the username and password. * `StrictRequire` This *forces* forbidden access when `[SSLRequireSSL](#sslrequiressl)` or `[SSLRequire](#sslrequire)` successfully decided that access should be forbidden. Usually the default is that in the case where a ```Satisfy any`'' directive is used, and other access restrictions are passed, denial of access due to `SSLRequireSSL` or `SSLRequire` is overridden (because that's how the Apache `Satisfy` mechanism should work.) But for strict access restriction you can use `SSLRequireSSL` and/or `SSLRequire` in combination with an ```SSLOptions +StrictRequire`''. Then an additional ```Satisfy Any`'' has no chance once mod\_ssl has decided to deny access. * `OptRenegotiate` This enables optimized SSL connection renegotiation handling when SSL directives are used in per-directory context. By default a strict scheme is enabled where *every* per-directory reconfiguration of SSL parameters causes a *full* SSL renegotiation handshake. When this option is used mod\_ssl tries to avoid unnecessary handshakes by doing more granular (but still safe) parameter checks. Nevertheless these granular checks sometimes may not be what the user expects, so enable this on a per-directory basis only, please. * `LegacyDNStringFormat` This option influences how values of the `SSL_{CLIENT,SERVER}_{I,S}_DN` variables are formatted. Since version 2.3.11, Apache HTTPD uses a RFC 2253 compatible format by default. This uses commas as delimiters between the attributes, allows the use of non-ASCII characters (which are converted to UTF8), escapes various special characters with backslashes, and sorts the attributes with the "C" attribute last. If `LegacyDNStringFormat` is set, the old format will be used which sorts the "C" attribute first, uses slashes as separators, and does not handle non-ASCII and special characters in any consistent way. ### Example ``` SSLOptions +FakeBasicAuth -StrictRequire <Files ~ "\.(cgi|shtml)$"> SSLOptions +StdEnvVars -ExportCertData </Files> ``` SSLPassPhraseDialog Directive ----------------------------- | | | | --- | --- | | Description: | Type of pass phrase dialog for encrypted private keys | | Syntax: | ``` SSLPassPhraseDialog type ``` | | Default: | ``` SSLPassPhraseDialog builtin ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ssl | When Apache starts up it has to read the various Certificate (see `[SSLCertificateFile](#sslcertificatefile)`) and Private Key (see `[SSLCertificateKeyFile](#sslcertificatekeyfile)`) files of the SSL-enabled virtual servers. Because for security reasons the Private Key files are usually encrypted, mod\_ssl needs to query the administrator for a Pass Phrase in order to decrypt those files. This query can be done in two ways which can be configured by *type*: * `builtin` This is the default where an interactive terminal dialog occurs at startup time just before Apache detaches from the terminal. Here the administrator has to manually enter the Pass Phrase for each encrypted Private Key file. Because a lot of SSL-enabled virtual hosts can be configured, the following reuse-scheme is used to minimize the dialog: When a Private Key file is encrypted, all known Pass Phrases (at the beginning there are none, of course) are tried. If one of those known Pass Phrases succeeds no dialog pops up for this particular Private Key file. If none succeeded, another Pass Phrase is queried on the terminal and remembered for the next round (where it perhaps can be reused). This scheme allows mod\_ssl to be maximally flexible (because for N encrypted Private Key files you *can* use N different Pass Phrases - but then you have to enter all of them, of course) while minimizing the terminal dialog (i.e. when you use a single Pass Phrase for all N Private Key files this Pass Phrase is queried only once). * `|/path/to/program [args...]` This mode allows an external program to be used which acts as a pipe to a particular input device; the program is sent the standard prompt text used for the `builtin` mode on `stdin`, and is expected to write password strings on `stdout`. If several passwords are needed (or an incorrect password is entered), additional prompt text will be written subsequent to the first password being returned, and more passwords must then be written back. * `exec:/path/to/program` Here an external program is configured which is called at startup for each encrypted Private Key file. It is called with two arguments (the first is of the form ```servername:portnumber`'', the second is either ```RSA`'', ```DSA`'', ```ECC`'' or an integer index starting at 3 if more than three keys are configured), which indicate for which server and algorithm it has to print the corresponding Pass Phrase to `stdout`. In versions 2.4.8 (unreleased) and 2.4.9, it is called with one argument, a string of the form ```servername:portnumber:index`'' (with `index` being a zero-based integer number), which indicate the server, TCP port and certificate number. The intent is that this external program first runs security checks to make sure that the system is not compromised by an attacker, and only when these checks were passed successfully it provides the Pass Phrase. Both these security checks, and the way the Pass Phrase is determined, can be as complex as you like. Mod\_ssl just defines the interface: an executable program which provides the Pass Phrase on `stdout`. Nothing more or less! So, if you're really paranoid about security, here is your interface. Anything else has to be left as an exercise to the administrator, because local security requirements are so different. The reuse-algorithm above is used here, too. In other words: The external program is called only once per unique Pass Phrase. ### Example ``` SSLPassPhraseDialog "exec:/usr/local/apache/sbin/pp-filter" ``` SSLProtocol Directive --------------------- | | | | --- | --- | | Description: | Configure usable SSL/TLS protocol versions | | Syntax: | ``` SSLProtocol [+|-]protocol ... ``` | | Default: | ``` SSLProtocol all -SSLv3 (up to 2.4.16: all) ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | This directive can be used to control which versions of the SSL/TLS protocol will be accepted in new connections. The available (case-insensitive) *protocol*s are: * `SSLv3` This is the Secure Sockets Layer (SSL) protocol, version 3.0, from the Netscape Corporation. It is the successor to SSLv2 and the predecessor to TLSv1, but is deprecated in [RFC 7568](http://www.ietf.org/rfc/rfc7568.txt). * `TLSv1` This is the Transport Layer Security (TLS) protocol, version 1.0. It is the successor to SSLv3 and is defined in [RFC 2246](http://www.ietf.org/rfc/rfc2246.txt). It is supported by nearly every client. * `TLSv1.1` (when using OpenSSL 1.0.1 and later) A revision of the TLS 1.0 protocol, as defined in [RFC 4346](http://www.ietf.org/rfc/rfc4346.txt). * `TLSv1.2` (when using OpenSSL 1.0.1 and later) A revision of the TLS 1.1 protocol, as defined in [RFC 5246](http://www.ietf.org/rfc/rfc5246.txt). * `TLSv1.3` (when using OpenSSL 1.1.1 and later) A new version of the TLS protocol, as defined in [RFC 8446](http://www.ietf.org/rfc/rfc8446.txt). * `all` This is a shortcut for ```+SSLv3 +TLSv1`'' or - when using OpenSSL 1.0.1 and later - ```+SSLv3 +TLSv1 +TLSv1.1 +TLSv1.2`'', respectively (except for OpenSSL versions compiled with the ``no-ssl3'' configuration option, where `all` does not include `+SSLv3`). ### Example ``` SSLProtocol TLSv1 ``` **`SSLProtocol` for name-based virtual hosts** Before OpenSSL 1.1.1, even though the Server Name Indication (SNI) allowed to determine the targeted virtual host early in the TLS handshake, it was not possible to switch the TLS protocol version of the connection at this point, and thus the `SSLProtocol` negotiated was always based off the one of the *base virtual host* (first virtual host declared on the listening `IP:port` of the connection). Beginning with Apache HTTP server version 2.4.42, when built/linked against OpenSSL 1.1.1 or later, and when the SNI is provided by the client in the TLS handshake, the `SSLProtocol` of each (name-based) virtual host can and will be honored. For compatibility with previous versions, if no `SSLProtocol` is configured in a name-based virtual host, the one from the base virtual host still applies, **unless** `SSLProtocol` is configured globally in which case the global value applies (this latter exception is more sensible than compatible, though). SSLProxyCACertificateFile Directive ----------------------------------- | | | | --- | --- | | Description: | File of concatenated PEM-encoded CA Certificates for Remote Server Auth | | Syntax: | ``` SSLProxyCACertificateFile file-path ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive sets the *all-in-one* file where you can assemble the Certificates of Certification Authorities (CA) whose *remote servers* you deal with. These are used for Remote Server Authentication. Such a file is simply the concatenation of the various PEM-encoded Certificate files, in order of preference. This can be used alternatively and/or additionally to `[SSLProxyCACertificatePath](#sslproxycacertificatepath)`. ### Example ``` SSLProxyCACertificateFile "/usr/local/apache2/conf/ssl.crt/ca-bundle-remote-server.crt" ``` SSLProxyCACertificatePath Directive ----------------------------------- | | | | --- | --- | | Description: | Directory of PEM-encoded CA Certificates for Remote Server Auth | | Syntax: | ``` SSLProxyCACertificatePath directory-path ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive sets the directory where you keep the Certificates of Certification Authorities (CAs) whose remote servers you deal with. These are used to verify the remote server certificate on Remote Server Authentication. The files in this directory have to be PEM-encoded and are accessed through hash filenames. So usually you can't just place the Certificate files there: you also have to create symbolic links named *hash-value*`.N`. And you should always make sure this directory contains the appropriate symbolic links. ### Example ``` SSLProxyCACertificatePath "/usr/local/apache2/conf/ssl.crt/" ``` SSLProxyCARevocationCheck Directive ----------------------------------- | | | | --- | --- | | Description: | Enable CRL-based revocation checking for Remote Server Auth | | Syntax: | ``` SSLProxyCARevocationCheck chain|leaf|none ``` | | Default: | ``` SSLProxyCARevocationCheck none ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | Enables certificate revocation list (CRL) checking for the *remote servers* you deal with. At least one of `[SSLProxyCARevocationFile](#sslproxycarevocationfile)` or `[SSLProxyCARevocationPath](#sslproxycarevocationpath)` must be configured. When set to `chain` (recommended setting), CRL checks are applied to all certificates in the chain, while setting it to `leaf` limits the checks to the end-entity cert. **When set to `chain` or `leaf`, CRLs *must* be available for successful validation** Prior to version 2.3.15, CRL checking in mod\_ssl also succeeded when no CRL(s) were found in any of the locations configured with `[SSLProxyCARevocationFile](#sslproxycarevocationfile)` or `[SSLProxyCARevocationPath](#sslproxycarevocationpath)`. With the introduction of this directive, the behavior has been changed: when checking is enabled, CRLs *must* be present for the validation to succeed - otherwise it will fail with an `"unable to get certificate CRL"` error. ### Example ``` SSLProxyCARevocationCheck chain ``` SSLProxyCARevocationFile Directive ---------------------------------- | | | | --- | --- | | Description: | File of concatenated PEM-encoded CA CRLs for Remote Server Auth | | Syntax: | ``` SSLProxyCARevocationFile file-path ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive sets the *all-in-one* file where you can assemble the Certificate Revocation Lists (CRL) of Certification Authorities (CA) whose *remote servers* you deal with. These are used for Remote Server Authentication. Such a file is simply the concatenation of the various PEM-encoded CRL files, in order of preference. This can be used alternatively and/or additionally to `[SSLProxyCARevocationPath](#sslproxycarevocationpath)`. ### Example ``` SSLProxyCARevocationFile "/usr/local/apache2/conf/ssl.crl/ca-bundle-remote-server.crl" ``` SSLProxyCARevocationPath Directive ---------------------------------- | | | | --- | --- | | Description: | Directory of PEM-encoded CA CRLs for Remote Server Auth | | Syntax: | ``` SSLProxyCARevocationPath directory-path ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive sets the directory where you keep the Certificate Revocation Lists (CRL) of Certification Authorities (CAs) whose remote servers you deal with. These are used to revoke the remote server certificate on Remote Server Authentication. The files in this directory have to be PEM-encoded and are accessed through hash filenames. So usually you have not only to place the CRL files there. Additionally you have to create symbolic links named *hash-value*`.rN`. And you should always make sure this directory contains the appropriate symbolic links. ### Example ``` SSLProxyCARevocationPath "/usr/local/apache2/conf/ssl.crl/" ``` SSLProxyCheckPeerCN Directive ----------------------------- | | | | --- | --- | | Description: | Whether to check the remote server certificate's CN field | | Syntax: | ``` SSLProxyCheckPeerCN on|off ``` | | Default: | ``` SSLProxyCheckPeerCN on ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive sets whether the remote server certificate's CN field is compared against the hostname of the request URL. If both are not equal a 502 status code (Bad Gateway) is sent. `SSLProxyCheckPeerCN` is superseded by `[SSLProxyCheckPeerName](#sslproxycheckpeername)` in release 2.4.5 and later. In all releases 2.4.5 through 2.4.20, setting `SSLProxyCheckPeerName off` was sufficient to enable this behavior (as the `SSLProxyCheckPeerCN` default was `on`.) In these releases, both directives must be set to `off` to completely avoid remote server certificate name validation. Many users reported this to be very confusing. As of release 2.4.21, all configurations which enable either one of the `SSLProxyCheckPeerName` or `SSLProxyCheckPeerCN` options will use the new `[SSLProxyCheckPeerName](#sslproxycheckpeername)` behavior, and all configurations which disable either one of the `SSLProxyCheckPeerName` or `SSLProxyCheckPeerCN` options will suppress all remote server certificate name validation. Only the following configuration will trigger the legacy certificate CN comparison in 2.4.21 and later releases; ### Example ``` SSLProxyCheckPeerCN on SSLProxyCheckPeerName off ``` SSLProxyCheckPeerExpire Directive --------------------------------- | | | | --- | --- | | Description: | Whether to check if remote server certificate is expired | | Syntax: | ``` SSLProxyCheckPeerExpire on|off ``` | | Default: | ``` SSLProxyCheckPeerExpire on ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive sets whether it is checked if the remote server certificate is expired or not. If the check fails a 502 status code (Bad Gateway) is sent. ### Example ``` SSLProxyCheckPeerExpire on ``` SSLProxyCheckPeerName Directive ------------------------------- | | | | --- | --- | | Description: | Configure host name checking for remote server certificates | | Syntax: | ``` SSLProxyCheckPeerName on|off ``` | | Default: | ``` SSLProxyCheckPeerName on ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Apache HTTP Server 2.4.5 and later The proxy section context is allowed in httpd 2.4.30 and later | This directive configures host name checking for server certificates when mod\_ssl is acting as an SSL client. The check will succeed if the host name from the request URI matches one of the CN attribute(s) of the certificate's subject, or matches the subjectAltName extension. If the check fails, the SSL request is aborted and a 502 status code (Bad Gateway) is returned. Wildcard matching is supported for specific cases: an subjectAltName entry of type dNSName, or CN attributes starting with `*.` will match with any host name of the same number of name elements and the same suffix. E.g. `*.example.org` will match `foo.example.org`, but will not match `foo.bar.example.org`, because the number of elements in the respective host names differs. This feature was introduced in 2.4.5 and superseded the behavior of the `[SSLProxyCheckPeerCN](#sslproxycheckpeercn)` directive, which only tested the exact value in the first CN attribute against the host name. However, many users were confused by the behavior of using these directives individually, so the mutual behavior of `SSLProxyCheckPeerName` and `SSLProxyCheckPeerCN` directives were improved in release 2.4.21. See the `[SSLProxyCheckPeerCN](#sslproxycheckpeercn)` directive description for the original behavior and details of these improvements. SSLProxyCipherSuite Directive ----------------------------- | | | | --- | --- | | Description: | Cipher Suite available for negotiation in SSL proxy handshake | | Syntax: | ``` SSLProxyCipherSuite [protocol] cipher-spec ``` | | Default: | ``` SSLProxyCipherSuite ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+EXP ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | Equivalent to `[SSLCipherSuite](#sslciphersuite)`, but for the proxy connection. Please refer to `[SSLCipherSuite](#sslciphersuite)` for additional information. SSLProxyEngine Directive ------------------------ | | | | --- | --- | | Description: | SSL Proxy Engine Operation Switch | | Syntax: | ``` SSLProxyEngine on|off ``` | | Default: | ``` SSLProxyEngine off ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive toggles the usage of the SSL/TLS Protocol Engine for proxy. This is usually used inside a `[<VirtualHost>](core#virtualhost)` section to enable SSL/TLS for proxy usage in a particular virtual host. By default the SSL/TLS Protocol Engine is disabled for proxy both for the main server and all configured virtual hosts. Note that the `SSLProxyEngine` directive should not, in general, be included in a virtual host that will be acting as a forward proxy (using `[<Proxy>](mod_proxy#proxy)` or `[ProxyRequests](mod_proxy#proxyrequests)` directives). `SSLProxyEngine` is not required to enable a forward proxy server to proxy SSL/TLS requests. ### Example ``` <VirtualHost _default_:443> SSLProxyEngine on #... </VirtualHost> ``` SSLProxyMachineCertificateChainFile Directive --------------------------------------------- | | | | --- | --- | | Description: | File of concatenated PEM-encoded CA certificates to be used by the proxy for choosing a certificate | | Syntax: | ``` SSLProxyMachineCertificateChainFile filename ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive sets the all-in-one file where you keep the certificate chain for all of the client certs in use. This directive will be needed if the remote server presents a list of CA certificates that are not direct signers of one of the configured client certificates. This referenced file is simply the concatenation of the various PEM-encoded certificate files. Upon startup, each client certificate configured will be examined and a chain of trust will be constructed. **Security warning** If this directive is enabled, all of the certificates in the file will be trusted as if they were also in `[SSLProxyCACertificateFile](#sslproxycacertificatefile)`. ### Example ``` SSLProxyMachineCertificateChainFile "/usr/local/apache2/conf/ssl.crt/proxyCA.pem" ``` SSLProxyMachineCertificateFile Directive ---------------------------------------- | | | | --- | --- | | Description: | File of concatenated PEM-encoded client certificates and keys to be used by the proxy | | Syntax: | ``` SSLProxyMachineCertificateFile filename ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive sets the all-in-one file where you keep the certificates and keys used for authentication of the proxy server to remote servers. This referenced file is simply the concatenation of the various PEM-encoded certificate files. Use this directive alternatively or additionally to `SSLProxyMachineCertificatePath`. The referenced file can contain any number of pairs of client certificate and associated private key. Each pair can be specified in either (certificate, key) or (key, certificate) order. If the file includes any non-leaf certificate, or any unmatched key and certificate pair, a configuration error will be issued at startup. When challenged to provide a client certificate by a remote server, the server should provide a list of *acceptable certificate authority names* in the challenge. If such a list is *not* provided, `<mod_ssl>` will use the first configured client cert/key. If a list of CA names *is* provided, `<mod_ssl>` will iterate through that list, and attempt to find a configured client cert which was issued either directly by that CA, or indirectly via any number of intermediary CA certificates. The chain of intermediate CA certificates can be built from those configured with `[SSLProxyMachineCertificateChainFile](#sslproxymachinecertificatechainfile)`. The first configured matching certificate will then be supplied in response to the challenge. If the list of CA names *is* provided by the remote server, and *no* matching client certificate can be found, no client certificate will be provided by `<mod_ssl>`, which will likely fail the SSL/TLS handshake (depending on the remote server configuration). Currently there is no support for encrypted private keys Only keys encoded in PKCS1 RSA, DSA or EC format are supported. Keys encoded in PKCS8 format, ie. starting with "`-----BEGIN PRIVATE KEY-----`", must be converted, eg. using "`openssl rsa -in private-pkcs8.pem -outform pem`". ### Example ``` SSLProxyMachineCertificateFile "/usr/local/apache2/conf/ssl.crt/proxy.pem" ``` SSLProxyMachineCertificatePath Directive ---------------------------------------- | | | | --- | --- | | Description: | Directory of PEM-encoded client certificates and keys to be used by the proxy | | Syntax: | ``` SSLProxyMachineCertificatePath directory ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive sets the directory where you keep the client certificates and keys used for authentication of the proxy server to remote servers. mod\_ssl will attempt to load every file inside the specified directory as if it was configured individually with `[SSLProxyMachineCertificateFile](#sslproxymachinecertificatefile)`. Currently there is no support for encrypted private keys Only keys encoded in PKCS1 RSA, DSA or EC format are supported. Keys encoded in PKCS8 format, ie. starting with "`-----BEGIN PRIVATE KEY-----`", must be converted, eg. using "`openssl rsa -in private-pkcs8.pem -outform pem`". ### Example ``` SSLProxyMachineCertificatePath "/usr/local/apache2/conf/proxy.crt/" ``` SSLProxyProtocol Directive -------------------------- | | | | --- | --- | | Description: | Configure usable SSL protocol flavors for proxy usage | | Syntax: | ``` SSLProxyProtocol [+|-]protocol ... ``` | | Default: | ``` SSLProxyProtocol all -SSLv3 (up to 2.4.16: all) ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive can be used to control the SSL protocol flavors mod\_ssl should use when establishing its server environment for proxy . It will only connect to servers using one of the provided protocols. Please refer to `[SSLProtocol](#sslprotocol)` for additional information. SSLProxyVerify Directive ------------------------ | | | | --- | --- | | Description: | Type of remote server Certificate verification | | Syntax: | ``` SSLProxyVerify level ``` | | Default: | ``` SSLProxyVerify none ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | When a proxy is configured to forward requests to a remote SSL server, this directive can be used to configure certificate verification of the remote server. The following levels are available for *level*: * **none**: no remote server Certificate is required at all * **optional**: the remote server *may* present a valid Certificate * **require**: the remote server *has to* present a valid Certificate * **optional\_no\_ca**: the remote server may present a valid Certificate but it need not to be (successfully) verifiable. In practice only levels **none** and **require** are really interesting, because level **optional** doesn't work with all servers and level **optional\_no\_ca** is actually against the idea of authentication (but can be used to establish SSL test pages, etc.) ### Example ``` SSLProxyVerify require ``` SSLProxyVerifyDepth Directive ----------------------------- | | | | --- | --- | | Description: | Maximum depth of CA Certificates in Remote Server Certificate verification | | Syntax: | ``` SSLProxyVerifyDepth number ``` | | Default: | ``` SSLProxyVerifyDepth 1 ``` | | Context: | server config, virtual host, proxy section | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | The proxy section context is allowed in httpd 2.4.30 and later | This directive sets how deeply mod\_ssl should verify before deciding that the remote server does not have a valid certificate. The depth actually is the maximum number of intermediate certificate issuers, i.e. the number of CA certificates which are max allowed to be followed while verifying the remote server certificate. A depth of 0 means that self-signed remote server certificates are accepted only, the default depth of 1 means the remote server certificate can be self-signed or has to be signed by a CA which is directly known to the server (i.e. the CA's certificate is under `[SSLProxyCACertificatePath](#sslproxycacertificatepath)`), etc. ### Example ``` SSLProxyVerifyDepth 10 ``` SSLRandomSeed Directive ----------------------- | | | | --- | --- | | Description: | Pseudo Random Number Generator (PRNG) seeding source | | Syntax: | ``` SSLRandomSeed context source [bytes] ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ssl | This configures one or more sources for seeding the Pseudo Random Number Generator (PRNG) in OpenSSL at startup time (*context* is `startup`) and/or just before a new SSL connection is established (*context* is `connect`). This directive can only be used in the global server context because the PRNG is a global facility. The following *source* variants are available: * `builtin` This is the always available builtin seeding source. Its usage consumes minimum CPU cycles under runtime and hence can be always used without drawbacks. The source used for seeding the PRNG contains of the current time, the current process id and a randomly chosen 128 bytes extract of the stack. The drawback is that this is not really a strong source and at startup time (where the scoreboard is still not available) this source just produces a few bytes of entropy. So you should always, at least for the startup, use an additional seeding source. * `file:/path/to/source` This variant uses an external file `/path/to/source` as the source for seeding the PRNG. When *bytes* is specified, only the first *bytes* number of bytes of the file form the entropy (and *bytes* is given to `/path/to/source` as the first argument). When *bytes* is not specified the whole file forms the entropy (and `0` is given to `/path/to/source` as the first argument). Use this especially at startup time, for instance with an available `/dev/random` and/or `/dev/urandom` devices (which usually exist on modern Unix derivatives like FreeBSD and Linux). *But be careful*: Usually `/dev/random` provides only as much entropy data as it actually has, i.e. when you request 512 bytes of entropy, but the device currently has only 100 bytes available two things can happen: On some platforms you receive only the 100 bytes while on other platforms the read blocks until enough bytes are available (which can take a long time). Here using an existing `/dev/urandom` is better, because it never blocks and actually gives the amount of requested data. The drawback is just that the quality of the received data may not be the best. * `exec:/path/to/program` This variant uses an external executable `/path/to/program` as the source for seeding the PRNG. When *bytes* is specified, only the first *bytes* number of bytes of its `stdout` contents form the entropy. When *bytes* is not specified, the entirety of the data produced on `stdout` form the entropy. Use this only at startup time when you need a very strong seeding with the help of an external program (for instance as in the example above with the `truerand` utility you can find in the mod\_ssl distribution which is based on the AT&T *truerand* library). Using this in the connection context slows down the server too dramatically, of course. So usually you should avoid using external programs in that context. * `egd:/path/to/egd-socket` (Unix only) This variant uses the Unix domain socket of the external Entropy Gathering Daemon (EGD) (see [http://www.lothar.com/tech /crypto/](http://www.lothar.com/tech/crypto/)) to seed the PRNG. Use this if no random device exists on your platform. ### Example ``` SSLRandomSeed startup builtin SSLRandomSeed startup "file:/dev/random" SSLRandomSeed startup "file:/dev/urandom" 1024 SSLRandomSeed startup "exec:/usr/local/bin/truerand" 16 SSLRandomSeed connect builtin SSLRandomSeed connect "file:/dev/random" SSLRandomSeed connect "file:/dev/urandom" 1024 ``` SSLRenegBufferSize Directive ---------------------------- | | | | --- | --- | | Description: | Set the size for the SSL renegotiation buffer | | Syntax: | ``` SSLRenegBufferSize bytes ``` | | Default: | ``` SSLRenegBufferSize 131072 ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_ssl | If an SSL renegotiation is required in per-location context, for example, any use of `[SSLVerifyClient](#sslverifyclient)` in a Directory or Location block, then `<mod_ssl>` must buffer any HTTP request body into memory until the new SSL handshake can be performed. This directive can be used to set the amount of memory that will be used for this buffer. Note that in many configurations, the client sending the request body will be untrusted so a denial of service attack by consumption of memory must be considered when changing this configuration setting. ### Example ``` SSLRenegBufferSize 262144 ``` SSLRequire Directive -------------------- | | | | --- | --- | | Description: | Allow access only when an arbitrarily complex boolean expression is true | | Syntax: | ``` SSLRequire expression ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_ssl | **SSLRequire is deprecated** `SSLRequire` is deprecated and should in general be replaced by [Require expr](mod_authz_core#reqexpr). The so called [ap\_expr](../expr) syntax of `Require expr` is a superset of the syntax of `SSLRequire`, with the following exception: In `SSLRequire`, the comparison operators `<`, `<=`, ... are completely equivalent to the operators `lt`, `le`, ... and work in a somewhat peculiar way that first compares the length of two strings and then the lexical order. On the other hand, [ap\_expr](../expr) has two sets of comparison operators: The operators `<`, `<=`, ... do lexical string comparison, while the operators `-lt`, `-le`, ... do integer comparison. For the latter, there are also aliases without the leading dashes: `lt`, `le`, ... This directive specifies a general access requirement which has to be fulfilled in order to allow access. It is a very powerful directive because the requirement specification is an arbitrarily complex boolean expression containing any number of access checks. The *expression* must match the following syntax (given as a BNF grammar notation): > > ``` > expr ::= "**true**" | "**false**" > | "**!**" expr > | expr "**&&**" expr > | expr "**||**" expr > | "**(**" expr "**)**" > | comp > > comp ::= word "**==**" word | word "**eq**" word > | word "**!=**" word | word "**ne**" word > | word "**<**" word | word "**lt**" word > | word "**<=**" word | word "**le**" word > | word "**>**" word | word "**gt**" word > | word "**>=**" word | word "**ge**" word > | word "**in**" "**{**" wordlist "**}**" > | word "**in**" "**PeerExtList(**" word "**)**" > | word "**=~**" regex > | word "**!~**" regex > > wordlist ::= word > | wordlist "**,**" word > > word ::= digit > | cstring > | variable > | function > > digit ::= [0-9]+ > cstring ::= "..." > variable ::= "**%{**" varname "**}**" > function ::= funcname "**(**" funcargs "**)**" > ``` > For `varname` any of the variables described in [Environment Variables](#envvars) can be used. For `funcname` the available functions are listed in the [ap\_expr documentation](../expr#functions). The *expression* is parsed into an internal machine representation when the configuration is loaded, and then evaluated during request processing. In .htaccess context, the *expression* is both parsed and executed each time the .htaccess file is encountered during request processing. ### Example ``` SSLRequire ( %{SSL_CIPHER} !~ m/^(EXP|NULL)-/ \ and %{SSL_CLIENT_S_DN_O} eq "Snake Oil, Ltd." \ and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"} \ and %{TIME_WDAY} -ge 1 and %{TIME_WDAY} -le 5 \ and %{TIME_HOUR} -ge 8 and %{TIME_HOUR} -le 20 ) \ or %{REMOTE_ADDR} =~ m/^192\.76\.162\.[0-9]+$/ ``` The `PeerExtList(*object-ID*)` function expects to find zero or more instances of the X.509 certificate extension identified by the given *object ID* (OID) in the client certificate. The expression evaluates to true if the left-hand side string matches exactly against the value of an extension identified with this OID. (If multiple extensions with the same OID are present, at least one extension must match). ### Example ``` SSLRequire "foobar" in PeerExtList("1.2.3.4.5.6") ``` **Notes on the PeerExtList function** * The object ID can be specified either as a descriptive name recognized by the SSL library, such as `"nsComment"`, or as a numeric OID, such as `"1.2.3.4.5.6"`. * Expressions with types known to the SSL library are rendered to a string before comparison. For an extension with a type not recognized by the SSL library, mod\_ssl will parse the value if it is one of the primitive ASN.1 types UTF8String, IA5String, VisibleString, or BMPString. For an extension of one of these types, the string value will be converted to UTF-8 if necessary, then compared against the left-hand-side expression. ### See also * [Environment Variables in Apache HTTP Server](../env), for additional examples. * [Require expr](mod_authz_core#reqexpr) * [Generic expression syntax in Apache HTTP Server](../expr) SSLRequireSSL Directive ----------------------- | | | | --- | --- | | Description: | Deny access when SSL is not used for the HTTP request | | Syntax: | `SSLRequireSSL` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_ssl | This directive forbids access unless HTTP over SSL (i.e. HTTPS) is enabled for the current connection. This is very handy inside the SSL-enabled virtual host or directories for defending against configuration errors that expose stuff that should be protected. When this directive is present all requests are denied which are not using SSL. ### Example ``` SSLRequireSSL ``` SSLSessionCache Directive ------------------------- | | | | --- | --- | | Description: | Type of the global/inter-process SSL Session Cache | | Syntax: | ``` SSLSessionCache type ``` | | Default: | ``` SSLSessionCache none ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ssl | This configures the storage type of the global/inter-process SSL Session Cache. This cache is an optional facility which speeds up parallel request processing. For requests to the same server process (via HTTP keep-alive), OpenSSL already caches the SSL session information locally. But because modern clients request inlined images and other data via parallel requests (usually up to four parallel requests are common) those requests are served by *different* pre-forked server processes. Here an inter-process cache helps to avoid unnecessary session handshakes. The following five storage *type*s are currently supported: * `none` This disables the global/inter-process Session Cache. This will incur a noticeable speed penalty and may cause problems if using certain browsers, particularly if client certificates are enabled. This setting is not recommended. * `nonenotnull` This disables any global/inter-process Session Cache. However it does force OpenSSL to send a non-null session ID to accommodate buggy clients that require one. * `dbm:/path/to/datafile` This makes use of a DBM hashfile on the local disk to synchronize the local OpenSSL memory caches of the server processes. This session cache may suffer reliability issues under high load. To use this, ensure that `<mod_socache_dbm>` is loaded. * `shmcb:/path/to/datafile`[`(`*size*`)`] This makes use of a high-performance cyclic buffer (approx. *size* bytes in size) inside a shared memory segment in RAM (established via `/path/to/datafile`) to synchronize the local OpenSSL memory caches of the server processes. This is the recommended session cache. To use this, ensure that `<mod_socache_shmcb>` is loaded. * `dc:UNIX:/path/to/socket` This makes use of the [distcache](http://distcache.sourceforge.net/) distributed session caching libraries. The argument should specify the location of the server or proxy to be used using the distcache address syntax; for example, `UNIX:/path/to/socket` specifies a UNIX domain socket (typically a local dc\_client proxy); `IP:server.example.com:9001` specifies an IP address. To use this, ensure that `<mod_socache_dc>` is loaded. ### Examples ``` SSLSessionCache "dbm:/usr/local/apache/logs/ssl_gcache_data" SSLSessionCache "shmcb:/usr/local/apache/logs/ssl_gcache_data(512000)" ``` The `ssl-cache` mutex is used to serialize access to the session cache to prevent corruption. This mutex can be configured using the `[Mutex](core#mutex)` directive. SSLSessionCacheTimeout Directive -------------------------------- | | | | --- | --- | | Description: | Number of seconds before an SSL session expires in the Session Cache | | Syntax: | ``` SSLSessionCacheTimeout seconds ``` | | Default: | ``` SSLSessionCacheTimeout 300 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Applies also to RFC 5077 TLS session resumption in Apache 2.4.10 and later | This directive sets the timeout in seconds for the information stored in the global/inter-process SSL Session Cache, the OpenSSL internal memory cache and for sessions resumed by TLS session resumption (RFC 5077). It can be set as low as 15 for testing, but should be set to higher values like 300 in real life. ### Example ``` SSLSessionCacheTimeout 600 ``` SSLSessionTicketKeyFile Directive --------------------------------- | | | | --- | --- | | Description: | Persistent encryption/decryption key for TLS session tickets | | Syntax: | ``` SSLSessionTicketKeyFile file-path ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in httpd 2.4.0 and later, if using OpenSSL 0.9.8h or later | Optionally configures a secret key for encrypting and decrypting TLS session tickets, as defined in [RFC 5077](http://www.ietf.org/rfc/rfc5077.txt). Primarily suitable for clustered environments where TLS sessions information should be shared between multiple nodes. For single-instance httpd setups, it is recommended to *not* configure a ticket key file, but to rely on (random) keys generated by mod\_ssl at startup, instead. The ticket key file must contain 48 bytes of random data, preferably created from a high-entropy source. On a Unix-based system, a ticket key file can be created as follows: ``` dd if=/dev/random of=/path/to/file.tkey bs=1 count=48 ``` Ticket keys should be rotated (replaced) on a frequent basis, as this is the only way to invalidate an existing session ticket - OpenSSL currently doesn't allow to specify a limit for ticket lifetimes. A new ticket key only gets used after restarting the web server. All existing session tickets become invalid after a restart. The ticket key file contains sensitive keying material and should be protected with file permissions similar to those used for `[SSLCertificateKeyFile](#sslcertificatekeyfile)`. SSLSessionTickets Directive --------------------------- | | | | --- | --- | | Description: | Enable or disable use of TLS session tickets | | Syntax: | ``` SSLSessionTickets on|off ``` | | Default: | ``` SSLSessionTickets on ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in httpd 2.4.11 and later, if using OpenSSL 0.9.8f or later. | This directive allows to enable or disable the use of TLS session tickets (RFC 5077). TLS session tickets are enabled by default. Using them without restarting the web server with an appropriate frequency (e.g. daily) compromises perfect forward secrecy. SSLSRPUnknownUserSeed Directive ------------------------------- | | | | --- | --- | | Description: | SRP unknown user seed | | Syntax: | ``` SSLSRPUnknownUserSeed secret-string ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in httpd 2.4.4 and later, if using OpenSSL 1.0.1 or later | This directive sets the seed used to fake SRP user parameters for unknown users, to avoid leaking whether a given user exists. Specify a secret string. If this directive is not used, then Apache will return the UNKNOWN\_PSK\_IDENTITY alert to clients who specify an unknown username. ### Example ``` SSLSRPUnknownUserSeed "secret" ``` SSLSRPVerifierFile Directive ---------------------------- | | | | --- | --- | | Description: | Path to SRP verifier file | | Syntax: | ``` SSLSRPVerifierFile file-path ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in httpd 2.4.4 and later, if using OpenSSL 1.0.1 or later | This directive enables TLS-SRP and sets the path to the OpenSSL SRP (Secure Remote Password) verifier file containing TLS-SRP usernames, verifiers, salts, and group parameters. ### Example ``` SSLSRPVerifierFile "/path/to/file.srpv" ``` The verifier file can be created with the `openssl` command line utility: ### Creating the SRP verifier file ``` openssl srp -srpvfile passwd.srpv -userinfo "some info" -add username ``` The value given with the optional `-userinfo` parameter is available in the `SSL_SRP_USERINFO` request environment variable. SSLStaplingCache Directive -------------------------- | | | | --- | --- | | Description: | Configures the OCSP stapling cache | | Syntax: | ``` SSLStaplingCache type ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available if using OpenSSL 0.9.8h or later | Configures the cache used to store OCSP responses which get included in the TLS handshake if `[SSLUseStapling](#sslusestapling)` is enabled. Configuration of a cache is mandatory for OCSP stapling. With the exception of `none` and `nonenotnull`, the same storage types are supported as with `[SSLSessionCache](#sslsessioncache)`. SSLStaplingErrorCacheTimeout Directive -------------------------------------- | | | | --- | --- | | Description: | Number of seconds before expiring invalid responses in the OCSP stapling cache | | Syntax: | ``` SSLStaplingErrorCacheTimeout seconds ``` | | Default: | ``` SSLStaplingErrorCacheTimeout 600 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available if using OpenSSL 0.9.8h or later | Sets the timeout in seconds before *invalid* responses in the OCSP stapling cache (configured through `[SSLStaplingCache](#sslstaplingcache)`) will expire. To set the cache timeout for valid responses, see `[SSLStaplingStandardCacheTimeout](#sslstaplingstandardcachetimeout)`. SSLStaplingFakeTryLater Directive --------------------------------- | | | | --- | --- | | Description: | Synthesize "tryLater" responses for failed OCSP stapling queries | | Syntax: | ``` SSLStaplingFakeTryLater on|off ``` | | Default: | ``` SSLStaplingFakeTryLater on ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available if using OpenSSL 0.9.8h or later | When enabled and a query to an OCSP responder for stapling purposes fails, mod\_ssl will synthesize a "tryLater" response for the client. Only effective if `[SSLStaplingReturnResponderErrors](#sslstaplingreturnrespondererrors)` is also enabled. SSLStaplingForceURL Directive ----------------------------- | | | | --- | --- | | Description: | Override the OCSP responder URI specified in the certificate's AIA extension | | Syntax: | ``` SSLStaplingForceURL uri ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available if using OpenSSL 0.9.8h or later | This directive overrides the URI of an OCSP responder as obtained from the authorityInfoAccess (AIA) extension of the certificate. One potential use is when a proxy is used for retrieving OCSP queries. SSLStaplingResponderTimeout Directive ------------------------------------- | | | | --- | --- | | Description: | Timeout for OCSP stapling queries | | Syntax: | ``` SSLStaplingResponderTimeout seconds ``` | | Default: | ``` SSLStaplingResponderTimeout 10 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available if using OpenSSL 0.9.8h or later | This option sets the timeout for queries to OCSP responders when `[SSLUseStapling](#sslusestapling)` is enabled and mod\_ssl is querying a responder for OCSP stapling purposes. SSLStaplingResponseMaxAge Directive ----------------------------------- | | | | --- | --- | | Description: | Maximum allowable age for OCSP stapling responses | | Syntax: | ``` SSLStaplingResponseMaxAge seconds ``` | | Default: | ``` SSLStaplingResponseMaxAge -1 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available if using OpenSSL 0.9.8h or later | This option sets the maximum allowable age ("freshness") when considering OCSP responses for stapling purposes, i.e. when `[SSLUseStapling](#sslusestapling)` is turned on. The default value (`-1`) does not enforce a maximum age, which means that OCSP responses are considered valid as long as their `nextUpdate` field is in the future. SSLStaplingResponseTimeSkew Directive ------------------------------------- | | | | --- | --- | | Description: | Maximum allowable time skew for OCSP stapling response validation | | Syntax: | ``` SSLStaplingResponseTimeSkew seconds ``` | | Default: | ``` SSLStaplingResponseTimeSkew 300 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available if using OpenSSL 0.9.8h or later | This option sets the maximum allowable time skew when mod\_ssl checks the `thisUpdate` and `nextUpdate` fields of OCSP responses which get included in the TLS handshake (OCSP stapling). Only applicable if `[SSLUseStapling](#sslusestapling)` is turned on. SSLStaplingReturnResponderErrors Directive ------------------------------------------ | | | | --- | --- | | Description: | Pass stapling related OCSP errors on to client | | Syntax: | ``` SSLStaplingReturnResponderErrors on|off ``` | | Default: | ``` SSLStaplingReturnResponderErrors on ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available if using OpenSSL 0.9.8h or later | When enabled, mod\_ssl will pass responses from unsuccessful stapling related OCSP queries (such as responses with an overall status other than "successful", responses with a certificate status other than "good", expired responses etc.) on to the client. If set to `off`, only responses indicating a certificate status of "good" will be included in the TLS handshake. SSLStaplingStandardCacheTimeout Directive ----------------------------------------- | | | | --- | --- | | Description: | Number of seconds before expiring responses in the OCSP stapling cache | | Syntax: | ``` SSLStaplingStandardCacheTimeout seconds ``` | | Default: | ``` SSLStaplingStandardCacheTimeout 3600 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available if using OpenSSL 0.9.8h or later | Sets the timeout in seconds before responses in the OCSP stapling cache (configured through `[SSLStaplingCache](#sslstaplingcache)`) will expire. This directive applies to *valid* responses, while `[SSLStaplingErrorCacheTimeout](#sslstaplingerrorcachetimeout)` is used for controlling the timeout for invalid/unavailable responses. SSLStrictSNIVHostCheck Directive -------------------------------- | | | | --- | --- | | Description: | Whether to allow non-SNI clients to access a name-based virtual host. | | Syntax: | ``` SSLStrictSNIVHostCheck on|off ``` | | Default: | ``` SSLStrictSNIVHostCheck off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available in Apache 2.2.12 and later | This directive sets whether a non-SNI client is allowed to access a name-based virtual host. If set to `on` in the default name-based virtual host, clients that are SNI unaware will not be allowed to access *any* virtual host, belonging to this particular IP / port combination. If set to `on` in any other virtual host, SNI unaware clients are not allowed to access this particular virtual host. This option is only available if httpd was compiled against an SNI capable version of OpenSSL. ### Example ``` SSLStrictSNIVHostCheck on ``` SSLUserName Directive --------------------- | | | | --- | --- | | Description: | Variable name to determine user name | | Syntax: | ``` SSLUserName varname ``` | | Context: | server config, directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_ssl | This directive sets the "user" field in the Apache request object. This is used by lower modules to identify the user with a character string. In particular, this may cause the environment variable `REMOTE_USER` to be set. The *varname* can be any of the [SSL environment variables](#envvars). Note that this directive has no effect if the `FakeBasicAuth` option is used (see [SSLOptions](#ssloptions)). ### Example ``` SSLUserName SSL_CLIENT_S_DN_CN ``` SSLUseStapling Directive ------------------------ | | | | --- | --- | | Description: | Enable stapling of OCSP responses in the TLS handshake | | Syntax: | ``` SSLUseStapling on|off ``` | | Default: | ``` SSLUseStapling off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ssl | | Compatibility: | Available if using OpenSSL 0.9.8h or later | This option enables OCSP stapling, as defined by the "Certificate Status Request" TLS extension specified in RFC 6066. If enabled (and requested by the client), mod\_ssl will include an OCSP response for its own certificate in the TLS handshake. Configuring an `[SSLStaplingCache](#sslstaplingcache)` is a prerequisite for enabling OCSP stapling. OCSP stapling relieves the client of querying the OCSP responder on its own, but it should be noted that with the RFC 6066 specification, the server's `CertificateStatus` reply may only include an OCSP response for a single cert. For server certificates with intermediate CA certificates in their chain (the typical case nowadays), stapling in its current implementation therefore only partially achieves the stated goal of "saving roundtrips and resources" - see also [RFC 6961](http://www.ietf.org/rfc/rfc6961.txt) (TLS Multiple Certificate Status Extension). When OCSP stapling is enabled, the `ssl-stapling` mutex is used to control access to the OCSP stapling cache in order to prevent corruption, and the `sss-stapling-refresh` mutex is used to control refreshes of OCSP responses. These mutexes can be configured using the `[Mutex](core#mutex)` directive. SSLVerifyClient Directive ------------------------- | | | | --- | --- | | Description: | Type of Client Certificate verification | | Syntax: | ``` SSLVerifyClient level ``` | | Default: | ``` SSLVerifyClient none ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_ssl | This directive sets the Certificate verification level for the Client Authentication. Notice that this directive can be used both in per-server and per-directory context. In per-server context it applies to the client authentication process used in the standard SSL handshake when a connection is established. In per-directory context it forces a SSL renegotiation with the reconfigured client verification level after the HTTP request was read but before the HTTP response is sent. The following levels are available for *level*: * **none**: no client Certificate is required at all * **optional**: the client *may* present a valid Certificate * **require**: the client *has to* present a valid Certificate * **optional\_no\_ca**: the client may present a valid Certificate but it need not to be (successfully) verifiable. This option cannot be relied upon for client authentication. ### Example ``` SSLVerifyClient require ``` SSLVerifyDepth Directive ------------------------ | | | | --- | --- | | Description: | Maximum depth of CA Certificates in Client Certificate verification | | Syntax: | ``` SSLVerifyDepth number ``` | | Default: | ``` SSLVerifyDepth 1 ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_ssl | This directive sets how deeply mod\_ssl should verify before deciding that the clients don't have a valid certificate. Notice that this directive can be used both in per-server and per-directory context. In per-server context it applies to the client authentication process used in the standard SSL handshake when a connection is established. In per-directory context it forces a SSL renegotiation with the reconfigured client verification depth after the HTTP request was read but before the HTTP response is sent. The depth actually is the maximum number of intermediate certificate issuers, i.e. the number of CA certificates which are max allowed to be followed while verifying the client certificate. A depth of 0 means that self-signed client certificates are accepted only, the default depth of 1 means the client certificate can be self-signed or has to be signed by a CA which is directly known to the server (i.e. the CA's certificate is under `[SSLCACertificatePath](#sslcacertificatepath)`), etc. ### Example ``` SSLVerifyDepth 10 ```
programming_docs
apache_http_server Apache Module mod_session Apache Module mod\_session ========================== | | | | --- | --- | | Description: | Session support | | Status: | Extension | | Module Identifier: | session\_module | | Source File: | mod\_session.c | | Compatibility: | Available in Apache 2.3 and later | ### Summary **Warning** The session modules make use of HTTP cookies, and as such can fall victim to Cross Site Scripting attacks, or expose potentially private information to clients. Please ensure that the relevant risks have been taken into account before enabling the session functionality on your server. This module provides support for a server wide per user session interface. Sessions can be used for keeping track of whether a user has been logged in, or for other per user information that should be kept available across requests. Sessions may be stored on the server, or may be stored on the browser. Sessions may also be optionally encrypted for added security. These features are divided into several modules in addition to `<mod_session>`; `<mod_session_crypto>`, `<mod_session_cookie>` and `<mod_session_dbd>`. Depending on the server requirements, load the appropriate modules into the server (either statically at compile time or dynamically via the `[LoadModule](mod_so#loadmodule)` directive). Sessions may be manipulated from other modules that depend on the session, or the session may be read from and written to using environment variables and HTTP headers, as appropriate. What is a session? ------------------ At the core of the session interface is a table of key and value pairs that are made accessible across browser requests. These pairs can be set to any valid string, as needed by the application making use of the session. The "session" is a **application/x-www-form-urlencoded** string containing these key value pairs, as defined by the [HTML specification](http://www.w3.org/TR/html4/). The session can optionally be encrypted and base64 encoded before being written to the storage mechanism, as defined by the administrator. Who can use a session? ---------------------- The session interface is primarily developed for the use by other server modules, such as `<mod_auth_form>`, however CGI based applications can optionally be granted access to the contents of the session via the HTTP\_SESSION environment variable. Sessions have the option to be modified and/or updated by inserting an HTTP response header containing the new session parameters. Keeping sessions on the server ------------------------------ Apache can be configured to keep track of per user sessions stored on a particular server or group of servers. This functionality is similar to the sessions available in typical application servers. If configured, sessions are tracked through the use of a session ID that is stored inside a cookie, or extracted from the parameters embedded within the URL query string, as found in a typical GET request. As the contents of the session are stored exclusively on the server, there is an expectation of privacy of the contents of the session. This does have performance and resource implications should a large number of sessions be present, or where a large number of webservers have to share sessions with one another. The `<mod_session_dbd>` module allows the storage of user sessions within a SQL database via `<mod_dbd>`. Keeping sessions on the browser ------------------------------- In high traffic environments where keeping track of a session on a server is too resource intensive or inconvenient, the option exists to store the contents of the session within a cookie on the client browser instead. This has the advantage that minimal resources are required on the server to keep track of sessions, and multiple servers within a server farm have no need to share session information. The contents of the session however are exposed to the client, with a corresponding risk of a loss of privacy. The `<mod_session_crypto>` module can be configured to encrypt the contents of the session before writing the session to the client. The `<mod_session_cookie>` allows the storage of user sessions on the browser within an HTTP cookie. Basic Examples -------------- Creating a session is as simple as turning the session on, and deciding where the session will be stored. In this example, the session will be stored on the browser, in a cookie called `session`. ### Browser based session ``` Session On SessionCookieName session path=/ ``` The session is not useful unless it can be written to or read from. The following example shows how values can be injected into the session through the use of a predetermined HTTP response header called `X-Replace-Session`. ### Writing to a session ``` Session On SessionCookieName session path=/ SessionHeader X-Replace-Session ``` The header should contain name value pairs expressed in the same format as a query string in a URL, as in the example below. Setting a key to the empty string has the effect of removing that key from the session. ### CGI to write to a session ``` #!/bin/bash echo "Content-Type: text/plain" echo "X-Replace-Session: key1=foo&key2=&key3=bar" echo env ``` If configured, the session can be read back from the HTTP\_SESSION environment variable. By default, the session is kept private, so this has to be explicitly turned on with the `[SessionEnv](#sessionenv)` directive. ### Read from a session ``` Session On SessionEnv On SessionCookieName session path=/ SessionHeader X-Replace-Session ``` Once read, the CGI variable `HTTP_SESSION` should contain the value `key1=foo&key3=bar`. Session Privacy --------------- Using the "show cookies" feature of your browser, you would have seen a clear text representation of the session. This could potentially be a problem should the end user need to be kept unaware of the contents of the session, or where a third party could gain unauthorised access to the data within the session. The contents of the session can be optionally encrypted before being placed on the browser using the `<mod_session_crypto>` module. ### Browser based encrypted session ``` Session On SessionCryptoPassphrase secret SessionCookieName session path=/ ``` The session will be automatically decrypted on load, and encrypted on save by Apache, the underlying application using the session need have no knowledge that encryption is taking place. Sessions stored on the server rather than on the browser can also be encrypted as needed, offering privacy where potentially sensitive information is being shared between webservers in a server farm using the `<mod_session_dbd>` module. Cookie Privacy -------------- The HTTP cookie mechanism also offers privacy features, such as the ability to restrict cookie transport to SSL protected pages only, or to prevent browser based javascript from gaining access to the contents of the cookie. **Warning** Some of the HTTP cookie privacy features are either non-standard, or are not implemented consistently across browsers. The session modules allow you to set cookie parameters, but it makes no guarantee that privacy will be respected by the browser. If security is a concern, use the `<mod_session_crypto>` to encrypt the contents of the session, or store the session on the server using the `<mod_session_dbd>` module. Standard cookie parameters can be specified after the name of the cookie, as in the example below. ### Setting cookie parameters ``` Session On SessionCryptoPassphrase secret SessionCookieName session path=/private;domain=example.com;httponly;secure; ``` In cases where the Apache server forms the frontend for backend origin servers, it is possible to have the session cookies removed from the incoming HTTP headers using the `[SessionCookieRemove](mod_session_cookie#sessioncookieremove)` directive. This keeps the contents of the session cookies from becoming accessible from the backend server. Session Support for Authentication ---------------------------------- As is possible within many application servers, authentication modules can use a session for storing the username and password after login. The `<mod_auth_form>` saves the user's login name and password within the session. ### Form based authentication ``` Session On SessionCryptoPassphrase secret SessionCookieName session path=/ AuthFormProvider file AuthUserFile "conf/passwd" AuthType form AuthName "realm" #... ``` See the `<mod_auth_form>` module for documentation and complete examples. Integrating Sessions with External Applications ----------------------------------------------- In order for sessions to be useful, it must be possible to share the contents of a session with external applications, and it must be possible for an external application to write a session of its own. A typical example might be an application that changes a user's password set by `<mod_auth_form>`. This application would need to read the current username and password from the session, make the required changes to the user's password, and then write the new password to the session in order to provide a seamless transition to the new password. A second example might involve an application that registers a new user for the first time. When registration is complete, the username and password is written to the session, providing a seamless transition to being logged in. Apache modules Modules within the server that need access to the session can use the **mod\_session.h** API in order to read from and write to the session. This mechanism is used by modules like `<mod_auth_form>`. CGI programs and scripting languages Applications that run within the webserver can optionally retrieve the value of the session from the **HTTP\_SESSION** environment variable. The session should be encoded as a **application/x-www-form-urlencoded** string as described by the [HTML specification](http://www.w3.org/TR/html4/). The environment variable is controlled by the setting of the `[SessionEnv](#sessionenv)` directive. The session can be written to by the script by returning a **application/x-www-form-urlencoded** response header with a name set by the `[SessionHeader](#sessionheader)` directive. In both cases, any encryption or decryption, and the reading the session from or writing the session to the chosen storage mechanism is handled by the `<mod_session>` modules and corresponding configuration. Applications behind `<mod_proxy>` If the `[SessionHeader](#sessionheader)` directive is used to define an HTTP request header, the session, encoded as a **application/x-www-form-urlencoded** string, will be made available to the application. If the same header is provided in the response, the value of this response header will be used to replace the session. As above, any encryption or decryption, and the reading the session from or writing the session to the chosen storage mechanism is handled by the `<mod_session>` modules and corresponding configuration. Standalone applications Applications might choose to manipulate the session outside the control of the Apache HTTP server. In this case, it is the responsibility of the application to read the session from the chosen storage mechanism, decrypt the session, update the session, encrypt the session and write the session to the chosen storage mechanism, as appropriate. Session Directive ----------------- | | | | --- | --- | | Description: | Enables a session for the current directory or location | | Syntax: | ``` Session On|Off ``` | | Default: | ``` Session Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_session | The `Session` directive enables a session for the directory or location container. Further directives control where the session will be stored and how privacy is maintained. SessionEnv Directive -------------------- | | | | --- | --- | | Description: | Control whether the contents of the session are written to the HTTP\_SESSION environment variable | | Syntax: | ``` SessionEnv On|Off ``` | | Default: | ``` SessionEnv Off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_session | If set to On, the `SessionEnv` directive causes the contents of the session to be written to a CGI environment variable called HTTP\_SESSION. The string is written in the URL query format, for example: `key1=foo&key3=bar` SessionExclude Directive ------------------------ | | | | --- | --- | | Description: | Define URL prefixes for which a session is ignored | | Syntax: | ``` SessionExclude path ``` | | Default: | `none` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session | The `SessionExclude` directive allows sessions to be disabled relative to URL prefixes only. This can be used to make a website more efficient, by targeting a more precise URL space for which a session should be maintained. By default, all URLs within the directory or location are included in the session. The `[SessionExclude](#sessionexclude)` directive takes precedence over the `[SessionInclude](#sessioninclude)` directive. **Warning** This directive has a similar purpose to the path attribute in HTTP cookies, but should not be confused with this attribute. This directive does not set the path attribute, which must be configured separately. SessionExpiryUpdateInterval Directive ------------------------------------- | | | | --- | --- | | Description: | Define the number of seconds a session's expiry may change without the session being updated | | Syntax: | ``` SessionExpiryUpdateInterval interval ``` | | Default: | ``` SessionExpiryUpdateInterval 0 (always update) ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_session | | Compatibility: | Available in Apache 2.4.41 and later | The `SessionExpiryUpdateInterval` directive allows sessions to avoid the cost associated with writing the session each request when only the expiry time has changed. This can be used to make a website more efficient or reduce load on a database when using `<mod_session_dbd>`. The session is always written if the data stored in the session has changed or the expiry has changed by more than the configured interval. Setting the interval to zero disables this directive, and the session expiry is refreshed for each request. This directive only has an effect when combined with `[SessionMaxAge](#sessionmaxage)` to enable session expiry. Sessions without an expiry are only written when the data stored in the session has changed. **Warning** Because the session expiry may not be refreshed with each request, it's possible for sessions to expire up to interval seconds early. Using a small interval usually provides sufficient savings while having a minimal effect on expiry resolution. SessionHeader Directive ----------------------- | | | | --- | --- | | Description: | Import session updates from a given HTTP response header | | Syntax: | ``` SessionHeader header ``` | | Default: | `none` | | Context: | server config, virtual host, directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_session | The `SessionHeader` directive defines the name of an HTTP response header which, if present, will be parsed and written to the current session. The header value is expected to be in the URL query format, for example: `key1=foo&key2=&key3=bar` Where a key is set to the empty string, that key will be removed from the session. SessionInclude Directive ------------------------ | | | | --- | --- | | Description: | Define URL prefixes for which a session is valid | | Syntax: | ``` SessionInclude path ``` | | Default: | ``` all URLs ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_session | The `SessionInclude` directive allows sessions to be made valid for specific URL prefixes only. This can be used to make a website more efficient, by targeting a more precise URL space for which a session should be maintained. By default, all URLs within the directory or location are included in the session. **Warning** This directive has a similar purpose to the path attribute in HTTP cookies, but should not be confused with this attribute. This directive does not set the path attribute, which must be configured separately. SessionMaxAge Directive ----------------------- | | | | --- | --- | | Description: | Define a maximum age in seconds for a session | | Syntax: | ``` SessionMaxAge maxage ``` | | Default: | ``` SessionMaxAge 0 ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_session | The `SessionMaxAge` directive defines a time limit for which a session will remain valid. When a session is saved, this time limit is reset and an existing session can be continued. If a session becomes older than this limit without a request to the server to refresh the session, the session will time out and be removed. Where a session is used to stored user login details, this has the effect of logging the user out automatically after the given time. Setting the maxage to zero disables session expiry. apache_http_server Apache Module mod_lbmethod_bytraffic Apache Module mod\_lbmethod\_bytraffic ====================================== | | | | --- | --- | | Description: | Weighted Traffic Counting load balancer scheduler algorithm for `<mod_proxy_balancer>` | | Status: | Extension | | Module Identifier: | lbmethod\_bytraffic\_module | | Source File: | mod\_lbmethod\_bytraffic.c | | Compatibility: | Split off from `<mod_proxy_balancer>` in 2.3 | ### Summary This module does not provide any configuration directives of its own. It requires the services of `<mod_proxy_balancer>`, and provides the `bytraffic` load balancing method. Weighted Traffic Counting Algorithm ----------------------------------- Enabled via `lbmethod=bytraffic`, the idea behind this scheduler is very similar to the Request Counting method, with the following changes: lbfactor is *how much traffic, in bytes, we want this worker to handle*. This is also a normalized value representing their "share" of the amount of work to be done, but instead of simply counting the number of requests, we take into account the amount of traffic this worker has either seen or produced. If a balancer is configured as follows: | worker | a | b | c | | --- | --- | --- | --- | | lbfactor | 1 | 2 | 1 | Then we mean that we want b to process twice the amount of bytes than a or c should. It does not necessarily mean that b would handle twice as many requests, but it would process twice the I/O. Thus, the size of the request and response are applied to the weighting and selection algorithm. Note: input and output bytes are weighted the same. apache_http_server Apache Module mod_proxy_express Apache Module mod\_proxy\_express ================================= | | | | --- | --- | | Description: | Dynamic mass reverse proxy extension for `<mod_proxy>` | | Status: | Extension | | Module Identifier: | proxy\_express\_module | | Source File: | mod\_proxy\_express.c | | Compatibility: | Available in Apache 2.3.13 and later | ### Summary This module creates dynamically configured mass reverse proxies, by mapping the `Host:` header of the HTTP request to a server name and backend URL stored in a DBM file. This allows for easy use of a huge number of reverse proxies with no configuration changes. It is much less feature-full than `<mod_proxy_balancer>`, which also provides dynamic growth, but is intended to handle much, much larger numbers of backends. It is ideally suited as a front-end HTTP switch and for micro-services architectures. This module *requires* the service of `<mod_proxy>`. **Warning** Do not enable proxying until you have [secured your server](mod_proxy#access). Open proxy servers are dangerous both to your network and to the Internet at large. **Limitations** * This module is not intended to replace the dynamic capability of `<mod_proxy_balancer>`. Instead, it is intended to be mostly a lightweight and fast alternative to using `<mod_rewrite>` with `[RewriteMap](mod_rewrite#rewritemap)` and the `[P]` flag for mapped reverse proxying. * It does not support regex or pattern matching at all. * It emulates: ``` <VirtualHost *:80> ServerName front.end.server ProxyPass "/" "back.end.server:port" ProxyPassReverse "/" "back.end.server:port" </VirtualHost> ``` That is, the entire URL is appended to the mapped backend URL. This is in keeping with the intent of being a simple but fast reverse proxy switch. ProxyExpressDBMFile Directive ----------------------------- | | | | --- | --- | | Description: | Pathname to DBM file. | | Syntax: | ``` ProxyExpressDBMFile pathname ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy\_express | The `ProxyExpressDBMFile` directive points to the location of the Express map DBM file. This file serves to map the incoming server name, obtained from the `Host:` header, to a backend URL. **Note** The file is constructed from a plain text file format using the `[httxt2dbm](../programs/httxt2dbm)` utility. **ProxyExpress map file** ``` ## ##express-map.txt: ## www1.example.com http://192.168.211.2:8080 www2.example.com http://192.168.211.12:8088 www3.example.com http://192.168.212.10 ``` **Create DBM file** ``` httxt2dbm -i express-map.txt -o emap ``` **Configuration** ``` ProxyExpressEnable on ProxyExpressDBMFile emap ``` ProxyExpressDBMType Directive ----------------------------- | | | | --- | --- | | Description: | DBM type of file. | | Syntax: | ``` ProxyExpressDBMType type ``` | | Default: | ``` ProxyExpressDBMType default ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy\_express | The `ProxyExpressDBMType` directive controls the DBM type expected by the module. The default is the default DBM type created with `[httxt2dbm](../programs/httxt2dbm)`. Possible values are (not all may be available at run time): | Value | Description | | --- | --- | | `db` | Berkeley DB files | | `gdbm` | GDBM files | | `ndbm` | NDBM files | | `sdbm` | SDBM files (always available) | | `default` | default DBM type | ProxyExpressEnable Directive ---------------------------- | | | | --- | --- | | Description: | Enable the module functionality. | | Syntax: | ``` ProxyExpressEnable on|off ``` | | Default: | ``` ProxyExpressEnable off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy\_express | The `ProxyExpressEnable` directive controls whether the module will be active.
programming_docs
apache_http_server Apache Module mod_authn_dbm Apache Module mod\_authn\_dbm ============================= | | | | --- | --- | | Description: | User authentication using DBM files | | Status: | Extension | | Module Identifier: | authn\_dbm\_module | | Source File: | mod\_authn\_dbm.c | | Compatibility: | Available in Apache 2.1 and later | ### Summary This module provides authentication front-ends such as `<mod_auth_digest>` and `<mod_auth_basic>` to authenticate users by looking up users in dbm password files. Similar functionality is provided by `<mod_authn_file>`. When using `<mod_auth_basic>` or `<mod_auth_digest>`, this module is invoked via the `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` or `[AuthDigestProvider](mod_auth_digest#authdigestprovider)` with the `dbm` value. AuthDBMType Directive --------------------- | | | | --- | --- | | Description: | Sets the type of database file that is used to store passwords | | Syntax: | ``` AuthDBMType default|SDBM|GDBM|NDBM|DB ``` | | Default: | ``` AuthDBMType default ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authn\_dbm | Sets the type of database file that is used to store the passwords. The default database type is determined at compile time. The availability of other types of database files also depends on [compile-time settings](../programs/configure#options). For example, in order to enable the support for Berkeley DB (correspondent to the `db` type) the `--with-berkeley-db` option needs to be added to httpd's configure to generate the necessary DSO. It is crucial that whatever program you use to create your password files is configured to use the same type of database. AuthDBMUserFile Directive ------------------------- | | | | --- | --- | | Description: | Sets the name of a database file containing the list of users and passwords for authentication | | Syntax: | ``` AuthDBMUserFile file-path ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authn\_dbm | The `AuthDBMUserFile` directive sets the name of a DBM file containing the list of users and passwords for user authentication. File-path is the absolute path to the user file. The user file is keyed on the username. The value for a user is the encrypted password, optionally followed by a colon and arbitrary data. The colon and the data following it will be ignored by the server. **Security:** Make sure that the `AuthDBMUserFile` is stored outside the document tree of the web-server; do *not* put it in the directory that it protects. Otherwise, clients will be able to download the `AuthDBMUserFile`. The encrypted password format depends on which authentication frontend (e.g. `<mod_auth_basic>` or `<mod_auth_digest>`) is being used. See [Password Formats](../misc/password_encryptions) for more information. Important compatibility note: The implementation of `dbmopen` in the Apache modules reads the string length of the hashed values from the DBM data structures, rather than relying upon the string being NULL-appended. Some applications, such as the Netscape web server, rely upon the string being NULL-appended, so if you are having trouble using DBM files interchangeably between applications this may be a part of the problem. A perl script called `[dbmmanage](../programs/dbmmanage)` is included with Apache. This program can be used to create and update DBM format password files for use with this module. Another tool for maintaining the DBM files is the included program `[htdbm](../programs/htdbm)`. apache_http_server Apache Module mod_proxy_ftp Apache Module mod\_proxy\_ftp ============================= | | | | --- | --- | | Description: | FTP support module for `<mod_proxy>` | | Status: | Extension | | Module Identifier: | proxy\_ftp\_module | | Source File: | mod\_proxy\_ftp.c | ### Summary This module *requires* the service of `<mod_proxy>`. It provides support for the proxying FTP sites. Note that FTP support is currently limited to the GET method. Thus, in order to get the ability of handling FTP proxy requests, `<mod_proxy>` and `<mod_proxy_ftp>` have to be present in the server. **Warning** Do not enable proxying until you have [secured your server](mod_proxy#access). Open proxy servers are dangerous both to your network and to the Internet at large. Why doesn't file type xxx download via FTP? ------------------------------------------- You probably don't have that particular file type defined as `application/octet-stream` in your proxy's mime.types configuration file. A useful line can be: ``` application/octet-stream bin dms lha lzh exe class tgz taz ``` Alternatively you may prefer to use the `[ForceType](core#forcetype)` directive to default everything to binary: ``` ForceType application/octet-stream ``` How can I force an FTP ASCII download of file xxx? -------------------------------------------------- In the rare situation where you must download a specific file using the FTP `ASCII` transfer method (while the default transfer is in `binary` mode), you can override `<mod_proxy>`'s default by suffixing the request with `;type=a` to force an ASCII transfer. (FTP Directory listings are always executed in ASCII mode, however.) How can I do FTP upload? ------------------------ Currently, only GET is supported for FTP in `<mod_proxy>`. You can of course use HTTP upload (POST or PUT) through an Apache proxy. How can I access FTP files outside of my home directory? -------------------------------------------------------- An FTP URI is interpreted relative to the home directory of the user who is logging in. Alas, to reach higher directory levels you cannot use /../, as the dots are interpreted by the browser and not actually sent to the FTP server. To address this problem, the so called Squid %2f hack was implemented in the Apache FTP proxy; it is a solution which is also used by other popular proxy servers like the [Squid Proxy Cache](http://www.squid-cache.org/). By prepending `/%2f` to the path of your request, you can make such a proxy change the FTP starting directory to `/` (instead of the home directory). For example, to retrieve the file `/etc/motd`, you would use the URL: `ftp://user@host/%2f/etc/motd` How can I hide the FTP cleartext password in my browser's URL line? ------------------------------------------------------------------- To log in to an FTP server by username and password, Apache uses different strategies. In absence of a user name and password in the URL altogether, Apache sends an anonymous login to the FTP server, *i.e.*, ``` user: anonymous password: apache-proxy@ ``` This works for all popular FTP servers which are configured for anonymous access. For a personal login with a specific username, you can embed the user name into the URL, like in: `ftp://username@host/myfile` If the FTP server asks for a password when given this username (which it should), then Apache will reply with a `401` (Authorization required) response, which causes the Browser to pop up the username/password dialog. Upon entering the password, the connection attempt is retried, and if successful, the requested resource is presented. The advantage of this procedure is that your browser does not display the password in cleartext (which it would if you had used `ftp://username:password@host/myfile` in the first place). **Note** The password which is transmitted in such a way is not encrypted on its way. It travels between your browser and the Apache proxy server in a base64-encoded cleartext string, and between the Apache proxy and the FTP server as plaintext. You should therefore think twice before accessing your FTP server via HTTP (or before accessing your personal files via FTP at all!) When using insecure channels, an eavesdropper might intercept your password on its way. Why do I get a file listing when I expected a file to be downloaded? -------------------------------------------------------------------- In order to allow both browsing the directories on an FTP server and downloading files, Apache looks at the request URL. If it looks like a directory, or contains wildcard characters ("\*?[{~"), then it guesses that a listing is wanted instead of a download. You can disable the special handling of names with wildcard characters. See the `[ProxyFtpListOnWildcard](#proxyftplistonwildcard)` directive. ProxyFtpDirCharset Directive ---------------------------- | | | | --- | --- | | Description: | Define the character set for proxied FTP listings | | Syntax: | ``` ProxyFtpDirCharset character_set ``` | | Default: | ``` ProxyFtpDirCharset ISO-8859-1 ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy\_ftp | | Compatibility: | Available in Apache 2.2.7 and later. Moved from `<mod_proxy>` in Apache 2.3.5. | The `ProxyFtpDirCharset` directive defines the character set to be set for FTP directory listings in HTML generated by `<mod_proxy_ftp>`. ProxyFtpEscapeWildcards Directive --------------------------------- | | | | --- | --- | | Description: | Whether wildcards in requested filenames are escaped when sent to the FTP server | | Syntax: | ``` ProxyFtpEscapeWildcards on|off ``` | | Default: | ``` ProxyFtpEscapeWildcards on ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy\_ftp | | Compatibility: | Available in Apache 2.3.3 and later | The `ProxyFtpEscapeWildcards` directive controls whether wildcard characters ("\*?[{~") in requested filenames are escaped with backslash before sending them to the FTP server. That is the default behavior, but many FTP servers don't know about the escaping and try to serve the literal filenames they were sent, including the backslashes in the names. Set to "off" to allow downloading files with wildcards in their names from FTP servers that don't understand wildcard escaping. ProxyFtpListOnWildcard Directive -------------------------------- | | | | --- | --- | | Description: | Whether wildcards in requested filenames trigger a file listing | | Syntax: | ``` ProxyFtpListOnWildcard on|off ``` | | Default: | ``` ProxyFtpListOnWildcard on ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy\_ftp | | Compatibility: | Available in Apache 2.3.3 and later | The `ProxyFtpListOnWildcard` directive controls whether wildcard characters ("\*?[{~") in requested filenames cause `<mod_proxy_ftp>` to return a listing of files instead of downloading a file. By default (value on), they do. Set to "off" to allow downloading files even if they have wildcard characters in their names. apache_http_server Apache Module mod_nw_ssl Apache Module mod\_nw\_ssl ========================== | | | | --- | --- | | Description: | Enable SSL encryption for NetWare | | Status: | Base | | Module Identifier: | nwssl\_module | | Source File: | mod\_nw\_ssl.c | | Compatibility: | NetWare only | ### Summary This module enables SSL encryption for a specified port. It takes advantage of the SSL encryption functionality that is built into the NetWare operating system. NWSSLTrustedCerts Directive --------------------------- | | | | --- | --- | | Description: | List of additional client certificates | | Syntax: | ``` NWSSLTrustedCerts filename [filename] ... ``` | | Context: | server config | | Status: | Base | | Module: | mod\_nw\_ssl | Specifies a list of client certificate files (DER format) that are used when creating a proxied SSL connection. Each client certificate used by a server must be listed separately in its own `.der` file. NWSSLUpgradeable Directive -------------------------- | | | | --- | --- | | Description: | Allows a connection to be upgraded to an SSL connection upon request | | Syntax: | ``` NWSSLUpgradeable [IP-address:]portnumber ``` | | Context: | server config | | Status: | Base | | Module: | mod\_nw\_ssl | Allow a connection that was created on the specified address and/or port to be upgraded to an SSL connection upon request from the client. The address and/or port must have already be defined previously with a `[Listen](mpm_common#listen)` directive. SecureListen Directive ---------------------- | | | | --- | --- | | Description: | Enables SSL encryption for the specified port | | Syntax: | ``` SecureListen [IP-address:]portnumber Certificate-Name [MUTUAL] ``` | | Context: | server config | | Status: | Base | | Module: | mod\_nw\_ssl | Specifies the port and the eDirectory based certificate name that will be used to enable SSL encryption. An optional third parameter also enables mutual authentication. apache_http_server Apache Module mod_proxy_fdpass Apache Module mod\_proxy\_fdpass ================================ | | | | --- | --- | | Description: | fdpass external process support module for `<mod_proxy>` | | Status: | Extension | | Module Identifier: | proxy\_fdpass\_module | | Source File: | mod\_proxy\_fdpass.c | | Compatibility: | Available for unix in version 2.3 and later | ### Summary This module *requires* the service of `<mod_proxy>`. It provides support for the passing the socket of the client to another process. `mod_proxy_fdpass` uses the ability of AF\_UNIX domain sockets to [pass an open file descriptor](http://www.freebsd.org/cgi/man.cgi?query=recv) to allow another process to finish handling a request. The module has a `proxy_fdpass_flusher` provider interface, which allows another module to optionally send the response headers, or even the start of the response body. The default `flush` provider disables keep-alive, and sends the response headers, letting the external process just send a response body. In order to use another provider, you have to set the `flusher` parameter in the `[ProxyPass](mod_proxy#proxypass)` directive. At this time the only data passed to the external process is the client socket. To receive a client socket, call recvfrom with an allocated [`struct cmsghdr`](http://www.kernel.org/doc/man-pages/online/pages/man3/cmsg.3.html). Future versions of this module may include more data after the client socket, but this is not implemented at this time. apache_http_server Apache Module mod_isapi Apache Module mod\_isapi ======================== | | | | --- | --- | | Description: | ISAPI Extensions within Apache for Windows | | Status: | Base | | Module Identifier: | isapi\_module | | Source File: | mod\_isapi.c | | Compatibility: | Win32 only | ### Summary This module implements the Internet Server extension API. It allows Internet Server extensions (*e.g.* ISAPI .dll modules) to be served by Apache for Windows, subject to the noted restrictions. ISAPI extension modules (.dll files) are written by third parties. The Apache Group does not author these modules, so we provide no support for them. Please contact the ISAPI's author directly if you are experiencing problems running their ISAPI extension. **Please *do not* post such problems to Apache's lists or bug reporting pages.** Usage ----- In the server configuration file, use the `[AddHandler](mod_mime#addhandler)` directive to associate ISAPI files with the `isapi-handler` handler, and map it to them with their file extensions. To enable any .dll file to be processed as an ISAPI extension, edit the httpd.conf file and add the following line: ``` AddHandler isapi-handler .dll ``` In older versions of the Apache server, `isapi-isa` was the proper handler name, rather than `isapi-handler`. As of 2.3 development versions of the Apache server, `isapi-isa` is no longer valid. You will need to change your configuration to use `isapi-handler` instead. There is no capability within the Apache server to leave a requested module loaded. However, you may preload and keep a specific module loaded by using the following syntax in your httpd.conf: ``` ISAPICacheFile c:/WebWork/Scripts/ISAPI/mytest.dll ``` Whether or not you have preloaded an ISAPI extension, all ISAPI extensions are governed by the same permissions and restrictions as CGI scripts. That is, `[Options](core#options)` `ExecCGI` must be set for the directory that contains the ISAPI .dll file. Review the [Additional Notes](#notes) and the [Programmer's Journal](#journal) for additional details and clarification of the specific ISAPI support offered by `<mod_isapi>`. Additional Notes ---------------- Apache's ISAPI implementation conforms to all of the ISAPI 2.0 specification, except for some "Microsoft-specific" extensions dealing with asynchronous I/O. Apache's I/O model does not allow asynchronous reading and writing in a manner that the ISAPI could access. If an ISA tries to access unsupported features, including async I/O, a message is placed in the error log to help with debugging. Since these messages can become a flood, the directive `ISAPILogNotSupported Off` exists to quiet this noise. Some servers, like Microsoft IIS, load the ISAPI extension into the server and keep it loaded until memory usage is too high, or unless configuration options are specified. Apache currently loads and unloads the ISAPI extension each time it is requested, unless the `[ISAPICacheFile](#isapicachefile)` directive is specified. This is inefficient, but Apache's memory model makes this the most effective method. Many ISAPI modules are subtly incompatible with the Apache server, and unloading these modules helps to ensure the stability of the server. Also, remember that while Apache supports ISAPI Extensions, it **does not support ISAPI Filters**. Support for filters may be added at a later date, but no support is planned at this time. Programmer's Journal -------------------- If you are programming Apache 2.0 `<mod_isapi>` modules, you must limit your calls to `ServerSupportFunction` to the following directives: `HSE_REQ_SEND_URL_REDIRECT_RESP` Redirect the user to another location. This must be a fully qualified URL (*e.g.* `http://server/location`). `HSE_REQ_SEND_URL` Redirect the user to another location. This cannot be a fully qualified URL, you are not allowed to pass the protocol or a server name (*e.g.* simply `/location`). This redirection is handled by the server, not the browser. **Warning** In their recent documentation, Microsoft appears to have abandoned the distinction between the two `HSE_REQ_SEND_URL` functions. Apache continues to treat them as two distinct functions with different requirements and behaviors. `HSE_REQ_SEND_RESPONSE_HEADER` Apache accepts a response body following the header if it follows the blank line (two consecutive newlines) in the headers string argument. This body cannot contain NULLs, since the headers argument is NULL terminated. `HSE_REQ_DONE_WITH_SESSION` Apache considers this a no-op, since the session will be finished when the ISAPI returns from processing. `HSE_REQ_MAP_URL_TO_PATH` Apache will translate a virtual name to a physical name. `HSE_APPEND_LOG_PARAMETER` This logged message may be captured in any of the following logs: * in the `\"%{isapi-parameter}n\"` component in a `[CustomLog](mod_log_config#customlog)` directive * in the `%q` log component with the `[ISAPIAppendLogToQuery](#isapiappendlogtoquery)` `On` directive * in the error log with the `[ISAPIAppendLogToErrors](#isapiappendlogtoerrors)` `On` directive The first option, the `%{isapi-parameter}n` component, is always available and preferred. `HSE_REQ_IS_KEEP_CONN` Will return the negotiated Keep-Alive status. `HSE_REQ_SEND_RESPONSE_HEADER_EX` Will behave as documented, although the `fKeepConn` flag is ignored. `HSE_REQ_IS_CONNECTED` Will report false if the request has been aborted. Apache returns `FALSE` to any unsupported call to `ServerSupportFunction`, and sets the `GetLastError` value to `ERROR_INVALID_PARAMETER`. `ReadClient` retrieves the request body exceeding the initial buffer (defined by `[ISAPIReadAheadBuffer](#isapireadaheadbuffer)`). Based on the `ISAPIReadAheadBuffer` setting (number of bytes to buffer prior to calling the ISAPI handler) shorter requests are sent complete to the extension when it is invoked. If the request is longer, the ISAPI extension must use `ReadClient` to retrieve the remaining request body. `WriteClient` is supported, but only with the `HSE_IO_SYNC` flag or no option flag (value of `0`). Any other `WriteClient` request will be rejected with a return value of `FALSE`, and a `GetLastError` value of `ERROR_INVALID_PARAMETER`. `GetServerVariable` is supported, although extended server variables do not exist (as defined by other servers.) All the usual Apache CGI environment variables are available from `GetServerVariable`, as well as the `ALL_HTTP` and `ALL_RAW` values. Since httpd 2.0, `<mod_isapi>` supports additional features introduced in later versions of the ISAPI specification, as well as limited emulation of async I/O and the `TransmitFile` semantics. Apache httpd also supports preloading ISAPI .dlls for performance. ISAPIAppendLogToErrors Directive -------------------------------- | | | | --- | --- | | Description: | Record `HSE_APPEND_LOG_PARAMETER` requests from ISAPI extensions to the error log | | Syntax: | ``` ISAPIAppendLogToErrors on|off ``` | | Default: | ``` ISAPIAppendLogToErrors off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_isapi | Record `HSE_APPEND_LOG_PARAMETER` requests from ISAPI extensions to the server error log. ISAPIAppendLogToQuery Directive ------------------------------- | | | | --- | --- | | Description: | Record `HSE_APPEND_LOG_PARAMETER` requests from ISAPI extensions to the query field | | Syntax: | ``` ISAPIAppendLogToQuery on|off ``` | | Default: | ``` ISAPIAppendLogToQuery on ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_isapi | Record `HSE_APPEND_LOG_PARAMETER` requests from ISAPI extensions to the query field (appended to the `[CustomLog](mod_log_config#customlog)` `%q` component). ISAPICacheFile Directive ------------------------ | | | | --- | --- | | Description: | ISAPI .dll files to be loaded at startup | | Syntax: | ``` ISAPICacheFile file-path [file-path] ... ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | mod\_isapi | Specifies a space-separated list of file names to be loaded when the Apache server is launched, and remain loaded until the server is shut down. This directive may be repeated for every ISAPI .dll file desired. The full path name of each file should be specified. If the path name is not absolute, it will be treated relative to `[ServerRoot](core#serverroot)`. ISAPIFakeAsync Directive ------------------------ | | | | --- | --- | | Description: | Fake asynchronous support for ISAPI callbacks | | Syntax: | ``` ISAPIFakeAsync on|off ``` | | Default: | ``` ISAPIFakeAsync off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_isapi | While set to on, asynchronous support for ISAPI callbacks is simulated. ISAPILogNotSupported Directive ------------------------------ | | | | --- | --- | | Description: | Log unsupported feature requests from ISAPI extensions | | Syntax: | ``` ISAPILogNotSupported on|off ``` | | Default: | ``` ISAPILogNotSupported off ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_isapi | Logs all requests for unsupported features from ISAPI extensions in the server error log. This may help administrators to track down problems. Once set to on and all desired ISAPI modules are functioning, it should be set back to off. ISAPIReadAheadBuffer Directive ------------------------------ | | | | --- | --- | | Description: | Size of the Read Ahead Buffer sent to ISAPI extensions | | Syntax: | ``` ISAPIReadAheadBuffer size ``` | | Default: | ``` ISAPIReadAheadBuffer 49152 ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Base | | Module: | mod\_isapi | Defines the maximum size of the Read Ahead Buffer sent to ISAPI extensions when they are initially invoked. All remaining data must be retrieved using the `ReadClient` callback; some ISAPI extensions may not support the `ReadClient` function. Refer questions to the ISAPI extension's author.
programming_docs
apache_http_server Apache Module mod_echo Apache Module mod\_echo ======================= | | | | --- | --- | | Description: | A simple echo server to illustrate protocol modules | | Status: | Experimental | | Module Identifier: | echo\_module | | Source File: | mod\_echo.c | ### Summary This module provides an example protocol module to illustrate the concept. It provides a simple echo server. Telnet to it and type stuff, and it will echo it. ProtocolEcho Directive ---------------------- | | | | --- | --- | | Description: | Turn the echo server on or off | | Syntax: | ``` ProtocolEcho On|Off ``` | | Default: | ``` ProtocolEcho Off ``` | | Context: | server config, virtual host | | Status: | Experimental | | Module: | mod\_echo | The `ProtocolEcho` directive enables or disables the echo server. ### Example ``` ProtocolEcho On ``` apache_http_server Apache Module mod_http2 Apache Module mod\_http2 ======================== | | | | --- | --- | | Description: | Support for the HTTP/2 transport layer | | Status: | Extension | | Module Identifier: | http2\_module | | Source File: | mod\_http2.c | | Compatibility: | Available in version 2.4.17 and later | ### Summary This module provides HTTP/2 ([RFC 7540](https://tools.ietf.org/html/rfc7540)) support for the Apache HTTP Server. This module relies on [libnghttp2](http://nghttp2.org/) to provide the core http/2 engine. You must enable HTTP/2 via `[Protocols](core#protocols)` in order to use the functionality described in this document. The HTTP/2 protocol [does not require](https://http2.github.io/faq/#does-http2-require-encryption) the use of encryption so two schemes are available: `h2` (HTTP/2 over TLS) and `h2c` (HTTP/2 over TCP). Two useful configuration schemes are: **HTTP/2 in a VirtualHost context (TLS only)** ``` Protocols h2 http/1.1 ``` Allows HTTP/2 negotiation (h2) via TLS ALPN in a secure `[<VirtualHost>](core#virtualhost)`. HTTP/2 preamble checking (Direct mode, see `[H2Direct](#h2direct)`) is disabled by default for `h2`. **HTTP/2 in a Server context (TLS and cleartext)** ``` Protocols h2 h2c http/1.1 ``` Allows HTTP/2 negotiation (h2) via TLS ALPN for secure `[<VirtualHost>](core#virtualhost)`. Allows HTTP/2 cleartext negotiation (h2c) upgrading from an initial HTTP/1.1 connection or via HTTP/2 preamble checking (Direct mode, see `[H2Direct](#h2direct)`). Refer to the official [HTTP/2 FAQ](https://http2.github.io/faq) for any doubt about the protocol. How it works ------------ ### HTTP/2 Dimensioning Enabling HTTP/2 on your Apache Server has impact on the resource consumption and if you have a busy site, you may need to consider carefully the implications. The first noticeable thing after enabling HTTP/2 is that your server processes will start additional threads. The reason for this is that HTTP/2 gives all requests that it receives to its own *Worker* threads for processing, collects the results and streams them out to the client. In the current implementation, these workers use a separate thread pool from the MPM workers that you might be familiar with. This is just how things are right now and not intended to be like this forever. (It might be forever for the 2.4.x release line, though.) So, HTTP/2 workers, or shorter H2Workers, will not show up in `<mod_status>`. They are also not counted against directives such as `[ThreadsPerChild](mpm_common#threadsperchild)`. However they take `[ThreadsPerChild](mpm_common#threadsperchild)` as default if you have not configured something else via `[H2MinWorkers](#h2minworkers)` and `[H2MaxWorkers](#h2maxworkers)`. Another thing to watch out for is is memory consumption. Since HTTP/2 keeps more state on the server to manage all the open request, priorities for and dependencies between them, it will always need more memory than HTTP/1.1 processing. There are three directives which steer the memory footprint of a HTTP/2 connection: `[H2MaxSessionStreams](#h2maxsessionstreams)`, `[H2WindowSize](#h2windowsize)` and `[H2StreamMaxMemSize](#h2streammaxmemsize)`. `[H2MaxSessionStreams](#h2maxsessionstreams)` limits the number of parallel requests that a client can make on a HTTP/2 connection. It depends on your site how many you should allow. The default is 100 which is plenty and unless you run into memory problems, I would keep it this way. Most requests that browsers send are GETs without a body, so they use up only a little bit of memory until the actual processing starts. `[H2WindowSize](#h2windowsize)` controls how much the client is allowed to send as body of a request, before it waits for the server to encourage more. Or, the other way around, it is the amount of request body data the server needs to be able to buffer. This is per request. And last, but not least, `[H2StreamMaxMemSize](#h2streammaxmemsize)` controls how much response data shall be buffered. The request sits in a H2Worker thread and is producing data, the HTTP/2 connection tries to send this to the client. If the client does not read fast enough, the connection will buffer this amount of data and then suspend the H2Worker. ### Multiple Hosts and Misdirected Requests Many sites use the same TLS certificate for multiple virtual hosts. The certificate either has a wildcard name, such as '\*.example.org' or carries several alternate names. Browsers using HTTP/2 will recognize that and reuse an already opened connection for such hosts. While this is great for performance, it comes at a price: such vhosts need more care in their configuration. The problem is that you will have multiple requests for multiple hosts on the same TLS connection. And that makes renegotiation impossible, in face the HTTP/2 standard forbids it. So, if you have several virtual hosts using the same certificate and want to use HTTP/2 for them, you need to make sure that all vhosts have exactly the same SSL configuration. You need the same protocol, ciphers and settings for client verification. If you mix things, Apache httpd will detect it and return a special response code, 421 Misdirected Request, to the client. ### Environment Variables This module can be configured to provide HTTP/2 related information as additional environment variables to the SSI and CGI namespace, as well as in custom log configurations (see `%{VAR_NAME}e`). | Variable Name: | Value Type: | Description: | | --- | --- | --- | | `HTTP2` | flag | HTTP/2 is being used. | | `H2PUSH` | flag | HTTP/2 Server Push is enabled for this connection and also supported by the client. | | `H2_PUSH` | flag | alternate name for `H2PUSH` | | `H2_PUSHED` | string | empty or `PUSHED` for a request being pushed by the server. | | `H2_PUSHED_ON` | number | HTTP/2 stream number that triggered the push of this request. | | `H2_STREAM_ID` | number | HTTP/2 stream number of this request. | | `H2_STREAM_TAG` | string | HTTP/2 process unique stream identifier, consisting of connection id and stream id separated by `-`. | H2CopyFiles Directive --------------------- | | | | --- | --- | | Description: | Determine file handling in responses | | Syntax: | ``` H2CopyFiles on|off ``` | | Default: | ``` H2CopyFiles off ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_http2 | | Compatibility: | Available in version 2.4.24 and later. | This directive influences how file content is handled in responses. When `off`, which is the default, file handles are passed from the requestion processing down to the main connection, using the usual Apache setaside handling for managing the lifetime of the file. When set to `on`, file content is copied while the request is still being processed and the buffered data is passed on to the main connection. This is better if a third party module is injecting files with different lifetimes into the response. An example for such a module is `mod_wsgi` that may place Python file handles into the response. Those files get close down when Python thinks processing has finished. That may be well before `<mod_http2>` is done with them. H2Direct Directive ------------------ | | | | --- | --- | | Description: | H2 Direct Protocol Switch | | Syntax: | ``` H2Direct on|off ``` | | Default: | ``` H2Direct on for h2c, off for h2 protocol ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | This directive toggles the usage of the HTTP/2 Direct Mode. This should be used inside a `[<VirtualHost>](core#virtualhost)` section to enable direct HTTP/2 communication for that virtual host. Direct communication means that if the first bytes received by the server on a connection match the HTTP/2 preamble, the HTTP/2 protocol is switched to immediately without further negotiation. This mode is defined in RFC 7540 for the cleartext (h2c) case. Its use on TLS connections not mandated by the standard. When a server/vhost does not have h2 or h2c enabled via `[Protocols](core#protocols)`, the connection is never inspected for a HTTP/2 preamble. `H2Direct` does not matter then. This is important for connections that use protocols where an initial read might hang indefinitely, such as NNTP. For clients that have out-of-band knowledge about a server supporting h2c, direct HTTP/2 saves the client from having to perform an HTTP/1.1 upgrade, resulting in better performance and avoiding the Upgrade restrictions on request bodies. This makes direct h2c attractive for server to server communication as well, when the connection can be trusted or is secured by other means. ### Example ``` H2Direct on ``` H2EarlyHints Directive ---------------------- | | | | --- | --- | | Description: | Determine sending of 103 status codes | | Syntax: | ``` H2EarlyHints on|off ``` | | Default: | ``` H2EarlyHints off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | | Compatibility: | Available in version 2.4.24 and later. | This setting controls if HTTP status 103 interim responses are forwarded to the client or not. By default, this is currently not the case since a range of clients still have trouble with unexpected interim responses. When set to `on`, PUSH resources announced with `H2PushResource` will trigger an interim 103 response before the final response. The 103 response will carry `Link` headers that advise the `preload` of such resources. H2MaxSessionStreams Directive ----------------------------- | | | | --- | --- | | Description: | Maximum number of active streams per HTTP/2 session. | | Syntax: | ``` H2MaxSessionStreams n ``` | | Default: | ``` H2MaxSessionStreams 100 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | This directive sets the maximum number of active streams per HTTP/2 session (e.g. connection) that the server allows. A stream is active if it is not `idle` or `closed` according to RFC 7540. ### Example ``` H2MaxSessionStreams 20 ``` H2MaxWorkerIdleSeconds Directive -------------------------------- | | | | --- | --- | | Description: | Maximum number of seconds h2 workers remain idle until shut down. | | Syntax: | ``` H2MaxWorkerIdleSeconds n ``` | | Default: | ``` H2MaxWorkerIdleSeconds 600 ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_http2 | This directive sets the maximum number of seconds a h2 worker may idle until it shuts itself down. This only happens while the number of h2 workers exceeds `[H2MinWorkers](#h2minworkers)`. ### Example ``` H2MaxWorkerIdleSeconds 20 ``` H2MaxWorkers Directive ---------------------- | | | | --- | --- | | Description: | Maximum number of worker threads to use per child process. | | Syntax: | ``` H2MaxWorkers n ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_http2 | This directive sets the maximum number of worker threads to spawn per child process for HTTP/2 processing. If this directive is not used, `<mod_http2>` will chose a value suitable for the `mpm` module loaded. ### Example ``` H2MaxWorkers 20 ``` H2MinWorkers Directive ---------------------- | | | | --- | --- | | Description: | Minimal number of worker threads to use per child process. | | Syntax: | ``` H2MinWorkers n ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_http2 | This directive sets the minimum number of worker threads to spawn per child process for HTTP/2 processing. If this directive is not used, `<mod_http2>` will chose a value suitable for the `mpm` module loaded. ### Example ``` H2MinWorkers 10 ``` H2ModernTLSOnly Directive ------------------------- | | | | --- | --- | | Description: | Require HTTP/2 connections to be "modern TLS" only | | Syntax: | ``` H2ModernTLSOnly on|off ``` | | Default: | ``` H2ModernTLSOnly on ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | | Compatibility: | Available in version 2.4.18 and later. | This directive toggles the security checks on HTTP/2 connections in TLS mode (https:). This can be used server wide or for specific `[<VirtualHost>](core#virtualhost)`s. The security checks require that the TSL protocol is at least TLSv1.2 and that none of the ciphers listed in RFC 7540, Appendix A is used. These checks will be extended once new security requirements come into place. The name stems from the [Security/Server Side TLS](https://wiki.mozilla.org/Security/Server_Side_TLS) definitions at mozilla where "modern compatibility" is defined. Mozilla Firefox and other browsers require modern compatibility for HTTP/2 connections. As everything in OpSec, this is a moving target and can be expected to evolve in the future. One purpose of having these checks in `<mod_http2>` is to enforce this security level for all connections, not only those from browsers. The other purpose is to prevent the negotiation of HTTP/2 as a protocol should the requirements not be met. Ultimately, the security of the TLS connection is determined by the server configuration directives for `<mod_ssl>`. ### Example ``` H2ModernTLSOnly off ``` H2OutputBuffering Directive --------------------------- | | | | --- | --- | | Description: | Determine buffering behaviour of output | | Syntax: | ``` H2OutputBuffering on/off ``` | | Default: | ``` H2OutputBuffering on ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | | Compatibility: | Available in version 2.4.48 and later. | The option 'H2OutputBuffering on/off' controls the buffering of stream output. The default is on, which is the behaviour of previous versions. When off, all bytes are made available immediately to the main connection for sending them out to the client. This fixes interop issues with certain flavours of gRPC. H2Padding Directive ------------------- | | | | --- | --- | | Description: | Determine the range of padding bytes added to payload frames | | Syntax: | ``` H2Padding numbits ``` | | Default: | ``` H2Padding 0 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | | Compatibility: | Available in version 2.4.39 and later. | With the default 0, no padding bytes are added to any payload frames, e.g. HEADERS, DATA and PUSH\_PROMISE. This is the behaviour of previous versions. It means that under certain conditions, an observer of network traffic can see the length of those frames in the TLS stream. When configuring numbits of 1-8, a random number in range [0, 2^numbits[ are added to each frame. The random value is chosen independently for each frame that the module sends back to the client. While more padding bytes give better message length obfuscation, they are also additional traffic. The optimal number therefore depends on the kind of web traffic the server carries. The default of 0, e.g. no padding, was chosen for maximum backward compatibility. There might be deployments where padding bytes are unwanted or do harm. The most likely cause would be a client that has a faults implementation. H2Push Directive ---------------- | | | | --- | --- | | Description: | H2 Server Push Switch | | Syntax: | ``` H2Push on|off ``` | | Default: | ``` H2Push on ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_http2 | | Compatibility: | Available in version 2.4.18 and later. | This directive toggles the usage of the HTTP/2 server push protocol feature. The HTTP/2 protocol allows the server to push other resources to a client when it asked for a particular one. This is helpful if those resources are connected in some way and the client can be expected to ask for it anyway. The pushing then saves the time it takes the client to ask for the resources itself. On the other hand, pushing resources the client never needs or already has is a waste of bandwidth. Server pushes are detected by inspecting the `Link` headers of responses (see https://tools.ietf.org/html/rfc5988 for the specification). When a link thus specified has the `rel=preload` attribute, it is treated as a resource to be pushed. Link headers in responses are either set by the application or can be configured via `H2PushResource` or using `<mod_headers>` as: ### mod\_headers example ``` <Location /index.html> Header add Link "</css/site.css>;rel=preload" Header add Link "</images/logo.jpg>;rel=preload" </Location> ``` As the example shows, there can be several link headers added to a response, resulting in several pushes being triggered. There are no checks in the module to avoid pushing the same resource twice or more to one client. Use with care. HTTP/2 server pushes are enabled by default. On a server or virtual host, you may enable/disable this feature for any connection to the host. In addition, you may disable PUSH for a set of resources in a Directory/Location. This controls which resources may cause a PUSH, not which resources may be sent via PUSH. ### Example ``` H2Push off ``` Last but not least, pushes happen only when the client signals its willingness to accept those. Most browsers do, some, like Safari 9, do not. Also, pushes also only happen for resources from the same *authority* as the original response is for. H2PushDiarySize Directive ------------------------- | | | | --- | --- | | Description: | H2 Server Push Diary Size | | Syntax: | ``` H2PushDiarySize n ``` | | Default: | ``` H2PushDiarySize 256 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | | Compatibility: | Available in version 2.4.19 and later. | This directive toggles the maximum number of HTTP/2 server pushes that are remembered per HTTP/2 connection. This can be used inside the `[<VirtualHost>](core#virtualhost)` section to influence the number for all connections to that virtual host. The push diary records a digest (currently using a 64 bit number) of pushed resources (their URL) to avoid duplicate pushes on the same connection. These value are not persisted, so clients opening a new connection will experience known pushes again. There is ongoing work to enable a client to disclose a digest of the resources it already has, so the diary maybe initialized by the client on each connection setup. If the maximum size is reached, newer entries replace the oldest ones. A diary entry uses 8 bytes, letting a default diary with 256 entries consume around 2 KB of memory. A size of 0 will effectively disable the push diary. H2PushPriority Directive ------------------------ | | | | --- | --- | | Description: | H2 Server Push Priority | | Syntax: | ``` H2PushPriority mime-type [after|before|interleaved] [weight] ``` | | Default: | ``` H2PushPriority * After 16 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | | Compatibility: | Available in version 2.4.18 and later. For having an effect, a nghttp2 library version 1.5.0 or newer is necessary. | This directive defines the priority handling of pushed responses based on the content-type of the response. This is usually defined per server config, but may also appear in a virtual host. HTTP/2 server pushes are always related to a client request. Each such request/response pairs, or *streams* have a dependency and a weight, together defining the *priority* of a stream. When a stream *depends* on another, say X depends on Y, then Y gets all bandwidth before X gets any. Note that this does not mean that Y will block X. If Y has no data to send, all bandwidth allocated to Y can be used by X. When a stream has more than one dependent, say X1 and X2 both depend on Y, the *weight* determines the bandwidth allocation. If X1 and X2 have the same weight, they both get half of the available bandwidth. If the weight of X1 is twice as large as that for X2, X1 gets twice the bandwidth of X2. Ultimately, every stream depends on the *root* stream which gets all the bandwidth available, but never sends anything. So all its bandwidth is distributed by weight among its children. Which either have data to send or distribute the bandwidth to their own children. And so on. If none of the children have data to send, that bandwidth get distributed somewhere else according to the same rules. The purpose of this priority system is to always make use of available bandwidth while allowing precedence and weight to be given to specific streams. Since, normally, all streams are initiated by the client, it is also the one that sets these priorities. Only when such a stream results in a PUSH, gets the server to decide what the *initial* priority of such a pushed stream is. In the examples below, X is the client stream. It depends on Y and the server decides to PUSH streams P1 and P2 onto X. The default priority rule is: ### Default Priority Rule ``` H2PushPriority * After 16 ``` which reads as 'Send a pushed stream of any content-type depending on the client stream with weight 16'. And so P1 and P2 will be send after X and, as they have equal weight, share bandwidth equally among themselves. ### Interleaved Priority Rule ``` H2PushPriority text/css Interleaved 256 ``` which reads as 'Send any CSS resource on the same dependency and weight as the client stream'. If P1 has content-type 'text/css', it will depend on Y (as does X) and its effective weight will be calculated as `P1ew = Xw * (P1w / 256)`. With P1w being 256, this will make the effective weight the same as the weight of X. If both X and P1 have data to send, bandwidth will be allocated to both equally. With Pw specified as 512, a pushed, interleaved stream would get double the weight of X. With 128 only half as much. Note that effective weights are always capped at 256. ### Before Priority Rule ``` H2PushPriority application/json Before ``` This says that any pushed stream of content type 'application/json' should be send out *before* X. This makes P1 dependent on Y and X dependent on P1. So, X will be stalled as long as P1 has data to send. The effective weight is inherited from the client stream. Specifying a weight is not allowed. Be aware that the effect of priority specifications is limited by the available server resources. If a server does not have workers available for pushed streams, the data for the stream may only ever arrive when other streams have been finished. Last, but not least, there are some specifics of the syntax to be used in this directive: 1. '\*' is the only special content-type that matches all others. 'image/\*' will not work. 2. The default dependency is 'After'. 3. There are also default weights: for 'After' it is 16, 'interleaved' is 256. ### Shorter Priority Rules ``` H2PushPriority application/json 32 # an After rule H2PushPriority image/jpeg before # weight inherited H2PushPriority text/css interleaved # weight 256 default ``` H2PushResource Directive ------------------------ | | | | --- | --- | | Description: | Declares resources for early pushing to the client | | Syntax: | ``` H2PushResource [add] path [critical] ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_http2 | | Compatibility: | Available in version 2.4.24 and later. | When added to a directory/location HTTP/2 PUSHes will be attempted for all paths added via this directive. This directive can be used several times for the same location. This directive pushes resources much earlier than adding `Link` headers via `<mod_headers>`. `<mod_http2>` announces these resources in a `103 Early Hints` interim response to the client. That means that clients not supporting PUSH will still get early preload hints. In contrast to setting `Link` response headers via `<mod_headers>`, this directive will only take effect on HTTP/2 connections. By adding `critical` to such a resource, the server will give processing it more preference and send its data, once available, before the data from the main request. H2SerializeHeaders Directive ---------------------------- | | | | --- | --- | | Description: | Serialize Request/Response Processing Switch | | Syntax: | ``` H2SerializeHeaders on|off ``` | | Default: | ``` H2SerializeHeaders off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | This directive toggles if HTTP/2 requests shall be serialized in HTTP/1.1 format for processing by `httpd` core or if received binary data shall be passed into the `request_rec`s directly. Serialization will lower performance, but gives more backward compatibility in case custom filters/hooks need it. ### Example ``` H2SerializeHeaders on ``` H2StreamMaxMemSize Directive ---------------------------- | | | | --- | --- | | Description: | Maximum amount of output data buffered per stream. | | Syntax: | ``` H2StreamMaxMemSize bytes ``` | | Default: | ``` H2StreamMaxMemSize 65536 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | This directive sets the maximum number of outgoing data bytes buffered in memory for an active streams. This memory is not allocated per stream as such. Allocations are counted against this limit when they are about to be done. Stream processing freezes when the limit has been reached and will only continue when buffered data has been sent out to the client. ### Example ``` H2StreamMaxMemSize 128000 ``` H2TLSCoolDownSecs Directive --------------------------- | | | | --- | --- | | Description: | Configure the number of seconds of idle time on TLS before shrinking writes | | Syntax: | ``` H2TLSCoolDownSecs seconds ``` | | Default: | ``` H2TLSCoolDownSecs 1 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | | Compatibility: | Available in version 2.4.18 and later. | This directive sets the number of seconds of idle time on a TLS connection before the TLS write size falls back to small (~1300 bytes) length. This can be used server wide or for specific `[<VirtualHost>](core#virtualhost)`s. See `[H2TLSWarmUpSize](#h2tlswarmupsize)` for a description of TLS warmup. `H2TLSCoolDownSecs` reflects the fact that connections may deteriorate over time (and TCP flow adjusts) for idle connections as well. It is beneficial to overall performance to fall back to the pre-warmup phase after a number of seconds that no data has been sent. In deployments where connections can be considered reliable, this timer can be disabled by setting it to 0. The following example sets the seconds to zero, effectively disabling any cool down. Warmed up TLS connections stay on maximum record size. ### Example ``` H2TLSCoolDownSecs 0 ``` H2TLSWarmUpSize Directive ------------------------- | | | | --- | --- | | Description: | Configure the number of bytes on TLS connection before doing max writes | | Syntax: | ``` H2TLSWarmUpSize amount ``` | | Default: | ``` H2TLSWarmUpSize 1048576 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | | Compatibility: | Available in version 2.4.18 and later. | This directive sets the number of bytes to be sent in small TLS records (~1300 bytes) until doing maximum sized writes (16k) on https: HTTP/2 connections. This can be used server wide or for specific `[<VirtualHost>](core#virtualhost)`s. Measurements by [google performance labs](https://www.igvita.com) show that best performance on TLS connections is reached, if initial record sizes stay below the MTU level, to allow a complete record to fit into an IP packet. While TCP adjust its flow-control and window sizes, longer TLS records can get stuck in queues or get lost and need retransmission. This is of course true for all packets. TLS however needs the whole record in order to decrypt it. Any missing bytes at the end will stall usage of the received ones. After a sufficient number of bytes have been send successfully, the TCP state of the connection is stable and maximum TLS record sizes (16 KB) can be used for optimal performance. In deployments where servers are reached locally or over reliable connections only, the value might be decreased with 0 disabling any warmup phase altogether. The following example sets the size to zero, effectively disabling any warmup phase. ### Example ``` H2TLSWarmUpSize 0 ``` H2Upgrade Directive ------------------- | | | | --- | --- | | Description: | H2 Upgrade Protocol Switch | | Syntax: | ``` H2Upgrade on|off ``` | | Default: | ``` H2Upgrade on for h2c, off for h2 protocol ``` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Extension | | Module: | mod\_http2 | This directive toggles the usage of the HTTP/1.1 Upgrade method for switching to HTTP/2. This should be used inside a `[<VirtualHost>](core#virtualhost)` section to enable Upgrades to HTTP/2 for that virtual host. This method of switching protocols is defined in HTTP/1.1 and uses the "Upgrade" header (thus the name) to announce willingness to use another protocol. This may happen on any request of a HTTP/1.1 connection. This method of protocol switching is enabled by default on cleartext (potential h2c) connections and disabled on TLS (potential h2), as mandated by RFC 7540. Please be aware that Upgrades are only accepted for requests that carry no body. POSTs and PUTs with content will never trigger an upgrade to HTTP/2. See `[H2Direct](#h2direct)` for an alternative to Upgrade. This mode only has an effect when h2 or h2c is enabled via the `[Protocols](core#protocols)`. ### Example ``` H2Upgrade on ``` H2WindowSize Directive ---------------------- | | | | --- | --- | | Description: | Size of Stream Window for upstream data. | | Syntax: | ``` H2WindowSize bytes ``` | | Default: | ``` H2WindowSize 65535 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_http2 | This directive sets the size of the window that is used for flow control from client to server and limits the amount of data the server has to buffer. The client will stop sending on a stream once the limit has been reached until the server announces more available space (as it has processed some of the data). This limit affects only request bodies, not its meta data such as headers. Also, it has no effect on response bodies as the window size for those are managed by the clients. ### Example ``` H2WindowSize 128000 ```
programming_docs
apache_http_server Apache Module mod_authn_anon Apache Module mod\_authn\_anon ============================== | | | | --- | --- | | Description: | Allows "anonymous" user access to authenticated areas | | Status: | Extension | | Module Identifier: | authn\_anon\_module | | Source File: | mod\_authn\_anon.c | | Compatibility: | Available in Apache 2.1 and later | ### Summary This module provides authentication front-ends such as `<mod_auth_basic>` to authenticate users similar to anonymous-ftp sites, *i.e.* have a 'magic' user id 'anonymous' and the email address as a password. These email addresses can be logged. Combined with other (database) access control methods, this allows for effective user tracking and customization according to a user profile while still keeping the site open for 'unregistered' users. One advantage of using Auth-based user tracking is that, unlike magic-cookies and funny URL pre/postfixes, it is completely browser independent and it allows users to share URLs. When using `<mod_auth_basic>`, this module is invoked via the `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` directive with the `anon` value. Example ------- The example below is combined with "normal" htpasswd-file based authentication and allows users in additionally as 'guests' with the following properties: * It insists that the user enters a userID. (`[Anonymous\_NoUserID](#anonymous_nouserid)`) * It insists that the user enters a password. (`[Anonymous\_MustGiveEmail](#anonymous_mustgiveemail)`) * The password entered must be a valid email address, *i.e.* contain at least one '@' and a '.'. (`[Anonymous\_VerifyEmail](#anonymous_verifyemail)`) * The userID must be one of `anonymous guest www test welcome` and comparison is **not** case sensitive. (`[Anonymous](#anonymous)`) * And the Email addresses entered in the passwd field are logged to the error log file. (`[Anonymous\_LogEmail](#anonymous_logemail)`) ### Example ``` <Directory "/var/www/html/private"> AuthName "Use 'anonymous' & Email address for guest entry" AuthType Basic AuthBasicProvider file anon AuthUserFile "/path/to/your/.htpasswd" Anonymous_NoUserID off Anonymous_MustGiveEmail on Anonymous_VerifyEmail on Anonymous_LogEmail on Anonymous anonymous guest www test welcome Require valid-user </Directory> ``` Anonymous Directive ------------------- | | | | --- | --- | | Description: | Specifies userIDs that are allowed access without password verification | | Syntax: | ``` Anonymous user [user] ... ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authn\_anon | A list of one or more 'magic' userIDs which are allowed access without password verification. The userIDs are space separated. It is possible to use the ' and " quotes to allow a space in a userID as well as the \ escape character. Please note that the comparison is **case-IN-sensitive**. It's strongly recommended that the magic username '`anonymous`' is always one of the allowed userIDs. ### Example: ``` Anonymous anonymous "Not Registered" "I don't know" ``` This would allow the user to enter without password verification by using the userIDs "anonymous", "AnonyMous", "Not Registered" and "I Don't Know". As of Apache 2.1 it is possible to specify the userID as "`*`". That allows *any* supplied userID to be accepted. Anonymous\_LogEmail Directive ----------------------------- | | | | --- | --- | | Description: | Sets whether the password entered will be logged in the error log | | Syntax: | ``` Anonymous_LogEmail On|Off ``` | | Default: | ``` Anonymous_LogEmail On ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authn\_anon | When set `On`, the default, the 'password' entered (which hopefully contains a sensible email address) is logged in the error log. Anonymous\_MustGiveEmail Directive ---------------------------------- | | | | --- | --- | | Description: | Specifies whether blank passwords are allowed | | Syntax: | ``` Anonymous_MustGiveEmail On|Off ``` | | Default: | ``` Anonymous_MustGiveEmail On ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authn\_anon | Specifies whether the user must specify an email address as the password. This prohibits blank passwords. Anonymous\_NoUserID Directive ----------------------------- | | | | --- | --- | | Description: | Sets whether the userID field may be empty | | Syntax: | ``` Anonymous_NoUserID On|Off ``` | | Default: | ``` Anonymous_NoUserID Off ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authn\_anon | When set `On`, users can leave the userID (and perhaps the password field) empty. This can be very convenient for MS-Explorer users who can just hit return or click directly on the OK button; which seems a natural reaction. Anonymous\_VerifyEmail Directive -------------------------------- | | | | --- | --- | | Description: | Sets whether to check the password field for a correctly formatted email address | | Syntax: | ``` Anonymous_VerifyEmail On|Off ``` | | Default: | ``` Anonymous_VerifyEmail Off ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authn\_anon | When set `On` the 'password' entered is checked for at least one '@' and a '.' to encourage users to enter valid email addresses (see the above `[Anonymous\_LogEmail](#anonymous_logemail)`). apache_http_server Apache Module mod_reflector Apache Module mod\_reflector ============================ | | | | --- | --- | | Description: | Reflect a request body as a response via the output filter stack. | | Status: | Base | | Module Identifier: | reflector\_module | | Source File: | mod\_reflector.c | | Compatibility: | Version 2.3 and later | ### Summary This module allows request bodies to be reflected back to the client, in the process passing the request through the output filter stack. A suitably configured chain of filters can be used to transform the request into a response. This module can be used to turn an output filter into an HTTP service. Examples -------- Compression service Pass the request body through the DEFLATE filter to compress the body. This request requires a Content-Encoding request header containing "gzip" for the filter to return compressed data. ``` <Location "/compress"> SetHandler reflector SetOutputFilter DEFLATE </Location> ``` Image downsampling service Pass the request body through an image downsampling filter, and reflect the results to the caller. ``` <Location "/downsample"> SetHandler reflector SetOutputFilter DOWNSAMPLE </Location> ``` ReflectorHeader Directive ------------------------- | | | | --- | --- | | Description: | Reflect an input header to the output headers | | Syntax: | ``` ReflectorHeader inputheader [outputheader] ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Options | | Status: | Base | | Module: | mod\_reflector | This directive controls the reflection of request headers to the response. The first argument is the name of the request header to copy. If the optional second argument is specified, it will be used as the name of the response header, otherwise the original request header name will be used. apache_http_server Apache Module mod_ext_filter Apache Module mod\_ext\_filter ============================== | | | | --- | --- | | Description: | Pass the response body through an external program before delivery to the client | | Status: | Extension | | Module Identifier: | ext\_filter\_module | | Source File: | mod\_ext\_filter.c | ### Summary `<mod_ext_filter>` presents a simple and familiar programming model for [filters](../filter). With this module, a program which reads from stdin and writes to stdout (i.e., a Unix-style filter command) can be a filter for Apache. This filtering mechanism is much slower than using a filter which is specially written for the Apache API and runs inside of the Apache server process, but it does have the following benefits: * the programming model is much simpler * any programming/scripting language can be used, provided that it allows the program to read from standard input and write to standard output * existing programs can be used unmodified as Apache filters Even when the performance characteristics are not suitable for production use, `<mod_ext_filter>` can be used as a prototype environment for filters. Examples -------- ### Generating HTML from some other type of response ``` # mod_ext_filter directive to define a filter # to HTML-ize text/c files using the external # program /usr/bin/enscript, with the type of # the result set to text/html ExtFilterDefine c-to-html mode=output \ intype=text/c outtype=text/html \ cmd="/usr/bin/enscript --color -w html -Ec -o -" <Directory "/export/home/trawick/apacheinst/htdocs/c"> # core directive to cause the new filter to # be run on output SetOutputFilter c-to-html # mod_mime directive to set the type of .c # files to text/c AddType text/c .c </Directory> ``` ### Implementing a content encoding filter Note: this gzip example is just for the purposes of illustration. Please refer to `<mod_deflate>` for a practical implementation. ``` # mod_ext_filter directive to define the external filter ExtFilterDefine gzip mode=output cmd=/bin/gzip <Location "/gzipped"> # core directive to cause the gzip filter to be # run on output SetOutputFilter gzip # mod_headers directive to add # "Content-Encoding: gzip" header field Header set Content-Encoding gzip </Location> ``` ### Slowing down the server ``` # mod_ext_filter directive to define a filter # which runs everything through cat; cat doesn't # modify anything; it just introduces extra pathlength # and consumes more resources ExtFilterDefine slowdown mode=output cmd=/bin/cat \ preservescontentlength <Location "/"> # core directive to cause the slowdown filter to # be run several times on output # SetOutputFilter slowdown;slowdown;slowdown </Location> ``` ### Using sed to replace text in the response ``` # mod_ext_filter directive to define a filter which # replaces text in the response # ExtFilterDefine fixtext mode=output intype=text/html \ cmd="/bin/sed s/verdana/arial/g" <Location "/"> # core directive to cause the fixtext filter to # be run on output SetOutputFilter fixtext </Location> ``` You can do the same thing using `<mod_substitute>` without invoking an external process. ### Tracing another filter ``` # Trace the data read and written by mod_deflate # for a particular client (IP 192.168.1.31) # experiencing compression problems. # This filter will trace what goes into mod_deflate. ExtFilterDefine tracebefore \ cmd="/bin/tracefilter.pl /tmp/tracebefore" \ EnableEnv=trace_this_client # This filter will trace what goes after mod_deflate. # Note that without the ftype parameter, the default # filter type of AP_FTYPE_RESOURCE would cause the # filter to be placed *before* mod_deflate in the filter # chain. Giving it a numeric value slightly higher than # AP_FTYPE_CONTENT_SET will ensure that it is placed # after mod_deflate. ExtFilterDefine traceafter \ cmd="/bin/tracefilter.pl /tmp/traceafter" \ EnableEnv=trace_this_client ftype=21 <Directory "/usr/local/docs"> SetEnvIf Remote_Addr 192.168.1.31 trace_this_client SetOutputFilter tracebefore;deflate;traceafter </Directory> ``` ### Here is the filter which traces the data: ``` #!/usr/local/bin/perl -w use strict; open(SAVE, ">$ARGV[0]") or die "can't open $ARGV[0]: $?"; while (<STDIN>) { print SAVE $_; print $_; } close(SAVE); ``` ExtFilterDefine Directive ------------------------- | | | | --- | --- | | Description: | Define an external filter | | Syntax: | ``` ExtFilterDefine filtername parameters ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ext\_filter | The `ExtFilterDefine` directive defines the characteristics of an external filter, including the program to run and its arguments. filtername specifies the name of the filter being defined. This name can then be used in `[SetOutputFilter](core#setoutputfilter)` directives. It must be unique among all registered filters. *At the present time, no error is reported by the register-filter API, so a problem with duplicate names isn't reported to the user.* Subsequent parameters can appear in any order and define the external command to run and certain other characteristics. The only required parameter is `cmd=`. These parameters are: `cmd=cmdline` The `cmd=` keyword allows you to specify the external command to run. If there are arguments after the program name, the command line should be surrounded in quotation marks (*e.g.*, `cmd="/bin/mypgm arg1 arg2"`.) Normal shell quoting is not necessary since the program is run directly, bypassing the shell. Program arguments are blank-delimited. A backslash can be used to escape blanks which should be part of a program argument. Any backslashes which are part of the argument must be escaped with backslash themselves. In addition to the standard CGI environment variables, DOCUMENT\_URI, DOCUMENT\_PATH\_INFO, and QUERY\_STRING\_UNESCAPED will also be set for the program. `mode=mode` Use `mode=output` (the default) for filters which process the response. Use `mode=input` for filters which process the request. `mode=input` is available in Apache 2.1 and later. `intype=imt` This parameter specifies the internet media type (*i.e.*, MIME type) of documents which should be filtered. By default, all documents are filtered. If `intype=` is specified, the filter will be disabled for documents of other types. `outtype=imt` This parameter specifies the internet media type (*i.e.*, MIME type) of filtered documents. It is useful when the filter changes the internet media type as part of the filtering operation. By default, the internet media type is unchanged. `PreservesContentLength` The `PreservesContentLength` keyword specifies that the filter preserves the content length. This is not the default, as most filters change the content length. In the event that the filter doesn't modify the length, this keyword should be specified. `ftype=filtertype` This parameter specifies the numeric value for filter type that the filter should be registered as. The default value, AP\_FTYPE\_RESOURCE, is sufficient in most cases. If the filter needs to operate at a different point in the filter chain than resource filters, then this parameter will be necessary. See the AP\_FTYPE\_foo definitions in util\_filter.h for appropriate values. `disableenv=env` This parameter specifies the name of an environment variable which, if set, will disable the filter. `enableenv=env` This parameter specifies the name of an environment variable which must be set, or the filter will be disabled. ExtFilterOptions Directive -------------------------- | | | | --- | --- | | Description: | Configure `<mod_ext_filter>` options | | Syntax: | ``` ExtFilterOptions option [option] ... ``` | | Default: | ``` ExtFilterOptions NoLogStderr ``` | | Context: | directory | | Status: | Extension | | Module: | mod\_ext\_filter | The `ExtFilterOptions` directive specifies special processing options for `<mod_ext_filter>`. Option can be one of `LogStderr | NoLogStderr` The `LogStderr` keyword specifies that messages written to standard error by the external filter program will be saved in the Apache error log. `NoLogStderr` disables this feature. `Onfail=[abort|remove]` Determines how to proceed if the external filter program cannot be started. With `abort` (the default value) the request will be aborted. With `remove`, the filter is removed and the request continues without it. ``` ExtFilterOptions LogStderr ``` Messages written to the filter's standard error will be stored in the Apache error log. apache_http_server Apache Module mod_example_hooks Apache Module mod\_example\_hooks ================================= | | | | --- | --- | | Description: | Illustrates the Apache module API | | Status: | Experimental | | Module Identifier: | example\_hooks\_module | | Source File: | mod\_example\_hooks.c | ### Summary The files in the `modules/examples` directory under the Apache distribution directory tree are provided as an example to those that wish to write modules that use the Apache API. The main file is `mod_example_hooks.c`, which illustrates all the different callback mechanisms and call syntaxes. By no means does an add-on module need to include routines for all of the callbacks - quite the contrary! The example module is an actual working module. If you link it into your server, enable the "example-hooks-handler" handler for a location, and then browse to that location, you will see a display of some of the tracing the example module did as the various callbacks were made. Compiling the example\_hooks module ----------------------------------- To include the example\_hooks module in your server, follow the steps below: 1. Run `[configure](../programs/configure)` with `--enable-example-hooks` option. 2. Make the server (run "`make`"). To add another module of your own: 1. `cp modules/examples/mod_example_hooks.c modules/new_module/*mod\_myexample.c*` 2. Modify the file. 3. Create `modules/new_module/config.m4`. 1. Add `APACHE_MODPATH_INIT(new_module)`. 2. Copy APACHE\_MODULE line with "example\_hooks" from `modules/examples/config.m4`. 3. Replace the first argument "example\_hooks" with *myexample*. 4. Replace the second argument with brief description of your module. It will be used in `configure --help`. 5. If your module needs additional C compiler flags, linker flags or libraries, add them to CFLAGS, LDFLAGS and LIBS accordingly. See other `config.m4` files in modules directory for examples. 6. Add `APACHE_MODPATH_FINISH`. 4. Create `module/new_module/Makefile.in`. If your module doesn't need special build instructions, all you need to have in that file is `include $(top_srcdir)/build/special.mk`. 5. Run ./buildconf from the top-level directory. 6. Build the server with --enable-myexample Using the `mod_example_hooks` Module ------------------------------------ To activate the example\_hooks module, include a block similar to the following in your `httpd.conf` file: ``` <Location "/example-hooks-info"> SetHandler example-hooks-handler </Location> ``` As an alternative, you can put the following into a [`.htaccess`](core#accessfilename) file and then request the file "test.example" from that location: ``` AddHandler example-hooks-handler ".example" ``` After reloading/restarting your server, you should be able to browse to this location and see the brief display mentioned earlier. Example Directive ----------------- | | | | --- | --- | | Description: | Demonstration directive to illustrate the Apache module API | | Syntax: | `Example` | | Context: | server config, virtual host, directory, .htaccess | | Status: | Experimental | | Module: | mod\_example\_hooks | The `Example` directive just sets a demonstration flag which the example module's content handler displays. It takes no arguments. If you browse to an URL to which the example-hooks content-handler applies, you will get a display of the routines within the module and how and in what order they were called to service the document request. The effect of this directive one can observe under the point "`Example directive declared here: YES/NO`". apache_http_server Apache Module mod_slotmem_plain Apache Module mod\_slotmem\_plain ================================= | | | | --- | --- | | Description: | Slot-based shared memory provider. | | Status: | Extension | | Module Identifier: | slotmem\_plain\_module | | Source File: | mod\_slotmem\_plain.c | ### Summary `<mod_slotmem_plain>` is a memory provider which provides for creation and access to a plain memory segment in which the datasets are organized in "slots." If the memory needs to be shared between threads and processes, a better provider would be `<mod_slotmem_shm>`. `<mod_slotmem_plain>` provides the following API functions: ``` /* call the callback on all worker slots */ apr_status_t doall(ap_slotmem_instance_t *s, ap_slotmem_callback_fn_t *func, void *data, apr_pool_t *pool) /* create a new slotmem with each item size is item_size */ apr_status_t create(ap_slotmem_instance_t **new, const char *name, apr_size_t item_size, unsigned int item_num, ap_slotmem_type_t type, apr_pool_t *pool) /* attach to an existing slotmem */ apr_status_t attach(ap_slotmem_instance_t **new, const char *name, apr_size_t *item_size, unsigned int *item_num, apr_pool_t *pool) /* get the direct pointer to the memory associated with this worker slot */ apr_status_t dptr(ap_slotmem_instance_t *s, unsigned int item_id, void **mem) /* get/read the memory from this slot to dest */ apr_status_t get(ap_slotmem_instance_t *s, unsigned int item_id, unsigned char *dest, apr_size_t dest_len) /* put/write the data from src to this slot */ apr_status_t put(ap_slotmem_instance_t *slot, unsigned int item_id, unsigned char *src, apr_size_t src_len) /* return the total number of slots in the segment */ unsigned int num_slots(ap_slotmem_instance_t *s) /* return the total data size, in bytes, of a slot in the segment */ apr_size_t slot_size(ap_slotmem_instance_t *s) /* grab or allocate the first free slot and mark as in-use (does not do any data copying) */ apr_status_t grab(ap_slotmem_instance_t *s, unsigned int *item_id) /* forced grab or allocate the specified slot and mark as in-use (does not do any data copying) */ apr_status_t fgrab(ap_slotmem_instance_t *s, unsigned int item_id) /* release or free a slot and mark as not in-use (does not do any data copying) */ apr_status_t release(ap_slotmem_instance_t *s, unsigned int item_id) ```
programming_docs
apache_http_server Apache Module mod_ldap Apache Module mod\_ldap ======================= | | | | --- | --- | | Description: | LDAP connection pooling and result caching services for use by other LDAP modules | | Status: | Extension | | Module Identifier: | ldap\_module | | Source File: | util\_ldap.c | ### Summary This module was created to improve the performance of websites relying on backend connections to LDAP servers. In addition to the functions provided by the standard LDAP libraries, this module adds an LDAP connection pool and an LDAP shared memory cache. To enable this module, LDAP support must be compiled into apr-util. This is achieved by adding the `--with-ldap` flag to the `[configure](../programs/configure)` script when building Apache. SSL/TLS support is dependent on which LDAP toolkit has been linked to [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary"). As of this writing, APR-util supports: [OpenLDAP SDK](http://www.openldap.org/) (2.x or later), [Novell LDAP SDK](http://developer.novell.com/ndk/cldap.htm), [Mozilla LDAP SDK](https://wiki.mozilla.org/LDAP_C_SDK), native Solaris LDAP SDK (Mozilla based) or the native Microsoft LDAP SDK. See the [APR](http://apr.apache.org) website for details. Example Configuration --------------------- The following is an example configuration that uses `<mod_ldap>` to increase the performance of HTTP Basic authentication provided by `<mod_authnz_ldap>`. ``` # Enable the LDAP connection pool and shared # memory cache. Enable the LDAP cache status # handler. Requires that mod_ldap and mod_authnz_ldap # be loaded. Change the "yourdomain.example.com" to # match your domain. LDAPSharedCacheSize 500000 LDAPCacheEntries 1024 LDAPCacheTTL 600 LDAPOpCacheEntries 1024 LDAPOpCacheTTL 600 <Location "/ldap-status"> SetHandler ldap-status Require host yourdomain.example.com Satisfy any AuthType Basic AuthName "LDAP Protected" AuthBasicProvider ldap AuthLDAPURL "ldap://127.0.0.1/dc=example,dc=com?uid?one" Require valid-user </Location> ``` LDAP Connection Pool -------------------- LDAP connections are pooled from request to request. This allows the LDAP server to remain connected and bound ready for the next request, without the need to unbind/connect/rebind. The performance advantages are similar to the effect of HTTP keepalives. On a busy server it is possible that many requests will try and access the same LDAP server connection simultaneously. Where an LDAP connection is in use, Apache will create a new connection alongside the original one. This ensures that the connection pool does not become a bottleneck. There is no need to manually enable connection pooling in the Apache configuration. Any module using this module for access to LDAP services will share the connection pool. LDAP connections can keep track of the ldap client credentials used when binding to an LDAP server. These credentials can be provided to LDAP servers that do not allow anonymous binds during referral chasing. To control this feature, see the `[LDAPReferrals](#ldapreferrals)` and `[LDAPReferralHopLimit](#ldapreferralhoplimit)` directives. By default, this feature is enabled. LDAP Cache ---------- For improved performance, `<mod_ldap>` uses an aggressive caching strategy to minimize the number of times that the LDAP server must be contacted. Caching can easily double or triple the throughput of Apache when it is serving pages protected with `<mod_authnz_ldap>`. In addition, the load on the LDAP server will be significantly decreased. `<mod_ldap>` supports two types of LDAP caching during the search/bind phase with a *search/bind cache* and during the compare phase with two *operation caches*. Each LDAP URL that is used by the server has its own set of these three caches. ### The Search/Bind Cache The process of doing a search and then a bind is the most time-consuming aspect of LDAP operation, especially if the directory is large. The search/bind cache is used to cache all searches that resulted in successful binds. Negative results (*i.e.*, unsuccessful searches, or searches that did not result in a successful bind) are not cached. The rationale behind this decision is that connections with invalid credentials are only a tiny percentage of the total number of connections, so by not caching invalid credentials, the size of the cache is reduced. `<mod_ldap>` stores the username, the DN retrieved, the password used to bind, and the time of the bind in the cache. Whenever a new connection is initiated with the same username, `<mod_ldap>` compares the password of the new connection with the password in the cache. If the passwords match, and if the cached entry is not too old, `<mod_ldap>` bypasses the search/bind phase. The search and bind cache is controlled with the `[LDAPCacheEntries](#ldapcacheentries)` and `[LDAPCacheTTL](#ldapcachettl)` directives. ### Operation Caches During attribute and distinguished name comparison functions, `<mod_ldap>` uses two operation caches to cache the compare operations. The first compare cache is used to cache the results of compares done to test for LDAP group membership. The second compare cache is used to cache the results of comparisons done between distinguished names. Note that, when group membership is being checked, any sub-group comparison results are cached to speed future sub-group comparisons. The behavior of both of these caches is controlled with the `[LDAPOpCacheEntries](#ldapopcacheentries)` and `[LDAPOpCacheTTL](#ldapopcachettl)` directives. ### Monitoring the Cache `<mod_ldap>` has a content handler that allows administrators to monitor the cache performance. The name of the content handler is `ldap-status`, so the following directives could be used to access the `<mod_ldap>` cache information: ``` <Location "/server/cache-info"> SetHandler ldap-status </Location> ``` By fetching the URL `http://servername/cache-info`, the administrator can get a status report of every cache that is used by `<mod_ldap>` cache. Note that if Apache does not support shared memory, then each `[httpd](../programs/httpd)` instance has its own cache, so reloading the URL will result in different information each time, depending on which `[httpd](../programs/httpd)` instance processes the request. Using SSL/TLS ------------- The ability to create an SSL and TLS connections to an LDAP server is defined by the directives `[LDAPTrustedGlobalCert](#ldaptrustedglobalcert)`, `[LDAPTrustedClientCert](#ldaptrustedclientcert)` and `[LDAPTrustedMode](#ldaptrustedmode)`. These directives specify the CA and optional client certificates to be used, as well as the type of encryption to be used on the connection (none, SSL or TLS/STARTTLS). ``` # Establish an SSL LDAP connection on port 636. Requires that # mod_ldap and mod_authnz_ldap be loaded. Change the # "yourdomain.example.com" to match your domain. LDAPTrustedGlobalCert CA_DER "/certs/certfile.der" <Location "/ldap-status"> SetHandler ldap-status Require host yourdomain.example.com Satisfy any AuthType Basic AuthName "LDAP Protected" AuthBasicProvider ldap AuthLDAPURL "ldaps://127.0.0.1/dc=example,dc=com?uid?one" Require valid-user </Location> ``` ``` # Establish a TLS LDAP connection on port 389. Requires that # mod_ldap and mod_authnz_ldap be loaded. Change the # "yourdomain.example.com" to match your domain. LDAPTrustedGlobalCert CA_DER "/certs/certfile.der" <Location "/ldap-status"> SetHandler ldap-status Require host yourdomain.example.com Satisfy any AuthType Basic AuthName "LDAP Protected" AuthBasicProvider ldap AuthLDAPURL "ldap://127.0.0.1/dc=example,dc=com?uid?one" TLS Require valid-user </Location> ``` SSL/TLS Certificates -------------------- The different LDAP SDKs have widely different methods of setting and handling both CA and client side certificates. If you intend to use SSL or TLS, read this section CAREFULLY so as to understand the differences between configurations on the different LDAP toolkits supported. ### Netscape/Mozilla/iPlanet SDK CA certificates are specified within a file called cert7.db. The SDK will not talk to any LDAP server whose certificate was not signed by a CA specified in this file. If client certificates are required, an optional key3.db file may be specified with an optional password. The secmod file can be specified if required. These files are in the same format as used by the Netscape Communicator or Mozilla web browsers. The easiest way to obtain these files is to grab them from your browser installation. Client certificates are specified per connection using the `[LDAPTrustedClientCert](#ldaptrustedclientcert)` directive by referring to the certificate "nickname". An optional password may be specified to unlock the certificate's private key. The SDK supports SSL only. An attempt to use STARTTLS will cause an error when an attempt is made to contact the LDAP server at runtime. ``` # Specify a Netscape CA certificate file LDAPTrustedGlobalCert CA_CERT7_DB "/certs/cert7.db" # Specify an optional key3.db file for client certificate support LDAPTrustedGlobalCert CERT_KEY3_DB "/certs/key3.db" # Specify the secmod file if required LDAPTrustedGlobalCert CA_SECMOD "/certs/secmod" <Location "/ldap-status"> SetHandler ldap-status Require host yourdomain.example.com Satisfy any AuthType Basic AuthName "LDAP Protected" AuthBasicProvider ldap LDAPTrustedClientCert CERT_NICKNAME <nickname> [password] AuthLDAPURL "ldaps://127.0.0.1/dc=example,dc=com?uid?one" Require valid-user </Location> ``` ### Novell SDK One or more CA certificates must be specified for the Novell SDK to work correctly. These certificates can be specified as binary DER or Base64 (PEM) encoded files. Note: Client certificates are specified globally rather than per connection, and so must be specified with the `[LDAPTrustedGlobalCert](#ldaptrustedglobalcert)` directive as below. Trying to set client certificates via the `[LDAPTrustedClientCert](#ldaptrustedclientcert)` directive will cause an error to be logged when an attempt is made to connect to the LDAP server. The SDK supports both SSL and STARTTLS, set using the `[LDAPTrustedMode](#ldaptrustedmode)` parameter. If an ldaps:// URL is specified, SSL mode is forced, override this directive. ``` # Specify two CA certificate files LDAPTrustedGlobalCert CA_DER "/certs/cacert1.der" LDAPTrustedGlobalCert CA_BASE64 "/certs/cacert2.pem" # Specify a client certificate file and key LDAPTrustedGlobalCert CERT_BASE64 "/certs/cert1.pem" LDAPTrustedGlobalCert KEY_BASE64 "/certs/key1.pem" [password] # Do not use this directive, as it will throw an error #LDAPTrustedClientCert CERT_BASE64 "/certs/cert1.pem" ``` ### OpenLDAP SDK One or more CA certificates must be specified for the OpenLDAP SDK to work correctly. These certificates can be specified as binary DER or Base64 (PEM) encoded files. Both CA and client certificates may be specified globally (`[LDAPTrustedGlobalCert](#ldaptrustedglobalcert)`) or per-connection (`[LDAPTrustedClientCert](#ldaptrustedclientcert)`). When any settings are specified per-connection, the global settings are superseded. The documentation for the SDK claims to support both SSL and STARTTLS, however STARTTLS does not seem to work on all versions of the SDK. The SSL/TLS mode can be set using the LDAPTrustedMode parameter. If an ldaps:// URL is specified, SSL mode is forced. The OpenLDAP documentation notes that SSL (ldaps://) support has been deprecated to be replaced with TLS, although the SSL functionality still works. ``` # Specify two CA certificate files LDAPTrustedGlobalCert CA_DER "/certs/cacert1.der" LDAPTrustedGlobalCert CA_BASE64 "/certs/cacert2.pem" <Location "/ldap-status"> SetHandler ldap-status Require host yourdomain.example.com LDAPTrustedClientCert CERT_BASE64 "/certs/cert1.pem" LDAPTrustedClientCert KEY_BASE64 "/certs/key1.pem" # CA certs respecified due to per-directory client certs LDAPTrustedClientCert CA_DER "/certs/cacert1.der" LDAPTrustedClientCert CA_BASE64 "/certs/cacert2.pem" Satisfy any AuthType Basic AuthName "LDAP Protected" AuthBasicProvider ldap AuthLDAPURL "ldaps://127.0.0.1/dc=example,dc=com?uid?one" Require valid-user </Location> ``` ### Solaris SDK SSL/TLS for the native Solaris LDAP libraries is not yet supported. If required, install and use the OpenLDAP libraries instead. ### Microsoft SDK SSL/TLS certificate configuration for the native Microsoft LDAP libraries is done inside the system registry, and no configuration directives are required. Both SSL and TLS are supported by using the ldaps:// URL format, or by using the `[LDAPTrustedMode](#ldaptrustedmode)` directive accordingly. Note: The status of support for client certificates is not yet known for this toolkit. LDAPCacheEntries Directive -------------------------- | | | | --- | --- | | Description: | Maximum number of entries in the primary LDAP cache | | Syntax: | ``` LDAPCacheEntries number ``` | | Default: | ``` LDAPCacheEntries 1024 ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | Specifies the maximum size of the primary LDAP cache. This cache contains successful search/binds. Set it to 0 to turn off search/bind caching. The default size is 1024 cached searches. LDAPCacheTTL Directive ---------------------- | | | | --- | --- | | Description: | Time that cached items remain valid | | Syntax: | ``` LDAPCacheTTL seconds ``` | | Default: | ``` LDAPCacheTTL 600 ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | Specifies the time (in seconds) that an item in the search/bind cache remains valid. The default is 600 seconds (10 minutes). LDAPConnectionPoolTTL Directive ------------------------------- | | | | --- | --- | | Description: | Discard backend connections that have been sitting in the connection pool too long | | Syntax: | ``` LDAPConnectionPoolTTL n ``` | | Default: | ``` LDAPConnectionPoolTTL -1 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ldap | | Compatibility: | Apache HTTP Server 2.3.12 and later | Specifies the maximum age, in seconds, that a pooled LDAP connection can remain idle and still be available for use. Connections are cleaned up when they are next needed, not asynchronously. A setting of 0 causes connections to never be saved in the backend connection pool. The default value of -1, and any other negative value, allows connections of any age to be reused. For performance reasons, the reference time used by this directive is based on when the LDAP connection is returned to the pool, not the time of the last successful I/O with the LDAP server. Since 2.4.10, new measures are in place to avoid the reference time from being inflated by cache hits or slow requests. First, the reference time is not updated if no backend LDAP conncetions were needed. Second, the reference time uses the time the HTTP request was received instead of the time the request is completed. This timeout defaults to units of seconds, but accepts suffixes for milliseconds (ms), minutes (min), and hours (h). LDAPConnectionTimeout Directive ------------------------------- | | | | --- | --- | | Description: | Specifies the socket connection timeout in seconds | | Syntax: | ``` LDAPConnectionTimeout seconds ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | This directive configures the LDAP\_OPT\_NETWORK\_TIMEOUT (or LDAP\_OPT\_CONNECT\_TIMEOUT) option in the underlying LDAP client library, when available. This value typically controls how long the LDAP client library will wait for the TCP connection to the LDAP server to complete. If a connection is not successful with the timeout period, either an error will be returned or the LDAP client library will attempt to connect to a secondary LDAP server if one is specified (via a space-separated list of hostnames in the `[AuthLDAPURL](mod_authnz_ldap#authldapurl)`). The default is 10 seconds, if the LDAP client library linked with the server supports the LDAP\_OPT\_NETWORK\_TIMEOUT option. LDAPConnectionTimeout is only available when the LDAP client library linked with the server supports the LDAP\_OPT\_NETWORK\_TIMEOUT (or LDAP\_OPT\_CONNECT\_TIMEOUT) option, and the ultimate behavior is dictated entirely by the LDAP client library. LDAPLibraryDebug Directive -------------------------- | | | | --- | --- | | Description: | Enable debugging in the LDAP SDK | | Syntax: | ``` LDAPLibraryDebug 7 ``` | | Default: | `disabled` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | Turns on SDK-specific LDAP debug options that generally cause the LDAP SDK to log verbose trace information to the main Apache error log. The trace messages from the LDAP SDK provide gory details that can be useful during debugging of connectivity problems with backend LDAP servers This option is only configurable when Apache HTTP Server is linked with an LDAP SDK that implements `LDAP_OPT_DEBUG` or `LDAP_OPT_DEBUG_LEVEL`, such as OpenLDAP (a value of 7 is verbose) or Tivoli Directory Server (a value of 65535 is verbose). The logged information will likely contain plaintext credentials being used or validated by LDAP authentication, so care should be taken in protecting and purging the error log when this directive is used. LDAPOpCacheEntries Directive ---------------------------- | | | | --- | --- | | Description: | Number of entries used to cache LDAP compare operations | | Syntax: | ``` LDAPOpCacheEntries number ``` | | Default: | ``` LDAPOpCacheEntries 1024 ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | This specifies the number of entries `<mod_ldap>` will use to cache LDAP compare operations. The default is 1024 entries. Setting it to 0 disables operation caching. LDAPOpCacheTTL Directive ------------------------ | | | | --- | --- | | Description: | Time that entries in the operation cache remain valid | | Syntax: | ``` LDAPOpCacheTTL seconds ``` | | Default: | ``` LDAPOpCacheTTL 600 ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | Specifies the time (in seconds) that entries in the operation cache remain valid. The default is 600 seconds. LDAPReferralHopLimit Directive ------------------------------ | | | | --- | --- | | Description: | The maximum number of referral hops to chase before terminating an LDAP query. | | Syntax: | ``` LDAPReferralHopLimit number ``` | | Default: | ``` SDK dependent, typically between 5 and 10 ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_ldap | This directive, if enabled by the `[LDAPReferrals](#ldapreferrals)` directive, limits the number of referral hops that are followed before terminating an LDAP query. Support for this tunable is uncommon in LDAP SDKs. LDAPReferrals Directive ----------------------- | | | | --- | --- | | Description: | Enable referral chasing during queries to the LDAP server. | | Syntax: | ``` LDAPReferrals On|Off|default ``` | | Default: | ``` LDAPReferrals On ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_ldap | | Compatibility: | The default parameter is available in Apache 2.4.7 and later | Some LDAP servers divide their directory among multiple domains and use referrals to direct a client when a domain boundary is crossed. This is similar to a HTTP redirect. LDAP client libraries may or may not chase referrals by default. This directive explicitly configures the referral chasing in the underlying SDK. `LDAPReferrals` takes the following values: "on" When set to "on", the underlying SDK's referral chasing state is enabled, `[LDAPReferralHopLimit](#ldapreferralhoplimit)` is used to override the SDK's hop limit, and an LDAP rebind callback is registered. "off" When set to "off", the underlying SDK's referral chasing state is disabled completely. "default" When set to "default", the underlying SDK's referral chasing state is not changed, `[LDAPReferralHopLimit](#ldapreferralhoplimit)` is not used to override the SDK's hop limit, and no LDAP rebind callback is registered. The directive `[LDAPReferralHopLimit](#ldapreferralhoplimit)` works in conjunction with this directive to limit the number of referral hops to follow before terminating the LDAP query. When referral processing is enabled by a value of "On", client credentials will be provided, via a rebind callback, for any LDAP server requiring them. LDAPRetries Directive --------------------- | | | | --- | --- | | Description: | Configures the number of LDAP server retries. | | Syntax: | ``` LDAPRetries number-of-retries ``` | | Default: | ``` LDAPRetries 3 ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | The server will retry failed LDAP requests up to `LDAPRetries` times. Setting this directive to 0 disables retries. LDAP errors such as timeouts and refused connections are retryable. LDAPRetryDelay Directive ------------------------ | | | | --- | --- | | Description: | Configures the delay between LDAP server retries. | | Syntax: | ``` LDAPRetryDelay seconds ``` | | Default: | ``` LDAPRetryDelay 0 ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | If `LDAPRetryDelay` is set to a non-zero value, the server will delay retrying an LDAP request for the specified amount of time. Setting this directive to 0 will result in any retry to occur without delay. LDAP errors such as timeouts and refused connections are retryable. LDAPSharedCacheFile Directive ----------------------------- | | | | --- | --- | | Description: | Sets the shared memory cache file | | Syntax: | ``` LDAPSharedCacheFile directory-path/filename ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | Specifies the directory path and file name of the shared memory cache file. If not set, anonymous shared memory will be used if the platform supports it. LDAPSharedCacheSize Directive ----------------------------- | | | | --- | --- | | Description: | Size in bytes of the shared-memory cache | | Syntax: | ``` LDAPSharedCacheSize bytes ``` | | Default: | ``` LDAPSharedCacheSize 500000 ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | Specifies the number of bytes to allocate for the shared memory cache. The default is 500kb. If set to 0, shared memory caching will not be used and every HTTPD process will create its own cache. LDAPTimeout Directive --------------------- | | | | --- | --- | | Description: | Specifies the timeout for LDAP search and bind operations, in seconds | | Syntax: | ``` LDAPTimeout seconds ``` | | Default: | ``` LDAPTimeout 60 ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | | Compatibility: | Apache HTTP Server 2.3.5 and later | This directive configures the timeout for bind and search operations, as well as the LDAP\_OPT\_TIMEOUT option in the underlying LDAP client library, when available. If the timeout expires, httpd will retry in case an existing connection has been silently dropped by a firewall. However, performance will be much better if the firewall is configured to send TCP RST packets instead of silently dropping packets. Timeouts for ldap compare operations requires an SDK with LDAP\_OPT\_TIMEOUT, such as OpenLDAP >= 2.4.4. LDAPTrustedClientCert Directive ------------------------------- | | | | --- | --- | | Description: | Sets the file containing or nickname referring to a per connection client certificate. Not all LDAP toolkits support per connection client certificates. | | Syntax: | ``` LDAPTrustedClientCert type directory-path/filename/nickname [password] ``` | | Context: | directory, .htaccess | | Status: | Extension | | Module: | mod\_ldap | It specifies the directory path, file name or nickname of a per connection client certificate used when establishing an SSL or TLS connection to an LDAP server. Different locations or directories may have their own independent client certificate settings. Some LDAP toolkits (notably Novell) do not support per connection client certificates, and will throw an error on LDAP server connection if you try to use this directive (Use the `[LDAPTrustedGlobalCert](#ldaptrustedglobalcert)` directive instead for Novell client certificates - See the SSL/TLS certificate guide above for details). The type specifies the kind of certificate parameter being set, depending on the LDAP toolkit being used. Supported types are: * CA\_DER - binary DER encoded CA certificate * CA\_BASE64 - PEM encoded CA certificate * CERT\_DER - binary DER encoded client certificate * CERT\_BASE64 - PEM encoded client certificate * CERT\_NICKNAME - Client certificate "nickname" (Netscape SDK) * KEY\_DER - binary DER encoded private key * KEY\_BASE64 - PEM encoded private key LDAPTrustedGlobalCert Directive ------------------------------- | | | | --- | --- | | Description: | Sets the file or database containing global trusted Certificate Authority or global client certificates | | Syntax: | ``` LDAPTrustedGlobalCert type directory-path/filename [password] ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | It specifies the directory path and file name of the trusted CA certificates and/or system wide client certificates `<mod_ldap>` should use when establishing an SSL or TLS connection to an LDAP server. Note that all certificate information specified using this directive is applied globally to the entire server installation. Some LDAP toolkits (notably Novell) require all client certificates to be set globally using this directive. Most other toolkits require clients certificates to be set per Directory or per Location using `[LDAPTrustedClientCert](#ldaptrustedclientcert)`. If you get this wrong, an error may be logged when an attempt is made to contact the LDAP server, or the connection may silently fail (See the SSL/TLS certificate guide above for details). The type specifies the kind of certificate parameter being set, depending on the LDAP toolkit being used. Supported types are: * CA\_DER - binary DER encoded CA certificate * CA\_BASE64 - PEM encoded CA certificate * CA\_CERT7\_DB - Netscape cert7.db CA certificate database file * CA\_SECMOD - Netscape secmod database file * CERT\_DER - binary DER encoded client certificate * CERT\_BASE64 - PEM encoded client certificate * CERT\_KEY3\_DB - Netscape key3.db client certificate database file * CERT\_NICKNAME - Client certificate "nickname" (Netscape SDK) * CERT\_PFX - PKCS#12 encoded client certificate (Novell SDK) * KEY\_DER - binary DER encoded private key * KEY\_BASE64 - PEM encoded private key * KEY\_PFX - PKCS#12 encoded private key (Novell SDK) LDAPTrustedMode Directive ------------------------- | | | | --- | --- | | Description: | Specifies the SSL/TLS mode to be used when connecting to an LDAP server. | | Syntax: | ``` LDAPTrustedMode type ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_ldap | The following modes are supported: * NONE - no encryption * SSL - ldaps:// encryption on default port 636 * TLS - STARTTLS encryption on default port 389 Not all LDAP toolkits support all the above modes. An error message will be logged at runtime if a mode is not supported, and the connection to the LDAP server will fail. If an ldaps:// URL is specified, the mode becomes SSL and the setting of `LDAPTrustedMode` is ignored. LDAPVerifyServerCert Directive ------------------------------ | | | | --- | --- | | Description: | Force server certificate verification | | Syntax: | ``` LDAPVerifyServerCert On|Off ``` | | Default: | ``` LDAPVerifyServerCert On ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_ldap | Specifies whether to force the verification of a server certificate when establishing an SSL connection to the LDAP server.
programming_docs
apache_http_server Apache Module mod_systemd Apache Module mod\_systemd ========================== | | | | --- | --- | | Description: | Provides better support for systemd integration | | Status: | Extension | | Module Identifier: | systemd\_module | | Source File: | mod\_systemd.c | | Compatibility: | Available in Apache 2.4.42 and later | ### Summary This module provides support for systemd integration. It allows httpd to be used in a service with the systemd `Type=notify` (see [systemd.service(5)](https://www.freedesktop.org/software/systemd/man/systemd.service.html) for more information). The module is activated if loaded. ### Example of systemd service unit (more settings are probably needed for production systems) ``` [Unit] Description=The Apache HTTP Server After=network.target [Service] Type=notify ExecStart=/usr/local/apache2/bin/httpd -D FOREGROUND -k start ExecReload=/usr/local/apache2/bin/httpd -k graceful KillMode=mixed [Install] WantedBy=multi-user.target ``` Special attention should be given to how `ExecStop` and/or `KillMode` are configured for the service. If configured, an `ExecStop` command should be a *synchronous operation* which itself exits when the daemon has terminated. Running `httpd -k stop` *asynchronously* initiates daemon termination, so does not satisfy this condition. The example above uses `KillMode=mixed` so that systemd sends `SIGTERM` to signal the parent process (and only the parent) to shut down. The entire process group is then sent `SIGKILL` after `TimeoutStopSec` elapses, if any processes are still running. See [systemd.kill(5)](https://www.freedesktop.org/software/systemd/man/systemd.kill.html) for more information. This module does not provide support for Systemd socket activation. `[ExtendedStatus](core#extendedstatus)` is enabled by default if the module is loaded. If `[ExtendedStatus](core#extendedstatus)` is not disabled in the configuration, run-time load and request statistics are made available in the `systemctl status` output. apache_http_server Apache Module mod_cgi Apache Module mod\_cgi ====================== | | | | --- | --- | | Description: | Execution of CGI scripts | | Status: | Base | | Module Identifier: | cgi\_module | | Source File: | mod\_cgi.c | ### Summary Any file that has the handler `cgi-script` will be treated as a CGI script, and run by the server, with its output being returned to the client. Files acquire this handler either by having a name containing an extension defined by the `[AddHandler](mod_mime#addhandler)` directive, or by being in a `[ScriptAlias](mod_alias#scriptalias)` directory. For an introduction to using CGI scripts with Apache, see our tutorial on [Dynamic Content With CGI](../howto/cgi). When using a multi-threaded MPM under unix, the module `<mod_cgid>` should be used in place of this module. At the user level, the two modules are essentially identical. For backward-compatibility, the cgi-script handler will also be activated for any file with the mime-type `application/x-httpd-cgi`. The use of the magic mime-type is deprecated. CGI Environment variables ------------------------- The server will set the CGI environment variables as described in the [CGI specification](http://www.ietf.org/rfc/rfc3875), with the following provisions: PATH\_INFO This will not be available if the `[AcceptPathInfo](core#acceptpathinfo)` directive is explicitly set to `off`. The default behavior, if `AcceptPathInfo` is not given, is that `<mod_cgi>` will accept path info (trailing `/more/path/info` following the script filename in the URI), while the core server will return a 404 NOT FOUND error for requests with additional path info. Omitting the `AcceptPathInfo` directive has the same effect as setting it `On` for `<mod_cgi>` requests. REMOTE\_HOST This will only be set if `[HostnameLookups](core#hostnamelookups)` is set to `on` (it is off by default), and if a reverse DNS lookup of the accessing host's address indeed finds a host name. REMOTE\_IDENT This will only be set if `[IdentityCheck](mod_ident#identitycheck)` is set to `on` and the accessing host supports the ident protocol. Note that the contents of this variable cannot be relied upon because it can easily be faked, and if there is a proxy between the client and the server, it is usually totally useless. REMOTE\_USER This will only be set if the CGI script is subject to authentication. This module also leverages the core functions [ap\_add\_common\_vars](https://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__SCRIPT.html#ga0e81f9571a8a73f5da0e89e1f46d34b1) and [ap\_add\_cgi\_vars](https://ci.apache.org/projects/httpd/trunk/doxygen/group__APACHE__CORE__SCRIPT.html#ga6b975cd7ff27a338cb8752381a4cc14f) to add environment variables like: DOCUMENT\_ROOT Set with the content of the related `[DocumentRoot](core#documentroot)` directive. SERVER\_NAME The fully qualified domain name related to the request. SERVER\_ADDR The IP address of the Virtual Host serving the request. SERVER\_ADMIN Set with the content of the related `[ServerAdmin](core#serveradmin)` directive. For an exhaustive list it is suggested to write a basic CGI script that dumps all the environment variables passed by Apache in a convenient format. CGI Debugging ------------- Debugging CGI scripts has traditionally been difficult, mainly because it has not been possible to study the output (standard output and error) for scripts which are failing to run properly. These directives provide more detailed logging of errors when they occur. ### CGI Logfile Format When configured, the CGI error log logs any CGI which does not execute properly. Each CGI script which fails to operate causes several lines of information to be logged. The first two lines are always of the format: ``` %% [time] request-line %% HTTP-status CGI-script-filename ``` If the error is that CGI script cannot be run, the log file will contain an extra two lines: ``` %%error error-message ``` Alternatively, if the error is the result of the script returning incorrect header information (often due to a bug in the script), the following information is logged: ``` %request All HTTP request headers received POST or PUT entity (if any) %response All headers output by the CGI script %stdout CGI standard output %stderr CGI standard error ``` (The %stdout and %stderr parts may be missing if the script did not output anything on standard output or standard error). ScriptLog Directive ------------------- | | | | --- | --- | | Description: | Location of the CGI script error logfile | | Syntax: | ``` ScriptLog file-path ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | `<mod_cgi>`, `<mod_cgid>` | The `ScriptLog` directive sets the CGI script error logfile. If no `ScriptLog` is given, no error log is created. If given, any CGI errors are logged into the filename given as argument. If this is a relative file or path it is taken relative to the `[ServerRoot](core#serverroot)`. ### Example ``` ScriptLog logs/cgi_log ``` This log will be opened as the user the child processes run as, *i.e.* the user specified in the main `[User](mod_unixd#user)` directive. This means that either the directory the script log is in needs to be writable by that user or the file needs to be manually created and set to be writable by that user. If you place the script log in your main logs directory, do **NOT** change the directory permissions to make it writable by the user the child processes run as. Note that script logging is meant to be a debugging feature when writing CGI scripts, and is not meant to be activated continuously on running servers. It is not optimized for speed or efficiency, and may have security problems if used in a manner other than that for which it was designed. ScriptLogBuffer Directive ------------------------- | | | | --- | --- | | Description: | Maximum amount of PUT or POST requests that will be recorded in the scriptlog | | Syntax: | ``` ScriptLogBuffer bytes ``` | | Default: | ``` ScriptLogBuffer 1024 ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | `<mod_cgi>`, `<mod_cgid>` | The size of any PUT or POST entity body that is logged to the file is limited, to prevent the log file growing too big too quickly if large bodies are being received. By default, up to 1024 bytes are logged, but this can be changed with this directive. ScriptLogLength Directive ------------------------- | | | | --- | --- | | Description: | Size limit of the CGI script logfile | | Syntax: | ``` ScriptLogLength bytes ``` | | Default: | ``` ScriptLogLength 10385760 ``` | | Context: | server config, virtual host | | Status: | Base | | Module: | `<mod_cgi>`, `<mod_cgid>` | `ScriptLogLength` can be used to limit the size of the CGI script logfile. Since the logfile logs a lot of information per CGI error (all request headers, all script output) it can grow to be a big file. To prevent problems due to unbounded growth, this directive can be used to set an maximum file-size for the CGI logfile. If the file exceeds this size, no more information will be written to it. apache_http_server Apache Module mod_authnz_ldap Apache Module mod\_authnz\_ldap =============================== | | | | --- | --- | | Description: | Allows an LDAP directory to be used to store the database for HTTP Basic authentication. | | Status: | Extension | | Module Identifier: | authnz\_ldap\_module | | Source File: | mod\_authnz\_ldap.c | | Compatibility: | Available in version 2.1 and later | ### Summary This module allows authentication front-ends such as `<mod_auth_basic>` to authenticate users through an ldap directory. `<mod_authnz_ldap>` supports the following features: * Known to support the [OpenLDAP SDK](http://www.openldap.org/) (both 1.x and 2.x), [Novell LDAP SDK](http://developer.novell.com/ndk/cldap.htm) and the [iPlanet (Netscape)](http://www.iplanet.com/downloads/developer/) SDK. * Complex authorization policies can be implemented by representing the policy with LDAP filters. * Uses extensive caching of LDAP operations via <mod_ldap>. * Support for LDAP over SSL (requires the Netscape SDK) or TLS (requires the OpenLDAP 2.x SDK or Novell LDAP SDK). When using `<mod_auth_basic>`, this module is invoked via the `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` directive with the `ldap` value. Contents -------- * [General caveats](#gcaveats) * [Operation](#operation) + [The Authentication Phase](#authenphase) + [The Authorization Phase](#authorphase) * [The Require Directives](#requiredirectives) + [Require ldap-user](#requser) + [Require ldap-group](#reqgroup) + [Require ldap-dn](#reqdn) + [Require ldap-attribute](#reqattribute) + [Require ldap-filter](#reqfilter) * [Examples](#examples) * [Using TLS](#usingtls) * [Using SSL](#usingssl) * [Exposing Login Information](#exposed) * [Using Active Directory](#activedirectory) * [Using Microsoft FrontPage with `<mod_authnz_ldap>`](#frontpage) + [How It Works](#howitworks) + [Caveats](#fpcaveats) General caveats --------------- This module caches authentication and authorization results based on the configuration of `<mod_ldap>`. Changes made to the backing LDAP server will not be immediately reflected on the HTTP Server, including but not limited to user lockouts/revocations, password changes, or changes to group memberships. Consult the directives in `<mod_ldap>` for details of the cache tunables. Operation --------- There are two phases in granting access to a user. The first phase is authentication, in which the `<mod_authnz_ldap>` authentication provider verifies that the user's credentials are valid. This is also called the *search/bind* phase. The second phase is authorization, in which `<mod_authnz_ldap>` determines if the authenticated user is allowed access to the resource in question. This is also known as the *compare* phase. `<mod_authnz_ldap>` registers both an authn\_ldap authentication provider and an authz\_ldap authorization handler. The authn\_ldap authentication provider can be enabled through the `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` directive using the `ldap` value. The authz\_ldap handler extends the `[Require](mod_authz_core#require)` directive's authorization types by adding `ldap-user`, `ldap-dn` and `ldap-group` values. ### The Authentication Phase During the authentication phase, `<mod_authnz_ldap>` searches for an entry in the directory that matches the username that the HTTP client passes. If a single unique match is found, then `<mod_authnz_ldap>` attempts to bind to the directory server using the DN of the entry plus the password provided by the HTTP client. Because it does a search, then a bind, it is often referred to as the search/bind phase. Here are the steps taken during the search/bind phase. 1. Generate a search filter by combining the attribute and filter provided in the `[AuthLDAPURL](#authldapurl)` directive with the username passed by the HTTP client. 2. Search the directory using the generated filter. If the search does not return exactly one entry, deny or decline access. 3. Fetch the distinguished name of the entry retrieved from the search and attempt to bind to the LDAP server using that DN and the password passed by the HTTP client. If the bind is unsuccessful, deny or decline access. The following directives are used during the search/bind phase | | | | --- | --- | | `AuthLDAPURL` | Specifies the LDAP server, the base DN, the attribute to use in the search, as well as the extra search filter to use. | | `AuthLDAPBindDN` | An optional DN to bind with during the search phase. | | `AuthLDAPBindPassword` | An optional password to bind with during the search phase. | ### The Authorization Phase During the authorization phase, `<mod_authnz_ldap>` attempts to determine if the user is authorized to access the resource. Many of these checks require `<mod_authnz_ldap>` to do a compare operation on the LDAP server. This is why this phase is often referred to as the compare phase. `<mod_authnz_ldap>` accepts the following `[Require](mod_authz_core#require)` directives to determine if the credentials are acceptable: * Grant access if there is a [`Require ldap-user`](#reqgroup) directive, and the username in the directive matches the username passed by the client. * Grant access if there is a [`Require ldap-dn`](#reqdn) directive, and the DN in the directive matches the DN fetched from the LDAP directory. * Grant access if there is a [`Require ldap-group`](#reqgroup) directive, and the DN fetched from the LDAP directory (or the username passed by the client) occurs in the LDAP group or, potentially, in one of its sub-groups. * Grant access if there is a [`Require ldap-attribute`](#reqattribute) directive, and the attribute fetched from the LDAP directory matches the given value. * Grant access if there is a [`Require ldap-filter`](#reqfilter) directive, and the search filter successfully finds a single user object that matches the dn of the authenticated user. * otherwise, deny or decline access Other `[Require](mod_authz_core#require)` values may also be used which may require loading additional authorization modules. * Grant access to all successfully authenticated users if there is a [`Require valid-user`](#requser) directive. (requires `<mod_authz_user>`) * Grant access if there is a [`Require group`](#reqgroup) directive, and `<mod_authz_groupfile>` has been loaded with the `[AuthGroupFile](mod_authz_groupfile#authgroupfile)` directive set. * others... `<mod_authnz_ldap>` uses the following directives during the compare phase: | | | | --- | --- | | `AuthLDAPURL` | The attribute specified in the URL is used in compare operations for the `Require ldap-user` operation. | | `AuthLDAPCompareDNOnServer` | Determines the behavior of the `Require ldap-dn` directive. | | `AuthLDAPGroupAttribute` | Determines the attribute to use for comparisons in the `Require ldap-group` directive. | | `AuthLDAPGroupAttributeIsDN` | Specifies whether to use the user DN or the username when doing comparisons for the `Require ldap-group` directive. | | `AuthLDAPMaxSubGroupDepth` | Determines the maximum depth of sub-groups that will be evaluated during comparisons in the `Require ldap-group` directive. | | `AuthLDAPSubGroupAttribute` | Determines the attribute to use when obtaining sub-group members of the current group during comparisons in the `Require ldap-group` directive. | | `AuthLDAPSubGroupClass` | Specifies the LDAP objectClass values used to identify if queried directory objects really are group objects (as opposed to user objects) during the `Require ldap-group` directive's sub-group processing. | The Require Directives ---------------------- Apache's `[Require](mod_authz_core#require)` directives are used during the authorization phase to ensure that a user is allowed to access a resource. mod\_authnz\_ldap extends the authorization types with `ldap-user`, `ldap-dn`, `ldap-group`, `ldap-attribute` and `ldap-filter`. Other authorization types may also be used but may require that additional authorization modules be loaded. Since v2.4.8, [expressions](../expr) are supported within the LDAP require directives. ### Require ldap-user The `Require ldap-user` directive specifies what usernames can access the resource. Once `<mod_authnz_ldap>` has retrieved a unique DN from the directory, it does an LDAP compare operation using the username specified in the `Require ldap-user` to see if that username is part of the just-fetched LDAP entry. Multiple users can be granted access by putting multiple usernames on the line, separated with spaces. If a username has a space in it, then it must be surrounded with double quotes. Multiple users can also be granted access by using multiple `Require ldap-user` directives, with one user per line. For example, with a `[AuthLDAPURL](#authldapurl)` of `ldap://ldap/o=Example?cn` (i.e., `cn` is used for searches), the following Require directives could be used to restrict access: ``` Require ldap-user "Barbara Jenson" Require ldap-user "Fred User" Require ldap-user "Joe Manager" ``` Because of the way that `<mod_authnz_ldap>` handles this directive, Barbara Jenson could sign on as *Barbara Jenson*, *Babs Jenson* or any other `cn` that she has in her LDAP entry. Only the single `Require ldap-user` line is needed to support all values of the attribute in the user's entry. If the `uid` attribute was used instead of the `cn` attribute in the URL above, the above three lines could be condensed to ``` Require ldap-user bjenson fuser jmanager ``` ### Require ldap-group This directive specifies an LDAP group whose members are allowed access. It takes the distinguished name of the LDAP group. Note: Do not surround the group name with quotes. For example, assume that the following entry existed in the LDAP directory: ``` dn: cn=Administrators, o=Example objectClass: groupOfUniqueNames uniqueMember: cn=Barbara Jenson, o=Example uniqueMember: cn=Fred User, o=Example ``` The following directive would grant access to both Fred and Barbara: ``` Require ldap-group cn=Administrators, o=Example ``` Members can also be found within sub-groups of a specified LDAP group if `[AuthLDAPMaxSubGroupDepth](#authldapmaxsubgroupdepth)` is set to a value greater than 0. For example, assume the following entries exist in the LDAP directory: ``` dn: cn=Employees, o=Example objectClass: groupOfUniqueNames uniqueMember: cn=Managers, o=Example uniqueMember: cn=Administrators, o=Example uniqueMember: cn=Users, o=Example dn: cn=Managers, o=Example objectClass: groupOfUniqueNames uniqueMember: cn=Bob Ellis, o=Example uniqueMember: cn=Tom Jackson, o=Example dn: cn=Administrators, o=Example objectClass: groupOfUniqueNames uniqueMember: cn=Barbara Jenson, o=Example uniqueMember: cn=Fred User, o=Example dn: cn=Users, o=Example objectClass: groupOfUniqueNames uniqueMember: cn=Allan Jefferson, o=Example uniqueMember: cn=Paul Tilley, o=Example uniqueMember: cn=Temporary Employees, o=Example dn: cn=Temporary Employees, o=Example objectClass: groupOfUniqueNames uniqueMember: cn=Jim Swenson, o=Example uniqueMember: cn=Elliot Rhodes, o=Example ``` The following directives would allow access for Bob Ellis, Tom Jackson, Barbara Jenson, Fred User, Allan Jefferson, and Paul Tilley but would not allow access for Jim Swenson, or Elliot Rhodes (since they are at a sub-group depth of 2): ``` Require ldap-group cn=Employees, o=Example AuthLDAPMaxSubGroupDepth 1 ``` Behavior of this directive is modified by the `[AuthLDAPGroupAttribute](#authldapgroupattribute)`, `[AuthLDAPGroupAttributeIsDN](#authldapgroupattributeisdn)`, `[AuthLDAPMaxSubGroupDepth](#authldapmaxsubgroupdepth)`, `[AuthLDAPSubGroupAttribute](#authldapsubgroupattribute)`, and `[AuthLDAPSubGroupClass](#authldapsubgroupclass)` directives. ### Require ldap-dn The `Require ldap-dn` directive allows the administrator to grant access based on distinguished names. It specifies a DN that must match for access to be granted. If the distinguished name that was retrieved from the directory server matches the distinguished name in the `Require ldap-dn`, then authorization is granted. Note: do not surround the distinguished name with quotes. The following directive would grant access to a specific DN: ``` Require ldap-dn cn=Barbara Jenson, o=Example ``` Behavior of this directive is modified by the `[AuthLDAPCompareDNOnServer](#authldapcomparednonserver)` directive. ### Require ldap-attribute The `Require ldap-attribute` directive allows the administrator to grant access based on attributes of the authenticated user in the LDAP directory. If the attribute in the directory matches the value given in the configuration, access is granted. The following directive would grant access to anyone with the attribute employeeType = active ``` Require ldap-attribute employeeType="active" ``` Multiple attribute/value pairs can be specified on the same line separated by spaces or they can be specified in multiple `Require ldap-attribute` directives. The effect of listing multiple attribute/values pairs is an OR operation. Access will be granted if any of the listed attribute values match the value of the corresponding attribute in the user object. If the value of the attribute contains a space, only the value must be within double quotes. The following directive would grant access to anyone with the city attribute equal to "San Jose" or status equal to "Active" ``` Require ldap-attribute city="San Jose" status="active" ``` ### Require ldap-filter The `Require ldap-filter` directive allows the administrator to grant access based on a complex LDAP search filter. If the dn returned by the filter search matches the authenticated user dn, access is granted. The following directive would grant access to anyone having a cell phone and is in the marketing department ``` Require ldap-filter "&(cell=*)(department=marketing)" ``` The difference between the `Require ldap-filter` directive and the `Require ldap-attribute` directive is that `ldap-filter` performs a search operation on the LDAP directory using the specified search filter rather than a simple attribute comparison. If a simple attribute comparison is all that is required, the comparison operation performed by `ldap-attribute` will be faster than the search operation used by `ldap-filter` especially within a large directory. Examples -------- * Grant access to anyone who exists in the LDAP directory, using their UID for searches. ``` AuthLDAPURL "ldap://ldap1.example.com:389/ou=People, o=Example?uid?sub?(objectClass=*)" Require valid-user ``` * The next example is the same as above; but with the fields that have useful defaults omitted. Also, note the use of a redundant LDAP server. ``` AuthLDAPURL "ldap://ldap1.example.com ldap2.example.com/ou=People, o=Example" Require valid-user ``` * The next example is similar to the previous one, but it uses the common name instead of the UID. Note that this could be problematical if multiple people in the directory share the same `cn`, because a search on `cn` **must** return exactly one entry. That's why this approach is not recommended: it's a better idea to choose an attribute that is guaranteed unique in your directory, such as `uid`. ``` AuthLDAPURL "ldap://ldap.example.com/ou=People, o=Example?cn" Require valid-user ``` * Grant access to anybody in the Administrators group. The users must authenticate using their UID. ``` AuthLDAPURL ldap://ldap.example.com/o=Example?uid Require ldap-group cn=Administrators, o=Example ``` * Grant access to anybody in the group whose name matches the hostname of the virtual host. In this example an [expression](../expr) is used to build the filter. ``` AuthLDAPURL ldap://ldap.example.com/o=Example?uid Require ldap-group cn=%{SERVER_NAME}, o=Example ``` * The next example assumes that everyone at Example who carries an alphanumeric pager will have an LDAP attribute of `qpagePagerID`. The example will grant access only to people (authenticated via their UID) who have alphanumeric pagers: ``` AuthLDAPURL ldap://ldap.example.com/o=Example?uid??(qpagePagerID=*) Require valid-user ``` * The next example demonstrates the power of using filters to accomplish complicated administrative requirements. Without filters, it would have been necessary to create a new LDAP group and ensure that the group's members remain synchronized with the pager users. This becomes trivial with filters. The goal is to grant access to anyone who has a pager, plus grant access to Joe Manager, who doesn't have a pager, but does need to access the same resource: ``` AuthLDAPURL ldap://ldap.example.com/o=Example?uid??(|(qpagePagerID=*)(uid=jmanager)) Require valid-user ``` This last may look confusing at first, so it helps to evaluate what the search filter will look like based on who connects, as shown below. If Fred User connects as `fuser`, the filter would look like `(&(|(qpagePagerID=*)(uid=jmanager))(uid=fuser))` The above search will only succeed if *fuser* has a pager. When Joe Manager connects as *jmanager*, the filter looks like `(&(|(qpagePagerID=*)(uid=jmanager))(uid=jmanager))` The above search will succeed whether *jmanager* has a pager or not. Using TLS --------- To use TLS, see the `<mod_ldap>` directives `[LDAPTrustedClientCert](mod_ldap#ldaptrustedclientcert)`, `[LDAPTrustedGlobalCert](mod_ldap#ldaptrustedglobalcert)` and `[LDAPTrustedMode](mod_ldap#ldaptrustedmode)`. An optional second parameter can be added to the `[AuthLDAPURL](#authldapurl)` to override the default connection type set by `[LDAPTrustedMode](mod_ldap#ldaptrustedmode)`. This will allow the connection established by an *ldap://* Url to be upgraded to a secure connection on the same port. Using SSL --------- To use SSL, see the `<mod_ldap>` directives `[LDAPTrustedClientCert](mod_ldap#ldaptrustedclientcert)`, `[LDAPTrustedGlobalCert](mod_ldap#ldaptrustedglobalcert)` and `[LDAPTrustedMode](mod_ldap#ldaptrustedmode)`. To specify a secure LDAP server, use *ldaps://* in the `[AuthLDAPURL](#authldapurl)` directive, instead of *ldap://*. Exposing Login Information -------------------------- when this module performs *authentication*, ldap attributes specified in the `[AuthLDAPURL](#authldapurl)` directive are placed in environment variables with the prefix "AUTHENTICATE\_". when this module performs *authorization*, ldap attributes specified in the `[AuthLDAPURL](#authldapurl)` directive are placed in environment variables with the prefix "AUTHORIZE\_". If the attribute field contains the username, common name and telephone number of a user, a CGI program will have access to this information without the need to make a second independent LDAP query to gather this additional information. This has the potential to dramatically simplify the coding and configuration required in some web applications. Using Active Directory ---------------------- An Active Directory installation may support multiple domains at the same time. To distinguish users between domains, an identifier called a User Principle Name (UPN) can be added to a user's entry in the directory. This UPN usually takes the form of the user's account name, followed by the domain components of the particular domain, for example *[email protected]*. You may wish to configure the `<mod_authnz_ldap>` module to authenticate users present in any of the domains making up the Active Directory forest. In this way both *[email protected]* and *[email protected]* can be authenticated using the same query at the same time. To make this practical, Active Directory supports the concept of a Global Catalog. This Global Catalog is a read only copy of selected attributes of all the Active Directory servers within the Active Directory forest. Querying the Global Catalog allows all the domains to be queried in a single query, without the query spanning servers over potentially slow links. If enabled, the Global Catalog is an independent directory server that runs on port 3268 (3269 for SSL). To search for a user, do a subtree search for the attribute *userPrincipalName*, with an empty search root, like so: ``` AuthLDAPBindDN [email protected] AuthLDAPBindPassword password AuthLDAPURL ldap://10.0.0.1:3268/?userPrincipalName?sub ``` Users will need to enter their User Principal Name as a login, in the form *[email protected]*. Using Microsoft FrontPage with mod\_authnz\_ldap ------------------------------------------------ Normally, FrontPage uses FrontPage-web-specific user/group files (i.e., the `<mod_authn_file>` and `<mod_authz_groupfile>` modules) to handle all authentication. Unfortunately, it is not possible to just change to LDAP authentication by adding the proper directives, because it will break the *Permissions* forms in the FrontPage client, which attempt to modify the standard text-based authorization files. Once a FrontPage web has been created, adding LDAP authentication to it is a matter of adding the following directives to *every* `.htaccess` file that gets created in the web ``` AuthLDAPURL "the url" AuthGroupFile "mygroupfile" Require group "mygroupfile" ``` ### How It Works FrontPage restricts access to a web by adding the `Require valid-user` directive to the `.htaccess` files. The `Require valid-user` directive will succeed for any user who is valid *as far as LDAP is concerned*. This means that anybody who has an entry in the LDAP directory is considered a valid user, whereas FrontPage considers only those people in the local user file to be valid. By substituting the ldap-group with group file authorization, Apache is allowed to consult the local user file (which is managed by FrontPage) - instead of LDAP - when handling authorizing the user. Once directives have been added as specified above, FrontPage users will be able to perform all management operations from the FrontPage client. ### Caveats * When choosing the LDAP URL, the attribute to use for authentication should be something that will also be valid for putting into a `<mod_authn_file>` user file. The user ID is ideal for this. * When adding users via FrontPage, FrontPage administrators should choose usernames that already exist in the LDAP directory (for obvious reasons). Also, the password that the administrator enters into the form is ignored, since Apache will actually be authenticating against the password in the LDAP database, and not against the password in the local user file. This could cause confusion for web administrators. * Apache must be compiled with `<mod_auth_basic>`, `<mod_authn_file>` and `<mod_authz_groupfile>` in order to use FrontPage support. This is because Apache will still use the `<mod_authz_groupfile>` group file for determine the extent of a user's access to the FrontPage web. * The directives must be put in the `.htaccess` files. Attempting to put them inside `[<Location>](core#location)` or `[<Directory>](core#directory)` directives won't work. This is because `<mod_authnz_ldap>` has to be able to grab the `[AuthGroupFile](mod_authz_groupfile#authgroupfile)` directive that is found in FrontPage `.htaccess` files so that it knows where to look for the valid user list. If the `<mod_authnz_ldap>` directives aren't in the same `.htaccess` file as the FrontPage directives, then the hack won't work, because `<mod_authnz_ldap>` will never get a chance to process the `.htaccess` file, and won't be able to find the FrontPage-managed user file. AuthLDAPAuthorizePrefix Directive --------------------------------- | | | | --- | --- | | Description: | Specifies the prefix for environment variables set during authorization | | Syntax: | ``` AuthLDAPAuthorizePrefix prefix ``` | | Default: | ``` AuthLDAPAuthorizePrefix AUTHORIZE_ ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | | Compatibility: | Available in version 2.3.6 and later | This directive allows you to override the prefix used for environment variables set during LDAP authorization. If *AUTHENTICATE\_* is specified, consumers of these environment variables see the same information whether LDAP has performed authentication, authorization, or both. **Note** No authorization variables are set when a user is authorized on the basis of `Require valid-user`. AuthLDAPBindAuthoritative Directive ----------------------------------- | | | | --- | --- | | Description: | Determines if other authentication providers are used when a user can be mapped to a DN but the server cannot successfully bind with the user's credentials. | | Syntax: | ``` AuthLDAPBindAuthoritative off|on ``` | | Default: | ``` AuthLDAPBindAuthoritative on ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | By default, subsequent authentication providers are only queried if a user cannot be mapped to a DN, but not if the user can be mapped to a DN and their password cannot be verified with an LDAP bind. If `AuthLDAPBindAuthoritative` is set to *off*, other configured authentication modules will have a chance to validate the user if the LDAP bind (with the current user's credentials) fails for any reason. This allows users present in both LDAP and `[AuthUserFile](mod_authn_file#authuserfile)` to authenticate when the LDAP server is available but the user's account is locked or password is otherwise unusable. ### See also * `[AuthUserFile](mod_authn_file#authuserfile)` * `[AuthBasicProvider](mod_auth_basic#authbasicprovider)` AuthLDAPBindDN Directive ------------------------ | | | | --- | --- | | Description: | Optional DN to use in binding to the LDAP server | | Syntax: | ``` AuthLDAPBindDN distinguished-name ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | An optional DN used to bind to the server when searching for entries. If not provided, `<mod_authnz_ldap>` will use an anonymous bind. AuthLDAPBindPassword Directive ------------------------------ | | | | --- | --- | | Description: | Password used in conjunction with the bind DN | | Syntax: | ``` AuthLDAPBindPassword password ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | | Compatibility: | *exec:* was added in 2.4.5. | A bind password to use in conjunction with the bind DN. Note that the bind password is probably sensitive data, and should be properly protected. You should only use the `[AuthLDAPBindDN](#authldapbinddn)` and `AuthLDAPBindPassword` if you absolutely need them to search the directory. If the value begins with exec: the resulting command will be executed and the first line returned to standard output by the program will be used as the password. ``` #Password used as-is AuthLDAPBindPassword secret #Run /path/to/program to get my password AuthLDAPBindPassword exec:/path/to/program #Run /path/to/otherProgram and provide arguments AuthLDAPBindPassword "exec:/path/to/otherProgram argument1" ``` AuthLDAPCharsetConfig Directive ------------------------------- | | | | --- | --- | | Description: | Language to charset conversion configuration file | | Syntax: | ``` AuthLDAPCharsetConfig file-path ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_authnz\_ldap | The `AuthLDAPCharsetConfig` directive sets the location of the language to charset conversion configuration file. File-path is relative to the `[ServerRoot](core#serverroot)`. This file specifies the list of language extensions to character sets. Most administrators use the provided `charset.conv` file, which associates common language extensions to character sets. The file contains lines in the following format: ``` Language-Extension charset [Language-String] ... ``` The case of the extension does not matter. Blank lines, and lines beginning with a hash character (`#`) are ignored. AuthLDAPCompareAsUser Directive ------------------------------- | | | | --- | --- | | Description: | Use the authenticated user's credentials to perform authorization comparisons | | Syntax: | ``` AuthLDAPCompareAsUser on|off ``` | | Default: | ``` AuthLDAPCompareAsUser off ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | | Compatibility: | Available in version 2.3.6 and later | When set, and `<mod_authnz_ldap>` has authenticated the user, LDAP comparisons for authorization use the queried distinguished name (DN) and HTTP basic authentication password of the authenticated user instead of the servers configured credentials. The *ldap-attribute*, *ldap-user*, and *ldap-group* (single-level only) authorization checks use comparisons. This directive only has effect on the comparisons performed during nested group processing when `[AuthLDAPSearchAsUser](#authldapsearchasuser)` is also enabled. This directive should only be used when your LDAP server doesn't accept anonymous comparisons and you cannot use a dedicated `[AuthLDAPBindDN](#authldapbinddn)`. ### See also * `[AuthLDAPInitialBindAsUser](#authldapinitialbindasuser)` * `[AuthLDAPSearchAsUser](#authldapsearchasuser)` AuthLDAPCompareDNOnServer Directive ----------------------------------- | | | | --- | --- | | Description: | Use the LDAP server to compare the DNs | | Syntax: | ``` AuthLDAPCompareDNOnServer on|off ``` | | Default: | ``` AuthLDAPCompareDNOnServer on ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | When set, `<mod_authnz_ldap>` will use the LDAP server to compare the DNs. This is the only foolproof way to compare DNs. `<mod_authnz_ldap>` will search the directory for the DN specified with the [`Require dn`](#reqdn) directive, then, retrieve the DN and compare it with the DN retrieved from the user entry. If this directive is not set, `<mod_authnz_ldap>` simply does a string comparison. It is possible to get false negatives with this approach, but it is much faster. Note the `<mod_ldap>` cache can speed up DN comparison in most situations. AuthLDAPDereferenceAliases Directive ------------------------------------ | | | | --- | --- | | Description: | When will the module de-reference aliases | | Syntax: | ``` AuthLDAPDereferenceAliases never|searching|finding|always ``` | | Default: | ``` AuthLDAPDereferenceAliases always ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | This directive specifies when `<mod_authnz_ldap>` will de-reference aliases during LDAP operations. The default is `always`. AuthLDAPGroupAttribute Directive -------------------------------- | | | | --- | --- | | Description: | LDAP attributes used to identify the user members of groups. | | Syntax: | ``` AuthLDAPGroupAttribute attribute ``` | | Default: | ``` AuthLDAPGroupAttribute member uniqueMember ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | This directive specifies which LDAP attributes are used to check for user members within groups. Multiple attributes can be used by specifying this directive multiple times. If not specified, then `<mod_authnz_ldap>` uses the `member` and `uniqueMember` attributes. AuthLDAPGroupAttributeIsDN Directive ------------------------------------ | | | | --- | --- | | Description: | Use the DN of the client username when checking for group membership | | Syntax: | ``` AuthLDAPGroupAttributeIsDN on|off ``` | | Default: | ``` AuthLDAPGroupAttributeIsDN on ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | When set `on`, this directive says to use the distinguished name of the client username when checking for group membership. Otherwise, the username will be used. For example, assume that the client sent the username `bjenson`, which corresponds to the LDAP DN `cn=Babs Jenson, o=Example`. If this directive is set, `<mod_authnz_ldap>` will check if the group has `cn=Babs Jenson, o=Example` as a member. If this directive is not set, then `<mod_authnz_ldap>` will check if the group has `bjenson` as a member. AuthLDAPInitialBindAsUser Directive ----------------------------------- | | | | --- | --- | | Description: | Determines if the server does the initial DN lookup using the basic authentication users' own username, instead of anonymously or with hard-coded credentials for the server | | Syntax: | ``` AuthLDAPInitialBindAsUser off|on ``` | | Default: | ``` AuthLDAPInitialBindAsUser off ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | | Compatibility: | Available in version 2.3.6 and later | By default, the server either anonymously, or with a dedicated user and password, converts the basic authentication username into an LDAP distinguished name (DN). This directive forces the server to use the verbatim username and password provided by the incoming user to perform the initial DN search. If the verbatim username can't directly bind, but needs some cosmetic transformation, see `[AuthLDAPInitialBindPattern](#authldapinitialbindpattern)`. This directive should only be used when your LDAP server doesn't accept anonymous searches and you cannot use a dedicated `[AuthLDAPBindDN](#authldapbinddn)`. **Not available with authorization-only** This directive can only be used if this module authenticates the user, and has no effect when this module is used exclusively for authorization. ### See also * `[AuthLDAPInitialBindPattern](#authldapinitialbindpattern)` * `[AuthLDAPBindDN](#authldapbinddn)` * `[AuthLDAPCompareAsUser](#authldapcompareasuser)` * `[AuthLDAPSearchAsUser](#authldapsearchasuser)` AuthLDAPInitialBindPattern Directive ------------------------------------ | | | | --- | --- | | Description: | Specifies the transformation of the basic authentication username to be used when binding to the LDAP server to perform a DN lookup | | Syntax: | ``` AuthLDAPInitialBindPattern regex substitution ``` | | Default: | ``` AuthLDAPInitialBindPattern (.*) $1 (remote username used verbatim) ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | | Compatibility: | Available in version 2.3.6 and later | If `[AuthLDAPInitialBindAsUser](#authldapinitialbindasuser)` is set to *ON*, the basic authentication username will be transformed according to the regular expression and substitution arguments. The regular expression argument is compared against the current basic authentication username. The substitution argument may contain backreferences, but has no other variable interpolation. This directive should only be used when your LDAP server doesn't accept anonymous searches and you cannot use a dedicated `[AuthLDAPBindDN](#authldapbinddn)`. ``` AuthLDAPInitialBindPattern (.+) [email protected] ``` ``` AuthLDAPInitialBindPattern (.+) cn=$1,dc=example,dc=com ``` **Not available with authorization-only** This directive can only be used if this module authenticates the user, and has no effect when this module is used exclusively for authorization. **debugging** The substituted DN is recorded in the environment variable *LDAP\_BINDASUSER*. If the regular expression does not match the input, the verbatim username is used. ### See also * `[AuthLDAPInitialBindAsUser](#authldapinitialbindasuser)` * `[AuthLDAPBindDN](#authldapbinddn)` AuthLDAPMaxSubGroupDepth Directive ---------------------------------- | | | | --- | --- | | Description: | Specifies the maximum sub-group nesting depth that will be evaluated before the user search is discontinued. | | Syntax: | ``` AuthLDAPMaxSubGroupDepth Number ``` | | Default: | ``` AuthLDAPMaxSubGroupDepth 10 ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | | Compatibility: | Available in version 2.3.0 and later | When this directive is set to a non-zero value `X` combined with use of the `Require ldap-group someGroupDN` directive, the provided user credentials will be searched for as a member of the `someGroupDN` directory object or of any group member of the current group up to the maximum nesting level `X` specified by this directive. See the [`Require ldap-group`](#reqgroup) section for a more detailed example. **Nested groups performance** When `AuthLDAPSubGroupAttribute` overlaps with `AuthLDAPGroupAttribute` (as it does by default and as required by common LDAP schemas), uncached searching for subgroups in large groups can be very slow. If you use large, non-nested groups, set `AuthLDAPMaxSubGroupDepth` to zero. AuthLDAPRemoteUserAttribute Directive ------------------------------------- | | | | --- | --- | | Description: | Use the value of the attribute returned during the user query to set the REMOTE\_USER environment variable | | Syntax: | ``` AuthLDAPRemoteUserAttribute uid ``` | | Default: | `none` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | If this directive is set, the value of the `REMOTE_USER` environment variable will be set to the value of the attribute specified. Make sure that this attribute is included in the list of attributes in the `[AuthLDAPURL](#authldapurl)` definition, otherwise this directive will have no effect. This directive, if present, takes precedence over `[AuthLDAPRemoteUserIsDN](#authldapremoteuserisdn)`. This directive is useful should you want people to log into a website using an email address, but a backend application expects the username as a userid. AuthLDAPRemoteUserIsDN Directive -------------------------------- | | | | --- | --- | | Description: | Use the DN of the client username to set the REMOTE\_USER environment variable | | Syntax: | ``` AuthLDAPRemoteUserIsDN on|off ``` | | Default: | ``` AuthLDAPRemoteUserIsDN off ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | If this directive is set to on, the value of the `REMOTE_USER` environment variable will be set to the full distinguished name of the authenticated user, rather than just the username that was passed by the client. It is turned off by default. AuthLDAPSearchAsUser Directive ------------------------------ | | | | --- | --- | | Description: | Use the authenticated user's credentials to perform authorization searches | | Syntax: | ``` AuthLDAPSearchAsUser on|off ``` | | Default: | ``` AuthLDAPSearchAsUser off ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | | Compatibility: | Available in version 2.3.6 and later | When set, and `<mod_authnz_ldap>` has authenticated the user, LDAP searches for authorization use the queried distinguished name (DN) and HTTP basic authentication password of the authenticated user instead of the servers configured credentials. The *ldap-filter* and *ldap-dn* authorization checks use searches. This directive only has effect on the comparisons performed during nested group processing when `[AuthLDAPCompareAsUser](#authldapcompareasuser)` is also enabled. This directive should only be used when your LDAP server doesn't accept anonymous searches and you cannot use a dedicated `[AuthLDAPBindDN](#authldapbinddn)`. ### See also * `[AuthLDAPInitialBindAsUser](#authldapinitialbindasuser)` * `[AuthLDAPCompareAsUser](#authldapcompareasuser)` AuthLDAPSubGroupAttribute Directive ----------------------------------- | | | | --- | --- | | Description: | Specifies the attribute labels, one value per directive line, used to distinguish the members of the current group that are groups. | | Syntax: | ``` AuthLDAPSubGroupAttribute attribute ``` | | Default: | ``` AuthLDAPSubGroupAttribute member uniqueMember ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | | Compatibility: | Available in version 2.3.0 and later | An LDAP group object may contain members that are users and members that are groups (called nested or sub groups). The `AuthLDAPSubGroupAttribute` directive identifies the labels of group members and the `[AuthLDAPGroupAttribute](#authldapgroupattribute)` directive identifies the labels of the user members. Multiple attributes can be used by specifying this directive multiple times. If not specified, then `<mod_authnz_ldap>` uses the `member` and `uniqueMember` attributes. AuthLDAPSubGroupClass Directive ------------------------------- | | | | --- | --- | | Description: | Specifies which LDAP objectClass values identify directory objects that are groups during sub-group processing. | | Syntax: | ``` AuthLDAPSubGroupClass LdapObjectClass ``` | | Default: | ``` AuthLDAPSubGroupClass groupOfNames groupOfUniqueNames ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | | Compatibility: | Available in version 2.3.0 and later | An LDAP group object may contain members that are users and members that are groups (called nested or sub groups). The `[AuthLDAPSubGroupAttribute](#authldapsubgroupattribute)` directive identifies the labels of members that may be sub-groups of the current group (as opposed to user members). The `AuthLDAPSubGroupClass` directive specifies the LDAP objectClass values used in verifying that these potential sub-groups are in fact group objects. Verified sub-groups can then be searched for more user or sub-group members. Multiple attributes can be used by specifying this directive multiple times. If not specified, then `<mod_authnz_ldap>` uses the `groupOfNames` and `groupOfUniqueNames` values. AuthLDAPURL Directive --------------------- | | | | --- | --- | | Description: | URL specifying the LDAP search parameters | | Syntax: | ``` AuthLDAPURL url [NONE|SSL|TLS|STARTTLS] ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_authnz\_ldap | An RFC 2255 URL which specifies the LDAP search parameters to use. The syntax of the URL is `ldap://host:port/basedn?attribute?scope?filter` If you want to specify more than one LDAP URL that Apache should try in turn, the syntax is: ``` AuthLDAPURL "ldap://ldap1.example.com ldap2.example.com/dc=..." ``` ***Caveat:** If you specify multiple servers, you need to enclose the entire URL string in quotes; otherwise you will get an error: "AuthLDAPURL takes one argument, URL to define LDAP connection.."* You can of course use search parameters on each of these. ldap For regular ldap, use the string `ldap`. For secure LDAP, use `ldaps` instead. Secure LDAP is only available if Apache was linked to an LDAP library with SSL support. host:port The name/port of the ldap server (defaults to `localhost:389` for `ldap`, and `localhost:636` for `ldaps`). To specify multiple, redundant LDAP servers, just list all servers, separated by spaces. `<mod_authnz_ldap>` will try connecting to each server in turn, until it makes a successful connection. If multiple ldap servers are specified, then entire LDAP URL must be encapsulated in double quotes. Once a connection has been made to a server, that connection remains active for the life of the `[httpd](../programs/httpd)` process, or until the LDAP server goes down. If the LDAP server goes down and breaks an existing connection, `<mod_authnz_ldap>` will attempt to re-connect, starting with the primary server, and trying each redundant server in turn. Note that this is different than a true round-robin search. basedn The DN of the branch of the directory where all searches should start from. At the very least, this must be the top of your directory tree, but could also specify a subtree in the directory. attribute The attribute to search for. Although RFC 2255 allows a comma-separated list of attributes, only the first attribute will be used, no matter how many are provided. If no attributes are provided, the default is to use `uid`. It's a good idea to choose an attribute that will be unique across all entries in the subtree you will be using. All attributes listed will be put into the environment with an AUTHENTICATE\_ prefix for use by other modules. scope The scope of the search. Can be either `one` or `sub`. Note that a scope of `base` is also supported by RFC 2255, but is not supported by this module. If the scope is not provided, or if `base` scope is specified, the default is to use a scope of `sub`. filter A valid LDAP search filter. If not provided, defaults to `(objectClass=*)`, which will search for all objects in the tree. Filters are limited to approximately 8000 characters (the definition of `MAX_STRING_LEN` in the Apache source code). This should be more than sufficient for any application. In 2.4.10 and later, the keyword `none` disables the use of a filter; this is required by some primitive LDAP servers. When doing searches, the attribute, filter and username passed by the HTTP client are combined to create a search filter that looks like `(&(*filter*)(*attribute*=*username*))`. For example, consider an URL of `ldap://ldap.example.com/o=Example?cn?sub?(posixid=*)`. When a client attempts to connect using a username of `Babs Jenson`, the resulting search filter will be `(&(posixid=*)(cn=Babs Jenson))`. An optional parameter can be added to allow the LDAP Url to override the connection type. This parameter can be one of the following: NONE Establish an unsecure connection on the default LDAP port. This is the same as `ldap://` on port 389. SSL Establish a secure connection on the default secure LDAP port. This is the same as `ldaps://` TLS | STARTTLS Establish an upgraded secure connection on the default LDAP port. This connection will be initiated on port 389 by default and then upgraded to a secure connection on the same port. See above for examples of `[AuthLDAPURL](#authldapurl)` URLs.
programming_docs
apache_http_server Apache Module mod_status Apache Module mod\_status ========================= | | | | --- | --- | | Description: | Provides information on server activity and performance | | Status: | Base | | Module Identifier: | status\_module | | Source File: | mod\_status.c | ### Summary The Status module allows a server administrator to find out how well their server is performing. A HTML page is presented that gives the current server statistics in an easily readable form. If required this page can be made to automatically refresh (given a compatible browser). Another page gives a simple machine-readable list of the current server state. The details given are: * The number of workers serving requests * The number of idle workers * The status of each worker, the number of requests that worker has performed and the total number of bytes served by the worker (\*) * A total number of accesses and byte count served (\*) * The time the server was started/restarted and the time it has been running for * Averages giving the number of requests per second, the number of bytes served per second and the average number of bytes per request (\*) * The current percentage CPU used by each worker and in total by all workers combined (\*) * The current hosts and requests being processed (\*) The lines marked "(\*)" are only available if `[ExtendedStatus](core#extendedstatus)` is `On`. In version 2.3.6, loading mod\_status will toggle `[ExtendedStatus](core#extendedstatus)` On by default. Enabling Status Support ----------------------- To enable status reports only for browsers from the example.com domain add this code to your `httpd.conf` configuration file ``` <Location "/server-status"> SetHandler server-status Require host example.com </Location> ``` You can now access server statistics by using a Web browser to access the page `http://your.server.name/server-status` Automatic Updates ----------------- You can get the status page to update itself automatically if you have a browser that supports "refresh". Access the page `http://your.server.name/server-status?refresh=N` to refresh the page every N seconds. Machine Readable Status File ---------------------------- A machine-readable version of the status file is available by accessing the page `http://your.server.name/server-status?auto`. This is useful when automatically run, see the Perl program `log_server_status`, which you will find in the `/support` directory of your Apache HTTP Server installation. **It should be noted that if `<mod_status>` is loaded into the server, its handler capability is available in *all* configuration files, including *per*-directory files (*e.g.*, `.htaccess`). This may have security-related ramifications for your site.** Using server-status to troubleshoot ----------------------------------- The `server-status` page may be used as a starting place for troubleshooting a situation where your server is consuming all available resources (CPU or memory), and you wish to identify which requests or clients are causing the problem. First, ensure that you have `[ExtendedStatus](core#extendedstatus)` set on, so that you can see the full request and client information for each child or thread. Now look in your process list (using `top`, or similar process viewing utility) to identify the specific processes that are the main culprits. Order the output of `top` by CPU usage, or memory usage, depending on what problem you're trying to address. Reload the `server-status` page, and look for those process ids, and you'll be able to see what request is being served by that process, for what client. Requests are transient, so you may need to try several times before you catch it in the act, so to speak. This process *should* give you some idea what client, or what type of requests, are primarily responsible for your load problems. Often you will identify a particular web application that is misbehaving, or a particular client that is attacking your site. apache_http_server Apache Module mod_proxy_html Apache Module mod\_proxy\_html ============================== | | | | --- | --- | | Description: | Rewrite HTML links in to ensure they are addressable from Clients' networks in a proxy context. | | Status: | Base | | Module Identifier: | proxy\_html\_module | | Source File: | mod\_proxy\_html.c | | Compatibility: | Version 2.4 and later. Available as a third-party module for earlier 2.x versions | ### Summary This module provides an output filter to rewrite HTML links in a proxy situation, to ensure that links work for users outside the proxy. It serves the same purpose as Apache's `[ProxyPassReverse](mod_proxy#proxypassreverse)` directive does for HTTP headers, and is an essential component of a reverse proxy. For example, if a company has an application server at `appserver.example.com` that is only visible from within the company's internal network, and a public webserver `www.example.com`, they may wish to provide a gateway to the application server at `http://www.example.com/appserver/`. When the application server links to itself, those links need to be rewritten to work through the gateway. `<mod_proxy_html>` serves to rewrite `<a href="http://appserver.example.com/foo/bar.html">foobar</a>` to `<a href="http://www.example.com/appserver/foo/bar.html">foobar</a>` making it accessible from outside. mod\_proxy\_html was originally developed at WebÞing, whose extensive [documentation](http://apache.webthing.com/mod_proxy_html/) may be useful to users. ProxyHTMLBufSize Directive -------------------------- | | | | --- | --- | | Description: | Sets the buffer size increment for buffering inline scripts and stylesheets. | | Syntax: | ``` ProxyHTMLBufSize bytes ``` | | Default: | ``` ProxyHTMLBufSize 8192 ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party for earlier 2.x versions | In order to parse non-HTML content (stylesheets and scripts) embedded in HTML documents, `<mod_proxy_html>` has to read the entire script or stylesheet into a buffer. This buffer will be expanded as necessary to hold the largest script or stylesheet in a page, in increments of bytes as set by this directive. The default is 8192, and will work well for almost all pages. However, if you know you're proxying pages containing stylesheets and/or scripts bigger than 8K (that is, for a single script or stylesheet, NOT in total), it will be more efficient to set a larger buffer size and avoid the need to resize the buffer dynamically during a request. ProxyHTMLCharsetOut Directive ----------------------------- | | | | --- | --- | | Description: | Specify a charset for mod\_proxy\_html output. | | Syntax: | ``` ProxyHTMLCharsetOut Charset | * ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party for earlier 2.x versions | This selects an encoding for mod\_proxy\_html output. It should not normally be used, as any change from the default `UTF-8` (Unicode - as used internally by libxml2) will impose an additional processing overhead. The special token `ProxyHTMLCharsetOut *` will generate output using the same encoding as the input. Note that this relies on `<mod_xml2enc>` being loaded. ProxyHTMLDocType Directive -------------------------- | | | | --- | --- | | Description: | Sets an HTML or XHTML document type declaration. | | Syntax: | ``` ProxyHTMLDocType HTML|XHTML [Legacy] OR ProxyHTMLDocType fpi [SGML|XML] ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party for earlier 2.x versions | In the first form, documents will be declared as HTML 4.01 or XHTML 1.0 according to the option selected. This option also determines whether HTML or XHTML syntax is used for output. Note that the format of the documents coming from the backend server is immaterial: the parser will deal with it automatically. If the optional second argument is set to `Legacy`, documents will be declared "Transitional", an option that may be necessary if you are proxying pre-1998 content or working with defective authoring/publishing tools. In the second form, it will insert your own FPI. The optional second argument determines whether SGML/HTML or XML/XHTML syntax will be used. The default is changed to omitting any FPI, on the grounds that no FPI is better than a bogus one. If your backend generates decent HTML or XHTML, set it accordingly. If the first form is used, mod\_proxy\_html will also clean up the HTML to the specified standard. It cannot fix every error, but it will strip out bogus elements and attributes. It will also optionally log other errors at `[LogLevel](core#loglevel)` Debug. ProxyHTMLEnable Directive ------------------------- | | | | --- | --- | | Description: | Turns the proxy\_html filter on or off. | | Syntax: | ``` ProxyHTMLEnable On|Off ``` | | Default: | ``` ProxyHTMLEnable Off ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party module for earlier 2.x versions. | A simple switch to enable or disable the proxy\_html filter. If `<mod_xml2enc>` is loaded it will also automatically set up internationalisation support. Note that the proxy\_html filter will only act on HTML data (Content-Type text/html or application/xhtml+xml) and when the data are proxied. You can override this (at your own risk) by setting the PROXY\_HTML\_FORCE environment variable. ProxyHTMLEvents Directive ------------------------- | | | | --- | --- | | Description: | Specify attributes to treat as scripting events. | | Syntax: | ``` ProxyHTMLEvents attribute [attribute ...] ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party for earlier 2.x versions | Specifies one or more attributes to treat as scripting events and apply `[ProxyHTMLURLMap](#proxyhtmlurlmap)`s to where enabled. You can specify any number of attributes in one or more `ProxyHTMLEvents` directives. Normally you'll set this globally. If you set `ProxyHTMLEvents` in more than one scope so that one overrides the other, you'll need to specify a complete set in each of those scopes. A default configuration is supplied in proxy-html.conf and defines the events in standard HTML 4 and XHTML 1. ProxyHTMLExtended Directive --------------------------- | | | | --- | --- | | Description: | Determines whether to fix links in inline scripts, stylesheets, and scripting events. | | Syntax: | ``` ProxyHTMLExtended On|Off ``` | | Default: | ``` ProxyHTMLExtended Off ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party for earlier 2.x versions | Set to `Off`, HTML links are rewritten according to the `[ProxyHTMLURLMap](#proxyhtmlurlmap)` directives, but links appearing in Javascript and CSS are ignored. Set to `On`, all scripting events (as determined by `[ProxyHTMLEvents](#proxyhtmlevents)`) and embedded scripts or stylesheets are also processed by the `[ProxyHTMLURLMap](#proxyhtmlurlmap)` rules, according to the flags set for each rule. Since this requires more parsing, performance will be best if you only enable it when strictly necessary. You'll also need to take care over patterns matched, since the parser has no knowledge of what is a URL within an embedded script or stylesheet. In particular, extended matching of `/` is likely to lead to false matches. ProxyHTMLFixups Directive ------------------------- | | | | --- | --- | | Description: | Fixes for simple HTML errors. | | Syntax: | ``` ProxyHTMLFixups [lowercase] [dospath] [reset] ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party for earlier 2.x versions | This directive takes one to three arguments as follows: * `lowercase` Urls are rewritten to lowercase * `dospath` Backslashes in URLs are rewritten to forward slashes. * `reset` Unset any options set at a higher level in the configuration. Take care when using these. The fixes will correct certain authoring mistakes, but risk also erroneously fixing links that were correct to start with. Only use them if you know you have a broken backend server. ProxyHTMLInterp Directive ------------------------- | | | | --- | --- | | Description: | Enables per-request interpolation of `ProxyHTMLURLMap` rules. | | Syntax: | ``` ProxyHTMLInterp On|Off ``` | | Default: | ``` ProxyHTMLInterp Off ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party module for earlier 2.x versions | This enables per-request interpolation in `[ProxyHTMLURLMap](#proxyhtmlurlmap)` to- and from- patterns. If interpolation is not enabled, all rules are pre-compiled at startup. With interpolation, they must be re-compiled for every request, which implies an extra processing overhead. It should therefore be enabled only when necessary. ProxyHTMLLinks Directive ------------------------ | | | | --- | --- | | Description: | Specify HTML elements that have URL attributes to be rewritten. | | Syntax: | ``` ProxyHTMLLinks element attribute [attribute2 ...] ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party for earlier 2.x versions | Specifies elements that have URL attributes that should be rewritten using standard `[ProxyHTMLURLMap](#proxyhtmlurlmap)`s. You will need one `ProxyHTMLLinks` directive per element, but it can have any number of attributes. Normally you'll set this globally. If you set `ProxyHTMLLinks` in more than one scope so that one overrides the other, you'll need to specify a complete set in each of those scopes. A default configuration is supplied in proxy-html.conf and defines the HTML links for standard HTML 4 and XHTML 1. ### Examples from proxy-html.conf ``` ProxyHTMLLinks a href ProxyHTMLLinks area href ProxyHTMLLinks link href ProxyHTMLLinks img src longdesc usemap ProxyHTMLLinks object classid codebase data usemap ProxyHTMLLinks q cite ProxyHTMLLinks blockquote cite ProxyHTMLLinks ins cite ProxyHTMLLinks del cite ProxyHTMLLinks form action ProxyHTMLLinks input src usemap ProxyHTMLLinks head profile ProxyHTMLLinks base href ProxyHTMLLinks script src for ``` ProxyHTMLMeta Directive ----------------------- | | | | --- | --- | | Description: | Turns on or off extra pre-parsing of metadata in HTML `<head>` sections. | | Syntax: | ``` ProxyHTMLMeta On|Off ``` | | Default: | ``` ProxyHTMLMeta Off ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party module for earlier 2.x versions. | This turns on or off pre-parsing of metadata in HTML `<head>` sections. If not required, turning ProxyHTMLMeta Off will give a small performance boost by skipping this parse step. However, it is sometimes necessary for internationalisation to work correctly. `ProxyHTMLMeta` has two effects. Firstly and most importantly it enables detection of character encodings declared in the form ``` <meta http-equiv="Content-Type" content="text/html;charset=foo"> ``` or, in the case of an XHTML document, an XML declaration. It is NOT required if the charset is declared in a real HTTP header (which is always preferable) from the backend server, nor if the document is utf-8 (unicode) or a subset such as ASCII. You may also be able to dispense with it where documents use a default declared using `[xml2EncDefault](mod_xml2enc#xml2encdefault)`, but that risks propagating an incorrect declaration. A `[ProxyHTMLCharsetOut](#proxyhtmlcharsetout)` can remove that risk, but is likely to be a bigger processing overhead than enabling ProxyHTMLMeta. The other effect of enabling `ProxyHTMLMeta` is to parse all `<meta http-equiv=...>` declarations and convert them to real HTTP headers, in keeping with the original purpose of this form of the HTML <meta> element. **Warning** Because ProxyHTMLMeta promotes **all** `http-equiv` elements to HTTP headers, it is important that you only enable it in cases where you trust the HTML content as much as you trust the upstream server. If the HTML is controlled by bad actors, it will be possible for them to inject arbitrary, possibly malicious, HTTP headers into your server's responses. ProxyHTMLStripComments Directive -------------------------------- | | | | --- | --- | | Description: | Determines whether to strip HTML comments. | | Syntax: | ``` ProxyHTMLStripComments On|Off ``` | | Default: | ``` ProxyHTMLStripComments Off ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party for earlier 2.x versions | This directive will cause mod\_proxy\_html to strip HTML comments. Note that this will also kill off any scripts or styles embedded in comments (a bogosity introduced in 1995/6 with Netscape 2 for the benefit of then-older browsers, but still in use today). It may also interfere with comment-based processors such as SSI or ESI: be sure to run any of those *before* mod\_proxy\_html in the filter chain if stripping comments! ProxyHTMLURLMap Directive ------------------------- | | | | --- | --- | | Description: | Defines a rule to rewrite HTML links | | Syntax: | ``` ProxyHTMLURLMap from-pattern to-pattern [flags] [cond] ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_proxy\_html | | Compatibility: | Version 2.4 and later; available as a third-party module for earlier 2.x versions. | This is the key directive for rewriting HTML links. When parsing a document, whenever a link target matches from-pattern, the matching portion will be rewritten to to-pattern, as modified by any flags supplied and by the `[ProxyHTMLExtended](#proxyhtmlextended)` directive. Only the elements specified using the `[ProxyHTMLLinks](#proxyhtmllinks)` directive will be considered as HTML links. The optional third argument may define any of the following **Flags**. Flags are case-sensitive. h Ignore HTML links (pass through unchanged) e Ignore scripting events (pass through unchanged) c Pass embedded script and style sections through untouched. L Last-match. If this rule matches, no more rules are applied (note that this happens automatically for HTML links). l Opposite to L. Overrides the one-change-only default behaviour with HTML links. R Use Regular Expression matching-and-replace. `from-pattern` is a regexp, and `to-pattern` a replacement string that may be based on the regexp. Regexp memory is supported: you can use brackets () in the `from-pattern` and retrieve the matches with $1 to $9 in the `to-pattern`. If R is not set, it will use string-literal search-and-replace. The logic is *starts-with* in HTML links, but *contains* in scripting events and embedded script and style sections. x Use POSIX extended Regular Expressions. Only applicable with R. i Case-insensitive matching. Only applicable with R. n Disable regexp memory (for speed). Only applicable with R. s Line-based regexp matching. Only applicable with R. ^ Match at start only. This applies only to string matching (not regexps) and is irrelevant to HTML links. $ Match at end only. This applies only to string matching (not regexps) and is irrelevant to HTML links. V Interpolate environment variables in `to-pattern`. A string of the form `${varname|default}` will be replaced by the value of environment variable `varname`. If that is unset, it is replaced by `default`. The `|default` is optional. NOTE: interpolation will only be enabled if `[ProxyHTMLInterp](#proxyhtmlinterp)` is On. v Interpolate environment variables in `from-pattern`. Patterns supported are as above. NOTE: interpolation will only be enabled if `[ProxyHTMLInterp](#proxyhtmlinterp)` is On. The optional fourth **cond** argument defines a condition that will be evaluated per Request, provided `[ProxyHTMLInterp](#proxyhtmlinterp)` is On. If the condition evaluates FALSE the map will not be applied in this request. If TRUE, or if no condition is defined, the map is applied. A **cond** is evaluated by the [Expression Parser](../expr). In addition, the simpler syntax of conditions in mod\_proxy\_html 3.x for HTTPD 2.0 and 2.2 is also supported.
programming_docs
apache_http_server Apache Module mod_charset_lite Apache Module mod\_charset\_lite ================================ | | | | --- | --- | | Description: | Specify character set translation or recoding | | Status: | Extension | | Module Identifier: | charset\_lite\_module | | Source File: | mod\_charset\_lite.c | ### Summary `<mod_charset_lite>` allows the server to change the character set of responses before sending them to the client. In an EBCDIC environment, Apache always translates HTTP protocol content (e.g. response headers) from the code page of the Apache process locale to ISO-8859-1, but not the body of responses. In any environment, `<mod_charset_lite>` can be used to specify that response bodies should be translated. For example, if files are stored in EBCDIC, then `<mod_charset_lite>` can translate them to ISO-8859-1 before sending them to the client. This module provides a small subset of configuration mechanisms implemented by Russian Apache and its associated `mod_charset`. Common Problems --------------- ### Invalid character set names The character set name parameters of `[CharsetSourceEnc](#charsetsourceenc)` and `[CharsetDefault](#charsetdefault)` must be acceptable to the translation mechanism used by [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary") on the system where `<mod_charset_lite>` is deployed. These character set names are not standardized and are usually not the same as the corresponding values used in http headers. Currently, APR can only use iconv(3), so you can easily test your character set names using the iconv(1) program, as follows: ``` iconv -f charsetsourceenc-value -t charsetdefault-value ``` ### Mismatch between character set of content and translation rules If the translation rules don't make sense for the content, translation can fail in various ways, including: * The translation mechanism may return a bad return code, and the connection will be aborted. * The translation mechanism may silently place special characters (e.g., question marks) in the output buffer when it cannot translate the input buffer. CharsetDefault Directive ------------------------ | | | | --- | --- | | Description: | Charset to translate into | | Syntax: | ``` CharsetDefault charset ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_charset\_lite | The `CharsetDefault` directive specifies the charset that content in the associated container should be translated to. The value of the charset argument must be accepted as a valid character set name by the character set support in [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary"). Generally, this means that it must be supported by iconv. ### Example ``` <Directory "/export/home/trawick/apacheinst/htdocs/convert"> CharsetSourceEnc UTF-16BE CharsetDefault ISO-8859-1 </Directory> ``` Specifying the same charset for both `[CharsetSourceEnc](#charsetsourceenc)` and `[CharsetDefault](#charsetdefault)` disables translation. The charset need not match the charset of the response, but it must be a valid charset on the system. CharsetOptions Directive ------------------------ | | | | --- | --- | | Description: | Configures charset translation behavior | | Syntax: | ``` CharsetOptions option [option] ... ``` | | Default: | ``` CharsetOptions ImplicitAdd ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_charset\_lite | The `CharsetOptions` directive configures certain behaviors of `<mod_charset_lite>`. Option can be one of `ImplicitAdd | NoImplicitAdd` The `ImplicitAdd` keyword specifies that `<mod_charset_lite>` should implicitly insert its filter when the configuration specifies that the character set of content should be translated. If the filter chain is explicitly configured using the `[AddOutputFilter](mod_mime#addoutputfilter)` directive, `NoImplicitAdd` should be specified so that `<mod_charset_lite>` doesn't add its filter. `TranslateAllMimeTypes | NoTranslateAllMimeTypes` Normally, `<mod_charset_lite>` will only perform translation on a small subset of possible mimetypes. When the `TranslateAllMimeTypes` keyword is specified for a given configuration section, translation is performed without regard for mimetype. CharsetSourceEnc Directive -------------------------- | | | | --- | --- | | Description: | Source charset of files | | Syntax: | ``` CharsetSourceEnc charset ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | FileInfo | | Status: | Extension | | Module: | mod\_charset\_lite | The `CharsetSourceEnc` directive specifies the source charset of files in the associated container. The value of the charset argument must be accepted as a valid character set name by the character set support in [APR](https://httpd.apache.org/docs/2.4/en/glossary.html#apr "see glossary"). Generally, this means that it must be supported by iconv. ### Example ``` <Directory "/export/home/trawick/apacheinst/htdocs/convert"> CharsetSourceEnc UTF-16BE CharsetDefault ISO-8859-1 </Directory> ``` The character set names in this example work with the iconv translation support in Solaris 8. Specifying the same charset for both `[CharsetSourceEnc](#charsetsourceenc)` and `[CharsetDefault](#charsetdefault)` disables translation. The charset need not match the charset of the response, but it must be a valid charset on the system. apache_http_server Apache Module mod_watchdog Apache Module mod\_watchdog =========================== | | | | --- | --- | | Description: | provides infrastructure for other modules to periodically run tasks | | Status: | Base | | Module Identifier: | watchdog\_module | | Source File: | mod\_watchdog.c | | Compatibility: | Available in Apache 2.3 and later | ### Summary `<mod_watchdog>` defines programmatic hooks for other modules to periodically run tasks. These modules can register handlers for `<mod_watchdog>` hooks. Currently, the following modules in the Apache distribution use this functionality: * `<mod_heartbeat>` * `<mod_heartmonitor>` * `<mod_md>` * `<mod_proxy_hcheck>` To allow a module to use `<mod_watchdog>` functionality, `<mod_watchdog>` itself must be statically linked to the server core or, if a dynamic module, be loaded before the calling module. WatchdogInterval Directive -------------------------- | | | | --- | --- | | Description: | Watchdog interval in seconds | | Syntax: | ``` WatchdogInterval time-interval[s] ``` | | Default: | ``` WatchdogInterval 1 ``` | | Context: | server config | | Status: | Base | | Module: | mod\_watchdog | Sets the interval at which the watchdog\_step hook runs. Default is to run every second. apache_http_server Apache Module mod_auth_digest Apache Module mod\_auth\_digest =============================== | | | | --- | --- | | Description: | User authentication using MD5 Digest Authentication | | Status: | Extension | | Module Identifier: | auth\_digest\_module | | Source File: | mod\_auth\_digest.c | ### Summary This module implements HTTP Digest Authentication ([RFC2617](http://www.faqs.org/rfcs/rfc2617.html)), and provides an alternative to `<mod_auth_basic>` where the password is not transmitted as cleartext. However, this does **not** lead to a significant security advantage over basic authentication. On the other hand, the password storage on the server is much less secure with digest authentication than with basic authentication. Therefore, using basic auth and encrypting the whole connection using `<mod_ssl>` is a much better alternative. Using Digest Authentication --------------------------- To use MD5 Digest authentication, configure the location to be protected as shown in the below example: ### Example: ``` <Location "/private/"> AuthType Digest AuthName "private area" AuthDigestDomain "/private/" "http://mirror.my.dom/private2/" AuthDigestProvider file AuthUserFile "/web/auth/.digest_pw" Require valid-user </Location> ``` `[AuthDigestDomain](#authdigestdomain)` should list the locations that will be protected by this configuration. The password file referenced in the `[AuthUserFile](#authuserfile)` directive may be created and managed using the `[htdigest](../programs/htdigest)` tool. **Note** Digest authentication was intended to be more secure than basic authentication, but no longer fulfills that design goal. A man-in-the-middle attacker can trivially force the browser to downgrade to basic authentication. And even a passive eavesdropper can brute-force the password using today's graphics hardware, because the hashing algorithm used by digest authentication is too fast. Another problem is that the storage of the passwords on the server is insecure. The contents of a stolen htdigest file can be used directly for digest authentication. Therefore using `<mod_ssl>` to encrypt the whole connection is strongly recommended. `<mod_auth_digest>` only works properly on platforms where APR supports shared memory. AuthDigestAlgorithm Directive ----------------------------- | | | | --- | --- | | Description: | Selects the algorithm used to calculate the challenge and response hashes in digest authentication | | Syntax: | ``` AuthDigestAlgorithm MD5|MD5-sess ``` | | Default: | ``` AuthDigestAlgorithm MD5 ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_auth\_digest | The `AuthDigestAlgorithm` directive selects the algorithm used to calculate the challenge and response hashes. `MD5-sess` is not correctly implemented yet. AuthDigestDomain Directive -------------------------- | | | | --- | --- | | Description: | URIs that are in the same protection space for digest authentication | | Syntax: | ``` AuthDigestDomain URI [URI] ... ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_auth\_digest | The `AuthDigestDomain` directive allows you to specify one or more URIs which are in the same protection space (*i.e.* use the same realm and username/password info). The specified URIs are prefixes; the client will assume that all URIs "below" these are also protected by the same username/password. The URIs may be either absolute URIs (*i.e.* including a scheme, host, port, etc.) or relative URIs. This directive *should* always be specified and contain at least the (set of) root URI(s) for this space. Omitting to do so will cause the client to send the Authorization header for *every request* sent to this server. The URIs specified can also point to different servers, in which case clients (which understand this) will then share username/password info across multiple servers without prompting the user each time. AuthDigestNonceLifetime Directive --------------------------------- | | | | --- | --- | | Description: | How long the server nonce is valid | | Syntax: | ``` AuthDigestNonceLifetime seconds ``` | | Default: | ``` AuthDigestNonceLifetime 300 ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_auth\_digest | The `AuthDigestNonceLifetime` directive controls how long the server nonce is valid. When the client contacts the server using an expired nonce the server will send back a 401 with `stale=true`. If seconds is greater than 0 then it specifies the amount of time for which the nonce is valid; this should probably never be set to less than 10 seconds. If seconds is less than 0 then the nonce never expires. AuthDigestProvider Directive ---------------------------- | | | | --- | --- | | Description: | Sets the authentication provider(s) for this location | | Syntax: | ``` AuthDigestProvider provider-name [provider-name] ... ``` | | Default: | ``` AuthDigestProvider file ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_auth\_digest | The `AuthDigestProvider` directive sets which provider is used to authenticate the users for this location. The default `file` provider is implemented by the `<mod_authn_file>` module. Make sure that the chosen provider module is present in the server. See `<mod_authn_dbm>`, `<mod_authn_file>`, `<mod_authn_dbd>` and `<mod_authn_socache>` for providers. AuthDigestQop Directive ----------------------- | | | | --- | --- | | Description: | Determines the quality-of-protection to use in digest authentication | | Syntax: | ``` AuthDigestQop none|auth|auth-int [auth|auth-int] ``` | | Default: | ``` AuthDigestQop auth ``` | | Context: | directory, .htaccess | | Override: | AuthConfig | | Status: | Extension | | Module: | mod\_auth\_digest | The `AuthDigestQop` directive determines the quality-of-protection to use. `auth` will only do authentication (username/password); `auth-int` is authentication plus integrity checking (an MD5 hash of the entity is also computed and checked); `none` will cause the module to use the old RFC-2069 digest algorithm (which does not include integrity checking). Both `auth` and `auth-int` may be specified, in which the case the browser will choose which of these to use. `none` should only be used if the browser for some reason does not like the challenge it receives otherwise. `auth-int` is not implemented yet. AuthDigestShmemSize Directive ----------------------------- | | | | --- | --- | | Description: | The amount of shared memory to allocate for keeping track of clients | | Syntax: | ``` AuthDigestShmemSize size ``` | | Default: | ``` AuthDigestShmemSize 1000 ``` | | Context: | server config | | Status: | Extension | | Module: | mod\_auth\_digest | The `AuthDigestShmemSize` directive defines the amount of shared memory, that will be allocated at the server startup for keeping track of clients. Note that the shared memory segment cannot be set less than the space that is necessary for tracking at least *one* client. This value is dependent on your system. If you want to find out the exact value, you may simply set `AuthDigestShmemSize` to the value of `0` and read the error message after trying to start the server. The size is normally expressed in Bytes, but you may follow the number with a `K` or an `M` to express your value as KBytes or MBytes. For example, the following directives are all equivalent: ``` AuthDigestShmemSize 1048576 AuthDigestShmemSize 1024K AuthDigestShmemSize 1M ``` apache_http_server Apache Module mod_file_cache Apache Module mod\_file\_cache ============================== | | | | --- | --- | | Description: | Caches a static list of files in memory | | Status: | Experimental | | Module Identifier: | file\_cache\_module | | Source File: | mod\_file\_cache.c | ### Summary This module should be used with care. You can easily create a broken site using `<mod_file_cache>`, so read this document carefully. *Caching* frequently requested files that change very infrequently is a technique for reducing server load. `<mod_file_cache>` provides two techniques for caching frequently requested *static* files. Through configuration directives, you can direct `<mod_file_cache>` to either open then `mmap()` a file, or to pre-open a file and save the file's open *file handle*. Both techniques reduce server load when processing requests for these files by doing part of the work (specifically, the file I/O) for serving the file when the server is started rather than during each request. Notice: You cannot use this for speeding up CGI programs or other files which are served by special content handlers. It can only be used for regular files which are usually served by the Apache core content handler. This module is an extension of and borrows heavily from the `mod_mmap_static` module in Apache 1.3. Using mod\_file\_cache ---------------------- `<mod_file_cache>` caches a list of statically configured files via `[MMapFile](#mmapfile)` or `[CacheFile](#cachefile)` directives in the main server configuration. Not all platforms support both directives. You will receive an error message in the server error log if you attempt to use an unsupported directive. If given an unsupported directive, the server will start but the file will not be cached. On platforms that support both directives, you should experiment with both to see which works best for you. ### MMapFile Directive The `[MMapFile](#mmapfile)` directive of `<mod_file_cache>` maps a list of statically configured files into memory through the system call `mmap()`. This system call is available on most modern Unix derivatives, but not on all. There are sometimes system-specific limits on the size and number of files that can be `mmap()`ed, experimentation is probably the easiest way to find out. This `mmap()`ing is done once at server start or restart, only. So whenever one of the mapped files changes on the filesystem you *have* to restart the server (see the [Stopping and Restarting](../stopping) documentation). To reiterate that point: if the files are modified *in place* without restarting the server you may end up serving requests that are completely bogus. You should update files by unlinking the old copy and putting a new copy in place. Most tools such as `rdist` and `mv` do this. The reason why this modules doesn't take care of changes to the files is that this check would need an extra `stat()` every time which is a waste and against the intent of I/O reduction. ### CacheFile Directive The `[CacheFile](#cachefile)` directive of `<mod_file_cache>` opens an active *handle* or *file descriptor* to the file (or files) listed in the configuration directive and places these open file handles in the cache. When the file is requested, the server retrieves the handle from the cache and passes it to the `sendfile()` (or `TransmitFile()` on Windows), socket API. This file handle caching is done once at server start or restart, only. So whenever one of the cached files changes on the filesystem you *have* to restart the server (see the [Stopping and Restarting](../stopping) documentation). To reiterate that point: if the files are modified *in place* without restarting the server you may end up serving requests that are completely bogus. You should update files by unlinking the old copy and putting a new copy in place. Most tools such as `rdist` and `mv` do this. **Note** Don't bother asking for a directive which recursively caches all the files in a directory. Try this instead... See the `[Include](core#include)` directive, and consider this command: ``` find /www/htdocs -type f -print \ | sed -e 's/.*/mmapfile &/' > /www/conf/mmap.conf ``` CacheFile Directive ------------------- | | | | --- | --- | | Description: | Cache a list of file handles at startup time | | Syntax: | ``` CacheFile file-path [file-path] ... ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_file\_cache | The `CacheFile` directive opens handles to one or more files (given as whitespace separated arguments) and places these handles into the cache at server startup time. Handles to cached files are automatically closed on a server shutdown. When the files have changed on the filesystem, the server should be restarted to re-cache them. Be careful with the file-path arguments: They have to literally match the filesystem path Apache's URL-to-filename translation handlers create. We cannot compare inodes or other stuff to match paths through symbolic links *etc.* because that again would cost extra `stat()` system calls which is not acceptable. This module may or may not work with filenames rewritten by `<mod_alias>` or `<mod_rewrite>`. ### Example ``` CacheFile /usr/local/apache/htdocs/index.html ``` MMapFile Directive ------------------ | | | | --- | --- | | Description: | Map a list of files into memory at startup time | | Syntax: | ``` MMapFile file-path [file-path] ... ``` | | Context: | server config | | Status: | Experimental | | Module: | mod\_file\_cache | The `MMapFile` directive maps one or more files (given as whitespace separated arguments) into memory at server startup time. They are automatically unmapped on a server shutdown. When the files have changed on the filesystem at least a `HUP` or `USR1` signal should be send to the server to re-`mmap()` them. Be careful with the file-path arguments: They have to literally match the filesystem path Apache's URL-to-filename translation handlers create. We cannot compare inodes or other stuff to match paths through symbolic links *etc.* because that again would cost extra `stat()` system calls which is not acceptable. This module may or may not work with filenames rewritten by `<mod_alias>` or `<mod_rewrite>`. ### Example ``` MMapFile /usr/local/apache/htdocs/index.html ```
programming_docs
apache_http_server Apache Module mod_unixd Apache Module mod\_unixd ======================== | | | | --- | --- | | Description: | Basic (required) security for Unix-family platforms. | | Status: | Base | | Module Identifier: | unixd\_module | | Source File: | mod\_unixd.c | ChrootDir Directive ------------------- | | | | --- | --- | | Description: | Directory for apache to run chroot(8) after startup. | | Syntax: | ``` ChrootDir /path/to/directory ``` | | Default: | `none` | | Context: | server config | | Status: | Base | | Module: | `mod_unixd` | | Compatibility: | Available in Apache 2.2.10 and later | This directive tells the server to chroot(8) to the specified directory after startup, but before accepting requests over the 'net. Note that running the server under chroot is not simple, and requires additional setup, particularly if you are running scripts such as CGI or PHP. Please make sure you are properly familiar with the operation of chroot before attempting to use this feature. Group Directive --------------- | | | | --- | --- | | Description: | Group under which the server will answer requests | | Syntax: | ``` Group unix-group ``` | | Default: | ``` Group #-1 ``` | | Context: | server config | | Status: | Base | | Module: | mod\_unixd | The `Group` directive sets the group under which the server will answer requests. In order to use this directive, the server must be run initially as `root`. If you start the server as a non-root user, it will fail to change to the specified group, and will instead continue to run as the group of the original user. Unix-group is one of: A group name Refers to the given group by name. `#` followed by a group number. Refers to a group by its number. ### Example ``` Group www-group ``` It is recommended that you set up a new group specifically for running the server. Some admins use user `nobody`, but this is not always possible or desirable. **Security** Don't set `Group` (or `[User](#user)`) to `root` unless you know exactly what you are doing, and what the dangers are. ### See also * `[VHostGroup](mod_privileges#vhostgroup)` * `[SuexecUserGroup](mod_suexec#suexecusergroup)` Suexec Directive ---------------- | | | | --- | --- | | Description: | Enable or disable the suEXEC feature | | Syntax: | ``` Suexec On|Off ``` | | Default: | ``` On if suexec binary exists with proper owner and mode, Off otherwise ``` | | Context: | server config | | Status: | Base | | Module: | mod\_unixd | When On, startup will fail if the suexec binary doesn't exist or has an invalid owner or file mode. When Off, suEXEC will be disabled even if the suexec binary exists and has a valid owner and file mode. User Directive -------------- | | | | --- | --- | | Description: | The userid under which the server will answer requests | | Syntax: | ``` User unix-userid ``` | | Default: | ``` User #-1 ``` | | Context: | server config | | Status: | Base | | Module: | mod\_unixd | The `User` directive sets the user ID as which the server will answer requests. In order to use this directive, the server must be run initially as `root`. If you start the server as a non-root user, it will fail to change to the lesser privileged user, and will instead continue to run as that original user. If you do start the server as `root`, then it is normal for the parent process to remain running as root. Unix-userid is one of: A username Refers to the given user by name. # followed by a user number. Refers to a user by its number. The user should have no privileges that result in it being able to access files that are not intended to be visible to the outside world, and similarly, the user should not be able to execute code that is not meant for HTTP requests. It is recommended that you set up a new user and group specifically for running the server. Some admins use user `nobody`, but this is not always desirable, since the `nobody` user can have other uses on the system. **Security** Don't set `User` (or `[Group](#group)`) to `root` unless you know exactly what you are doing, and what the dangers are. ### See also * `[VHostUser](mod_privileges#vhostuser)` * `[SuexecUserGroup](mod_suexec#suexecusergroup)` apache_http_server Apache Module mod_proxy_http2 Apache Module mod\_proxy\_http2 =============================== | | | | --- | --- | | Description: | HTTP/2 support module for `<mod_proxy>` | | Status: | Extension | | Module Identifier: | proxy\_http2\_module | | Source File: | mod\_proxy\_http2.c | | Compatibility: | Available in httpd 2.4.19 and later | ### Summary `<mod_proxy_http2>` supports HTTP/2 only, it does *not* provide any downgrades to HTTP/1.1. This means that the backend needs to support HTTP/2 because HTTP/1.1 will not be used instead. This module *requires* the service of `<mod_proxy>`, so in order to get the ability of handling HTTP/2 proxy requests, `<mod_proxy>` and `<mod_proxy_http2>` need to be both loaded by the server. `<mod_proxy_http2>` works with incoming fronted requests using HTTP/1.1 or HTTP/2. In both cases, requests proxied to the same backend are sent over a single TCP connection whenever possible (namely when the connection can be re-used). Caveat: there will be no attempt to consolidate multiple HTTP/1.1 frontend requests (configured to be proxied to the same backend) into HTTP/2 streams belonging to the same HTTP/2 request. Each HTTP/1.1 frontend request will be proxied to the backend using a separate HTTP/2 request (trying to re-use the same TCP connection if possible). This module relies on [libnghttp2](http://nghttp2.org/) to provide the core http/2 engine. **Warning** This module is experimental. Its behaviors, directives, and defaults are subject to more change from release to release relative to other standard modules. Users are encouraged to consult the "CHANGES" file for potential updates. **Warning** Do not enable proxying until you have [secured your server](mod_proxy#access). Open proxy servers are dangerous both to your network and to the Internet at large. Basic Examples -------------- The examples below demonstrate how to configure HTTP/2 for backend connections for a reverse proxy. ### HTTP/2 (TLS) ``` ProxyPass "/app" "h2://app.example.com" ProxyPassReverse "/app" "https://app.example.com" ``` ### HTTP/2 (cleartext) ``` ProxyPass "/app" "h2c://app.example.com" ProxyPassReverse "/app" "http://app.example.com" ``` The schemes to configure above in `ProxyPassReverse` for reverse proxying `h2` (or `h2c`) protocols are the usual `https` (resp. `http`) as expected/used by the user agent. Request notes ------------- `<mod_proxy_http>` creates the following request notes for logging using the `%{VARNAME}n` format in `[LogFormat](mod_log_config#logformat)` or `[ErrorLogFormat](core#errorlogformat)`: proxy-source-port The local port used for the connection to the backend server. proxy-status The HTTP/2 status received from the backend server. apache_http_server Apache Module mod_heartbeat Apache Module mod\_heartbeat ============================ | | | | --- | --- | | Description: | Sends messages with server status to frontend proxy | | Status: | Experimental | | Module Identifier: | heartbeat\_module | | Source File: | mod\_heartbeat | | Compatibility: | Available in Apache 2.3 and later | ### Summary `<mod_heartbeat>` sends multicast messages to a `<mod_heartmonitor>` listener that advertises the servers current connection count. Usually, `<mod_heartmonitor>` will be running on a proxy server with `<mod_lbmethod_heartbeat>` loaded, which allows `[ProxyPass](mod_proxy#proxypass)` to use the "heartbeat" *lbmethod* inside of `[ProxyPass](mod_proxy#proxypass)`. `<mod_heartbeat>` itself is loaded on the origin server(s) that serve requests through the proxy server(s). To use `<mod_heartbeat>`, `<mod_status>` and `<mod_watchdog>` must be either a static modules or, if a dynamic module, must be loaded before `<mod_heartbeat>`. Consuming mod\_heartbeat Output ------------------------------- Every 1 second, this module generates a single multicast UDP packet, containing the number of busy and idle workers. The packet is a simple ASCII format, similar to GET query parameters in HTTP. ### An Example Packet `v=1&ready=75&busy=0` Consumers should handle new variables besides busy and ready, separated by '&', being added in the future. HeartbeatAddress Directive -------------------------- | | | | --- | --- | | Description: | Multicast address for heartbeat packets | | Syntax: | ``` HeartbeatAddress addr:port ``` | | Default: | `disabled` | | Context: | server config | | Status: | Experimental | | Module: | mod\_heartbeat | The `HeartbeatAddress` directive specifies the multicast address to which `<mod_heartbeat>` will send status information. This address will usually correspond to a configured `[HeartbeatListen](mod_heartmonitor#heartbeatlisten)` on a frontend proxy system. ``` HeartbeatAddress 239.0.0.1:27999 ``` apache_http_server Apache Module mod_socache_redis Apache Module mod\_socache\_redis ================================= | | | | --- | --- | | Description: | Redis based shared object cache provider. | | Status: | Extension | | Module Identifier: | socache\_redis\_module | | Source File: | mod\_socache\_redis.c | | Compatibility: | Available in Apache 2.4.39 and later | ### Summary `<mod_socache_redis>` is a shared object cache provider which provides for creation and access to a cache backed by the [Redis](https://redis.io/) high-performance, distributed memory object caching system. This shared object cache provider's "create" method requires a comma separated list of memcached host/port specifications. If using this provider via another modules configuration (such as `[SSLSessionCache](mod_ssl#sslsessioncache)`), provide the list of servers as the optional "arg" parameter. ``` SSLSessionCache redis:redis.example.com:12345,redis2.example.com:12345 ``` Details of other shared object cache providers can be found [here](../socache). RedisConnPoolTTL Directive -------------------------- | | | | --- | --- | | Description: | TTL used for the connection pool with the Redis server(s) | | Syntax: | ``` RedisConnPoolTTL num[units] ``` | | Default: | ``` RedisConnPoolTTL 15s ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_socache\_redis | | Compatibility: | Available in Apache 2.4.39 and later | Set the time to keep idle connections with the Redis server(s) alive (threaded platforms only). Valid values for `RedisConnPoolTTL` are times up to one hour. 0 means no timeout. This timeout defaults to units of seconds, but accepts suffixes for milliseconds (ms), seconds (s), minutes (min), and hours (h). ``` # Set a timeout of 10 minutes RedisConnPoolTTL 10min # Set a timeout of 60 seconds RedisConnPoolTTL 60 ``` RedisTimeout Directive ---------------------- | | | | --- | --- | | Description: | R/W timeout used for the connection with the Redis server(s) | | Syntax: | ``` RedisTimeout num[units] ``` | | Default: | ``` RedisTimeout 5s ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_socache\_redis | | Compatibility: | Available in Apache 2.4.39 and later | Set the Read/Write timeout used for the connection with the Redis server(s). Valid values for `RedisTimeout` are times up to one hour. 0 means no timeout. This timeout defaults to units of seconds, but accepts suffixes for milliseconds (ms), seconds (s), minutes (min), and hours (h). ``` # Set a timeout of 10 minutes RedisTimeout 10min # Set a timeout of 60 seconds RedisTimeout 60 ``` apache_http_server Apache Module mod_macro Apache Module mod\_macro ======================== | | | | --- | --- | | Description: | Provides macros within apache httpd runtime configuration files | | Status: | Base | | Module Identifier: | macro\_module | | Source File: | mod\_macro.c | | Compatibility: | Available in httpd 2.4.5 and later | ### Summary Provides macros within Apache httpd runtime configuration files, to ease the process of creating numerous similar configuration blocks. When the server starts up, the macros are expanded using the provided parameters, and the result is processed as along with the rest of the configuration file. Usage ----- Macros are defined using `[<Macro>](#macro)` blocks, which contain the portion of your configuration that needs to be repeated, complete with variables for those parts that will need to be substituted. For example, you might use a macro to define a `[<VirtualHost>](core#virtualhost)` block, in order to define multiple similar virtual hosts: ``` <Macro VHost $name $domain> <VirtualHost *:80> ServerName $domain ServerAlias www.$domain DocumentRoot "/var/www/vhosts/$name" ErrorLog "/var/log/httpd/$name.error_log" CustomLog "/var/log/httpd/$name.access_log" combined </VirtualHost> </Macro> ``` Macro names are case-insensitive, like httpd configuration directives. However, variable names are case sensitive. You would then invoke this macro several times to create virtual hosts: ``` Use VHost example example.com Use VHost myhost hostname.org Use VHost apache apache.org UndefMacro VHost ``` At server startup time, each of these `[Use](#use)` invocations would be expanded into a full virtualhost, as described by the `[<Macro>](#macro)` definition. The `[UndefMacro](#undefmacro)` directive is used so that later macros using the same variable names don't result in conflicting definitions. A more elaborate version of this example may be seen below in the Examples section. Tips ---- Parameter names should begin with a sigil such as `$`, `%`, or `@`, so that they are clearly identifiable, and also in order to help deal with interactions with other directives, such as the core `[Define](core#define)` directive. Failure to do so will result in a warning. Nevertheless, you are encouraged to have a good knowledge of your entire server configuration in order to avoid reusing the same variables in different scopes, which can cause confusion. Parameters prefixed with either `$` or `%` are not escaped. Parameters prefixes with `@` are escaped in quotes. Avoid using a parameter which contains another parameter as a prefix, (For example, `$win` and `$winter`) as this may cause confusion at expression evaluation time. In the event of such confusion, the longest possible parameter name is used. If you want to use a value within another string, it is useful to surround the parameter in braces, to avoid confusion: ``` <Macro DocRoot ${docroot}> DocumentRoot "/var/www/${docroot}/htdocs" </Macro> ``` Examples -------- ### Virtual Host Definition A common usage of `<mod_macro>` is for the creation of dynamically-generated virtual hosts. ``` ## Define a VHost Macro for repetitive configurations <Macro VHost $host $port $dir> Listen $port <VirtualHost *:$port> ServerName $host DocumentRoot "$dir" # Public document root <Directory "$dir"> Require all granted </Directory> # limit access to intranet subdir. <Directory "$dir/intranet"> Require ip 10.0.0.0/8 </Directory> </VirtualHost> </Macro> ## Use of VHost with different arguments. Use VHost www.apache.org 80 /vhosts/apache/htdocs Use VHost example.org 8080 /vhosts/example/htdocs Use VHost www.example.fr 1234 /vhosts/example.fr/htdocs ``` ### Removal of a macro definition It's recommended that you undefine a macro once you've used it. This avoids confusion in a complex configuration file where there may be conflicts in variable names. ``` <Macro DirGroup $dir $group> <Directory "$dir"> Require group $group </Directory> </Macro> Use DirGroup /www/apache/private private Use DirGroup /www/apache/server admin UndefMacro DirGroup ``` <Macro> Directive ----------------- | | | | --- | --- | | Description: | Define a configuration file macro | | Syntax: | ``` <Macro name [par1 .. parN]> ... </Macro> ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_macro | The `<Macro>` directive controls the definition of a macro within the server runtime configuration files. The first argument is the name of the macro. Other arguments are parameters to the macro. It is good practice to prefix parameter names with any of '`$%@`', and not macro names with such characters. ``` <Macro LocalAccessPolicy> Require ip 10.2.16.0/24 </Macro> <Macro RestrictedAccessPolicy $ipnumbers> Require ip $ipnumbers </Macro> ``` UndefMacro Directive -------------------- | | | | --- | --- | | Description: | Undefine a macro | | Syntax: | ``` UndefMacro name ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_macro | The `UndefMacro` directive undefines a macro which has been defined before hand. ``` UndefMacro LocalAccessPolicy UndefMacro RestrictedAccessPolicy ``` Use Directive ------------- | | | | --- | --- | | Description: | Use a macro | | Syntax: | ``` Use name [value1 ... valueN] ``` | | Context: | server config, virtual host, directory | | Status: | Base | | Module: | mod\_macro | The `Use` directive controls the use of a macro. The specified macro is expanded. It must be given the same number of arguments as in the macro definition. The provided values are associated to their corresponding initial parameters and are substituted before processing. ``` Use LocalAccessPolicy ... Use RestrictedAccessPolicy "192.54.172.0/24 192.54.148.0/24" ``` is equivalent, with the macros defined above, to: ``` Require ip 10.2.16.0/24 ... Require ip 192.54.172.0/24 192.54.148.0/24 ``` apache_http_server Apache Module mod_proxy Apache Module mod\_proxy ======================== | | | | --- | --- | | Description: | Multi-protocol proxy/gateway server | | Status: | Extension | | Module Identifier: | proxy\_module | | Source File: | mod\_proxy.c | ### Summary **Warning** Do not enable proxying with `[ProxyRequests](#proxyrequests)` until you have [secured your server](#access). Open proxy servers are dangerous both to your network and to the Internet at large. `<mod_proxy>` and related modules implement a proxy/gateway for Apache HTTP Server, supporting a number of popular protocols as well as several different load balancing algorithms. Third-party modules can add support for additional protocols and load balancing algorithms. A set of modules must be loaded into the server to provide the necessary features. These modules can be included statically at build time or dynamically via the `[LoadModule](mod_so#loadmodule)` directive). The set must include: * `<mod_proxy>`, which provides basic proxy capabilities * `<mod_proxy_balancer>` and one or more balancer modules if load balancing is required. (See `<mod_proxy_balancer>` for more information.) * one or more proxy scheme, or protocol, modules: | Protocol | Module | | --- | --- | | AJP13 (Apache JServe Protocol version 1.3) | `mod_proxy_ajp` | | CONNECT (for SSL) | `mod_proxy_connect` | | FastCGI | `mod_proxy_fcgi` | | ftp | `mod_proxy_ftp` | | HTTP/0.9, HTTP/1.0, and HTTP/1.1 | `mod_proxy_http` | | HTTP/2.0 | `mod_proxy_http2` | | SCGI | `mod_proxy_scgi` | | UWSGI | `mod_proxy_uwsgi` | | WS and WSS (Web-sockets) | `mod_proxy_wstunnel` | In addition, extended features are provided by other modules. Caching is provided by `<mod_cache>` and related modules. The ability to contact remote servers using the SSL/TLS protocol is provided by the `SSLProxy*` directives of `<mod_ssl>`. These additional modules will need to be loaded and configured to take advantage of these features. Forward Proxies and Reverse Proxies/Gateways -------------------------------------------- Apache HTTP Server can be configured in both a forward and reverse proxy (also known as gateway) mode. An ordinary forward proxy is an intermediate server that sits between the client and the *origin server*. In order to get content from the origin server, the client sends a request to the proxy naming the origin server as the target. The proxy then requests the content from the origin server and returns it to the client. The client must be specially configured to use the forward proxy to access other sites. A typical usage of a forward proxy is to provide Internet access to internal clients that are otherwise restricted by a firewall. The forward proxy can also use caching (as provided by `<mod_cache>`) to reduce network usage. The forward proxy is activated using the `[ProxyRequests](#proxyrequests)` directive. Because forward proxies allow clients to access arbitrary sites through your server and to hide their true origin, it is essential that you [secure your server](#access) so that only authorized clients can access the proxy before activating a forward proxy. A reverse proxy (or gateway), by contrast, appears to the client just like an ordinary web server. No special configuration on the client is necessary. The client makes ordinary requests for content in the namespace of the reverse proxy. The reverse proxy then decides where to send those requests and returns the content as if it were itself the origin. A typical usage of a reverse proxy is to provide Internet users access to a server that is behind a firewall. Reverse proxies can also be used to balance load among several back-end servers or to provide caching for a slower back-end server. In addition, reverse proxies can be used simply to bring several servers into the same URL space. A reverse proxy is activated using the `[ProxyPass](#proxypass)` directive or the `[P]` flag to the `[RewriteRule](mod_rewrite#rewriterule)` directive. It is **not** necessary to turn `[ProxyRequests](#proxyrequests)` on in order to configure a reverse proxy. Basic Examples -------------- The examples below are only a very basic idea to help you get started. Please read the documentation on the individual directives. In addition, if you wish to have caching enabled, consult the documentation from `<mod_cache>`. ### Reverse Proxy ``` ProxyPass "/foo" "http://foo.example.com/bar" ProxyPassReverse "/foo" "http://foo.example.com/bar" ``` ### Forward Proxy ``` ProxyRequests On ProxyVia On <Proxy "*"> Require host internal.example.com </Proxy> ``` Access via Handler ------------------ You can also force a request to be handled as a reverse-proxy request, by creating a suitable Handler pass-through. The example configuration below will pass all requests for PHP scripts to the specified FastCGI server using reverse proxy: ### Reverse Proxy PHP scripts ``` <FilesMatch "\.php$"> # Unix sockets require 2.4.7 or later SetHandler "proxy:unix:/path/to/app.sock|fcgi://localhost/" </FilesMatch> ``` This feature is available in Apache HTTP Server 2.4.10 and later. Workers ------- The proxy manages the configuration of origin servers and their communication parameters in objects called workers. There are two built-in workers: the default forward proxy worker and the default reverse proxy worker. Additional workers can be configured explicitly. The two default workers have a fixed configuration and will be used if no other worker matches the request. They do not use HTTP Keep-Alive or connection reuse. The TCP connections to the origin server will instead be opened and closed for each request. Explicitly configured workers are identified by their URL. They are usually created and configured using `[ProxyPass](#proxypass)` or `[ProxyPassMatch](#proxypassmatch)` when used for a reverse proxy: ``` ProxyPass "/example" "http://backend.example.com" connectiontimeout=5 timeout=30 ``` This will create a worker associated with the origin server URL `http://backend.example.com` that will use the given timeout values. When used in a forward proxy, workers are usually defined via the `[ProxySet](#proxyset)` directive: ``` ProxySet "http://backend.example.com" connectiontimeout=5 timeout=30 ``` or alternatively using `[Proxy](#proxy)` and `[ProxySet](#proxyset)`: ``` <Proxy "http://backend.example.com"> ProxySet connectiontimeout=5 timeout=30 </Proxy> ``` Using explicitly configured workers in the forward mode is not very common, because forward proxies usually communicate with many different origin servers. Creating explicit workers for some of the origin servers can still be useful if they are used very often. Explicitly configured workers have no concept of forward or reverse proxying by themselves. They encapsulate a common concept of communication with origin servers. A worker created by `[ProxyPass](#proxypass)` for use in a reverse proxy will also be used for forward proxy requests whenever the URL to the origin server matches the worker URL, and vice versa. The URL identifying a direct worker is the URL of its origin server including any path components given: ``` ProxyPass "/examples" "http://backend.example.com/examples" ProxyPass "/docs" "http://backend.example.com/docs" ``` This example defines two different workers, each using a separate connection pool and configuration. **Worker Sharing** Worker sharing happens if the worker URLs overlap, which occurs when the URL of some worker is a leading substring of the URL of another worker defined later in the configuration file. In the following example ``` ProxyPass "/apps" "http://backend.example.com/" timeout=60 ProxyPass "/examples" "http://backend.example.com/examples" timeout=10 ``` the second worker isn't actually created. Instead the first worker is used. The benefit is, that there is only one connection pool, so connections are more often reused. Note that all configuration attributes given explicitly for the later worker will be ignored. This will be logged as a warning. In the above example, the resulting timeout value for the URL `/examples` will be `60` instead of `10`! If you want to avoid worker sharing, sort your worker definitions by URL length, starting with the longest worker URLs. If you want to maximize worker sharing, use the reverse sort order. See also the related warning about ordering `[ProxyPass](#proxypass)` directives. Explicitly configured workers come in two flavors: direct workers and (load) balancer workers. They support many important configuration attributes which are described below in the `[ProxyPass](#proxypass)` directive. The same attributes can also be set using `[ProxySet](#proxyset)`. The set of options available for a direct worker depends on the protocol which is specified in the origin server URL. Available protocols include `ajp`, `fcgi`, `ftp`, `http` and `scgi`. Balancer workers are virtual workers that use direct workers known as their members to actually handle the requests. Each balancer can have multiple members. When it handles a request, it chooses a member based on the configured load balancing algorithm. A balancer worker is created if its worker URL uses `balancer` as the protocol scheme. The balancer URL uniquely identifies the balancer worker. Members are added to a balancer using `[BalancerMember](#balancermember)`. **DNS resolution for origin domains** DNS resolution happens when the socket to the origin domain is created for the first time. When connection reuse is enabled, each backend domain is resolved only once per child process, and cached for all further connections until the child is recycled. This information should to be considered while planning DNS maintenance tasks involving backend domains. Please also check `[ProxyPass](#proxypass)` parameters for more details about connection reuse. Controlling Access to Your Proxy -------------------------------- You can control who can access your proxy via the `[<Proxy>](#proxy)` control block as in the following example: ``` <Proxy "*"> Require ip 192.168.0 </Proxy> ``` For more information on access control directives, see `<mod_authz_host>`. Strictly limiting access is essential if you are using a forward proxy (using the `[ProxyRequests](#proxyrequests)` directive). Otherwise, your server can be used by any client to access arbitrary hosts while hiding his or her true identity. This is dangerous both for your network and for the Internet at large. When using a reverse proxy (using the `[ProxyPass](#proxypass)` directive with `ProxyRequests Off`), access control is less critical because clients can only contact the hosts that you have specifically configured. **See Also** the [Proxy-Chain-Auth](mod_proxy_http#env) environment variable. Slow Startup ------------ If you're using the `[ProxyBlock](#proxyblock)` directive, hostnames' IP addresses are looked up and cached during startup for later match test. This may take a few seconds (or more) depending on the speed with which the hostname lookups occur. Intranet Proxy -------------- An Apache httpd proxy server situated in an intranet needs to forward external requests through the company's firewall (for this, configure the `[ProxyRemote](#proxyremote)` directive to forward the respective scheme to the firewall proxy). However, when it has to access resources within the intranet, it can bypass the firewall when accessing hosts. The `[NoProxy](#noproxy)` directive is useful for specifying which hosts belong to the intranet and should be accessed directly. Users within an intranet tend to omit the local domain name from their WWW requests, thus requesting "http://somehost/" instead of `http://somehost.example.com/`. Some commercial proxy servers let them get away with this and simply serve the request, implying a configured local domain. When the `[ProxyDomain](#proxydomain)` directive is used and the server is [configured for proxy service](#proxyrequests), Apache httpd can return a redirect response and send the client to the correct, fully qualified, server address. This is the preferred method since the user's bookmark files will then contain fully qualified hosts. Protocol Adjustments -------------------- For circumstances where `<mod_proxy>` is sending requests to an origin server that doesn't properly implement keepalives or HTTP/1.1, there are two [environment variables](../env) that can force the request to use HTTP/1.0 with no keepalive. These are set via the `[SetEnv](mod_env#setenv)` directive. These are the `force-proxy-request-1.0` and `proxy-nokeepalive` notes. ``` <Location "/buggyappserver/"> ProxyPass "http://buggyappserver:7001/foo/" SetEnv force-proxy-request-1.0 1 SetEnv proxy-nokeepalive 1 </Location> ``` In 2.4.26 and later, the "no-proxy" environment variable can be set to disable `<mod_proxy>` processing the current request. This variable should be set with `[SetEnvIf](mod_setenvif#setenvif)`, as `[SetEnv](mod_env#setenv)` is not evaluated early enough. Request Bodies -------------- Some request methods such as POST include a request body. The HTTP protocol requires that requests which include a body either use chunked transfer encoding or send a `Content-Length` request header. When passing these requests on to the origin server, `<mod_proxy_http>` will always attempt to send the `Content-Length`. But if the body is large and the original request used chunked encoding, then chunked encoding may also be used in the upstream request. You can control this selection using [environment variables](../env). Setting `proxy-sendcl` ensures maximum compatibility with upstream servers by always sending the `Content-Length`, while setting `proxy-sendchunked` minimizes resource usage by using chunked encoding. Under some circumstances, the server must spool request bodies to disk to satisfy the requested handling of request bodies. For example, this spooling will occur if the original body was sent with chunked encoding (and is large), but the administrator has asked for backend requests to be sent with Content-Length or as HTTP/1.0. This spooling can also occur if the request body already has a Content-Length header, but the server is configured to filter incoming request bodies. `[LimitRequestBody](core#limitrequestbody)` only applies to request bodies that the server will spool to disk Reverse Proxy Request Headers ----------------------------- When acting in a reverse-proxy mode (using the `[ProxyPass](#proxypass)` directive, for example), `<mod_proxy_http>` adds several request headers in order to pass information to the origin server. These headers are: `X-Forwarded-For` The IP address of the client. `X-Forwarded-Host` The original host requested by the client in the `Host` HTTP request header. `X-Forwarded-Server` The hostname of the proxy server. Be careful when using these headers on the origin server, since they will contain more than one (comma-separated) value if the original request already contained one of these headers. For example, you can use `%{X-Forwarded-For}i` in the log format string of the origin server to log the original clients IP address, but you may get more than one address if the request passes through several proxies. See also the `[ProxyPreserveHost](#proxypreservehost)` and `[ProxyVia](#proxyvia)` directives, which control other request headers. Note: If you need to specify custom request headers to be added to the forwarded request, use the `[RequestHeader](mod_headers#requestheader)` directive. BalancerGrowth Directive ------------------------ | | | | --- | --- | | Description: | Number of additional Balancers that can be added Post-configuration | | Syntax: | ``` BalancerGrowth # ``` | | Default: | ``` BalancerGrowth 5 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | BalancerGrowth is only available in Apache HTTP Server 2.3.13 and later. | This directive allows for growth potential in the number of Balancers available for a virtualhost in addition to the number pre-configured. It only takes effect if there is at least one pre-configured Balancer. BalancerInherit Directive ------------------------- | | | | --- | --- | | Description: | Inherit ProxyPassed Balancers/Workers from the main server | | Syntax: | ``` BalancerInherit On|Off ``` | | Default: | ``` BalancerInherit On ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | BalancerInherit is only available in Apache HTTP Server 2.4.5 and later. | This directive will cause the current server/vhost to "inherit" ProxyPass Balancers and Workers defined in the main server. This can cause issues and inconsistent behavior if using the Balancer Manager and so should be disabled if using that feature. The setting in the global server defines the default for all vhosts. BalancerMember Directive ------------------------ | | | | --- | --- | | Description: | Add a member to a load balancing group | | Syntax: | ``` BalancerMember [balancerurl] url [key=value [key=value ...]] ``` | | Context: | directory | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | BalancerMember is only available in Apache HTTP Server 2.2 and later. | This directive adds a member to a load balancing group. It can be used within a `<Proxy balancer://...>` container directive and can take any of the key value pair parameters available to `[ProxyPass](#proxypass)` directives. One additional parameter is available only to `BalancerMember` directives: loadfactor. This is the member load factor - a decimal number between 1.0 (default) and 100.0, which defines the weighted load to be applied to the member in question. The balancerurl is only needed when not within a `<Proxy balancer://...>` container directive. It corresponds to the url of a balancer defined in `[ProxyPass](#proxypass)` directive. The path component of the balancer URL in any `<Proxy balancer://...>` container directive is ignored. Trailing slashes should typically be removed from the URL of a `BalancerMember`. BalancerPersist Directive ------------------------- | | | | --- | --- | | Description: | Attempt to persist changes made by the Balancer Manager across restarts. | | Syntax: | ``` BalancerPersist On|Off ``` | | Default: | ``` BalancerPersist Off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | BalancerPersist is only available in Apache HTTP Server 2.4.4 and later. | This directive will cause the shared memory storage associated with the balancers and balancer members to be persisted across restarts. This allows these local changes to not be lost during the normal restart/graceful state transitions. NoProxy Directive ----------------- | | | | --- | --- | | Description: | Hosts, domains, or networks that will be connected to directly | | Syntax: | ``` NoProxy host [host] ... ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | This directive is only useful for Apache httpd proxy servers within intranets. The `NoProxy` directive specifies a list of subnets, IP addresses, hosts and/or domains, separated by spaces. A request to a host which matches one or more of these is always served directly, without forwarding to the configured `[ProxyRemote](#proxyremote)` proxy server(s). ### Example ``` ProxyRemote "*" "http://firewall.example.com:81" NoProxy ".example.com" "192.168.112.0/21" ``` The host arguments to the `NoProxy` directive are one of the following type list: Domain A Domain is a partially qualified DNS domain name, preceded by a period. It represents a list of hosts which logically belong to the same DNS domain or zone (*i.e.*, the suffixes of the hostnames are all ending in Domain). ### Examples ``` .com .example.org. ``` To distinguish Domains from [Hostname](#hostname)s (both syntactically and semantically; a DNS domain can have a DNS A record, too!), Domains are always written with a leading period. **Note** Domain name comparisons are done without regard to the case, and Domains are always assumed to be anchored in the root of the DNS tree; therefore, the two domains `.ExAmple.com` and `.example.com.` (note the trailing period) are considered equal. Since a domain comparison does not involve a DNS lookup, it is much more efficient than subnet comparison. SubNet A SubNet is a partially qualified internet address in numeric (dotted quad) form, optionally followed by a slash and the netmask, specified as the number of significant bits in the SubNet. It is used to represent a subnet of hosts which can be reached over a common network interface. In the absence of the explicit net mask it is assumed that omitted (or zero valued) trailing digits specify the mask. (In this case, the netmask can only be multiples of 8 bits wide.) Examples: `192.168` or `192.168.0.0` the subnet 192.168.0.0 with an implied netmask of 16 valid bits (sometimes used in the netmask form `255.255.0.0`) `192.168.112.0/21` the subnet `192.168.112.0/21` with a netmask of 21 valid bits (also used in the form `255.255.248.0`) As a degenerate case, a *SubNet* with 32 valid bits is the equivalent to an [IPAddr](#ipaddr), while a SubNet with zero valid bits (*e.g.*, 0.0.0.0/0) is the same as the constant \_Default\_, matching any IP address. IPAddr A IPAddr represents a fully qualified internet address in numeric (dotted quad) form. Usually, this address represents a host, but there need not necessarily be a DNS domain name connected with the address. ### Example `192.168.123.7` **Note** An IPAddr does not need to be resolved by the DNS system, so it can result in more effective apache performance. Hostname A Hostname is a fully qualified DNS domain name which can be resolved to one or more [IPAddrs](#ipaddr) via the DNS domain name service. It represents a logical host (in contrast to [Domain](#domain)s, see above) and must be resolvable to at least one [IPAddr](#ipaddr) (or often to a list of hosts with different [IPAddr](#ipaddr)s). ### Examples ``` prep.ai.example.edu www.example.org ``` **Note** In many situations, it is more effective to specify an [IPAddr](#ipaddr) in place of a Hostname since a DNS lookup can be avoided. Name resolution in Apache httpd can take a remarkable deal of time when the connection to the name server uses a slow PPP link. Hostname comparisons are done without regard to the case, and Hostnames are always assumed to be anchored in the root of the DNS tree; therefore, the two hosts `WWW.ExAmple.com` and `www.example.com.` (note the trailing period) are considered equal. ### See also * [DNS Issues](../dns-caveats) <Proxy> Directive ----------------- | | | | --- | --- | | Description: | Container for directives applied to proxied resources | | Syntax: | ``` <Proxy wildcard-url> ...</Proxy> ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | Directives placed in `<Proxy>` sections apply only to matching proxied content. Shell-style wildcards are allowed. For example, the following will allow only hosts in `yournetwork.example.com` to access content via your proxy server: ``` <Proxy "*"> Require host yournetwork.example.com </Proxy> ``` The following example will process all files in the `foo` directory of `example.com` through the `INCLUDES` filter when they are sent through the proxy server: ``` <Proxy "http://example.com/foo/*"> SetOutputFilter INCLUDES </Proxy> ``` **Differences from the Location configuration section** A backend URL matches the configuration section if it begins with the the wildcard-url string, even if the last path segment in the directive only matches a prefix of the backend URL. For example, <Proxy "http://example.com/foo"> matches all of http://example.com/foo, http://example.com/foo/bar, and http://example.com/foobar. The matching of the final URL differs from the behavior of the `[<Location>](core#location)` section, which for purposes of this note treats the final path component as if it ended in a slash. For more control over the matching, see `<ProxyMatch>`. ### See also * `[<ProxyMatch>](#proxymatch)` Proxy100Continue Directive -------------------------- | | | | --- | --- | | Description: | Forward 100-continue expectation to the origin server | | Syntax: | ``` Proxy100Continue Off|On ``` | | Default: | ``` Proxy100Continue On ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | Available in version 2.4.40 and later | This directive determines whether the proxy should forward 100-continue *Expect:*ation to the origin server and thus let it decide when/if the HTTP request body should be read, or when `Off` the proxy should generate *100 Continue* intermediate response by itself before forwarding the request body. **Effectiveness** This option is of use only for HTTP proxying, as handled by `<mod_proxy_http>`. ProxyAddHeaders Directive ------------------------- | | | | --- | --- | | Description: | Add proxy information in X-Forwarded-\* headers | | Syntax: | ``` ProxyAddHeaders Off|On ``` | | Default: | ``` ProxyAddHeaders On ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | Available in version 2.3.10 and later | This directive determines whether or not proxy related information should be passed to the backend server through X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Server HTTP headers. **Effectiveness** This option is of use only for HTTP proxying, as handled by `<mod_proxy_http>`. ProxyBadHeader Directive ------------------------ | | | | --- | --- | | Description: | Determines how to handle bad header lines in a response | | Syntax: | ``` ProxyBadHeader IsError|Ignore|StartBody ``` | | Default: | ``` ProxyBadHeader IsError ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | The `ProxyBadHeader` directive determines the behavior of `<mod_proxy>` if it receives syntactically invalid response header lines (*i.e.* containing no colon) from the origin server. The following arguments are possible: `IsError` Abort the request and end up with a 502 (Bad Gateway) response. This is the default behavior. `Ignore` Treat bad header lines as if they weren't sent. `StartBody` When receiving the first bad header line, finish reading the headers and treat the remainder as body. This helps to work around buggy backend servers which forget to insert an empty line between the headers and the body. ProxyBlock Directive -------------------- | | | | --- | --- | | Description: | Words, hosts, or domains that are banned from being proxied | | Syntax: | ``` ProxyBlock *|word|host|domain [word|host|domain] ... ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | The `ProxyBlock` directive specifies a list of words, hosts and/or domains, separated by spaces. HTTP, HTTPS, and FTP document requests to sites whose names contain matched words, hosts or domains are *blocked* by the proxy server. The proxy module will also attempt to determine IP addresses of list items which may be hostnames during startup, and cache them for match test as well. That may slow down the startup time of the server. ### Example ``` ProxyBlock "news.example.com" "auctions.example.com" "friends.example.com" ``` Note that `example` would also be sufficient to match any of these sites. Hosts would also be matched if referenced by IP address. Note also that ``` ProxyBlock "*" ``` blocks connections to all sites. ProxyDomain Directive --------------------- | | | | --- | --- | | Description: | Default domain name for proxied requests | | Syntax: | ``` ProxyDomain Domain ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | This directive is only useful for Apache httpd proxy servers within intranets. The `ProxyDomain` directive specifies the default domain which the apache proxy server will belong to. If a request to a host without a domain name is encountered, a redirection response to the same host with the configured Domain appended will be generated. ### Example ``` ProxyRemote "*" "http://firewall.example.com:81" NoProxy ".example.com" "192.168.112.0/21" ProxyDomain ".example.com" ``` ProxyErrorOverride Directive ---------------------------- | | | | --- | --- | | Description: | Override error pages for proxied content | | Syntax: | ``` ProxyErrorOverride Off|On [code ...] ``` | | Default: | ``` ProxyErrorOverride Off ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | The list of status codes was added in 2.5.1 | This directive is useful for reverse-proxy setups where you want to have a common look and feel on the error pages seen by the end user. This also allows for included files (via `<mod_include>`'s SSI) to get the error code and act accordingly. (Default behavior would display the error page of the proxied server. Turning this on shows the SSI Error message.) This directive does not affect the processing of informational (1xx), normal success (2xx), or redirect (3xx) responses. By default `ProxyErrorOverride` affects all responses with codes between 400 (including) and 600 (excluding). ### Example for default behavior ``` ProxyErrorOverride On ``` To change the default behavior, you can specify the status codes to consider, separated by spaces. If you do so, all other status codes will be ignored. You can only specify status codes, that are considered error codes: between 400 (including) and 600 (excluding). ### Example for custom status codes ``` ProxyErrorOverride On 403 405 500 501 502 503 504 ``` ProxyIOBufferSize Directive --------------------------- | | | | --- | --- | | Description: | Determine size of internal data throughput buffer | | Syntax: | ``` ProxyIOBufferSize bytes ``` | | Default: | ``` ProxyIOBufferSize 8192 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | The `ProxyIOBufferSize` directive adjusts the size of the internal buffer which is used as a scratchpad for the data between input and output. The size must be at least `512`. In almost every case, there's no reason to change that value. If used with AJP, this directive sets the maximum AJP packet size in bytes. Values larger than 65536 are set to 65536. If you change it from the default, you must also change the `packetSize` attribute of your AJP connector on the Tomcat side! The attribute `packetSize` is only available in Tomcat `5.5.20+` and `6.0.2+` Normally it is not necessary to change the maximum packet size. Problems with the default value have been reported when sending certificates or certificate chains. <ProxyMatch> Directive ---------------------- | | | | --- | --- | | Description: | Container for directives applied to regular-expression-matched proxied resources | | Syntax: | ``` <ProxyMatch regex> ...</ProxyMatch> ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | The `<ProxyMatch>` directive is identical to the `[<Proxy>](#proxy)` directive, except that it matches URLs using [regular expressions](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary"). From 2.4.8 onwards, named groups and backreferences are captured and written to the environment with the corresponding name prefixed with "MATCH\_" and in upper case. This allows elements of URLs to be referenced from within [expressions](../expr) and modules like `<mod_rewrite>`. In order to prevent confusion, numbered (unnamed) backreferences are ignored. Use named groups instead. ``` <ProxyMatch "^http://(?<sitename>[^/]+)"> Require ldap-group cn=%{env:MATCH_SITENAME},ou=combined,o=Example </ProxyMatch> ``` ### See also * `[<Proxy>](#proxy)` ProxyMaxForwards Directive -------------------------- | | | | --- | --- | | Description: | Maximum number of proxies that a request can be forwarded through | | Syntax: | ``` ProxyMaxForwards number ``` | | Default: | ``` ProxyMaxForwards -1 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | Default behaviour changed in 2.2.7 | The `ProxyMaxForwards` directive specifies the maximum number of proxies through which a request may pass if there's no `Max-Forwards` header supplied with the request. This may be set to prevent infinite proxy loops or a DoS attack. ### Example ``` ProxyMaxForwards 15 ``` Note that setting `ProxyMaxForwards` is a violation of the HTTP/1.1 protocol (RFC2616), which forbids a Proxy setting `Max-Forwards` if the Client didn't set it. Earlier Apache httpd versions would always set it. A negative `ProxyMaxForwards` value, including the default -1, gives you protocol-compliant behavior but may leave you open to loops. ProxyPass Directive ------------------- | | | | --- | --- | | Description: | Maps remote servers into the local server URL-space | | Syntax: | ``` ProxyPass [path] !|url [key=value [key=value ...]] [nocanon] [interpolate] [noquery] ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | Unix Domain Socket (UDS) support added in 2.4.7 | This directive allows remote servers to be mapped into the space of the local server. The local server does not act as a proxy in the conventional sense but appears to be a mirror of the remote server. The local server is often called a reverse proxy or gateway. The path is the name of a local virtual path; url is a partial URL for the remote server and cannot include a query string. It is strongly suggested to review the concept of a [Worker](#workers) before proceeding any further with this section. This directive is not supported within `[<Directory>](core#directory)`, `[<If>](core#if)` and `[<Files>](core#files)` containers. The `[ProxyRequests](#proxyrequests)` directive should usually be set **off** when using `ProxyPass`. In 2.4.7 and later, support for using a Unix Domain Socket is available by using a target which prepends `unix:/path/lis.sock|`. For example, to proxy HTTP and target the UDS at /home/www.socket, you would use `unix:/home/www.socket|http://localhost/whatever/`. **Note:** The path associated with the `unix:` URL is `DefaultRuntimeDir` aware. When used inside a `[<Location>](core#location)` section, the first argument is omitted and the local directory is obtained from the `[<Location>](core#location)`. The same will occur inside a `[<LocationMatch>](core#locationmatch)` section; however, ProxyPass does not interpret the regexp as such, so it is necessary to use `ProxyPassMatch` in this situation instead. Suppose the local server has address `http://example.com/`; then ``` <Location "/mirror/foo/"> ProxyPass "http://backend.example.com/" </Location> ``` will cause a local request for `http://example.com/mirror/foo/bar` to be internally converted into a proxy request to `http://backend.example.com/bar`. If you require a more flexible reverse-proxy configuration, see the `[RewriteRule](mod_rewrite#rewriterule)` directive with the `[P]` flag. The following alternative syntax is possible; however, it can carry a performance penalty when present in very large numbers. The advantage of the below syntax is that it allows for dynamic control via the [Balancer Manager](mod_proxy_balancer#balancer_manager) interface: ``` ProxyPass "/mirror/foo/" "http://backend.example.com/" ``` If the first argument ends with a trailing **/**, the second argument should also end with a trailing **/**, and vice versa. Otherwise, the resulting requests to the backend may miss some needed slashes and do not deliver the expected results. The `!` directive is useful in situations where you don't want to reverse-proxy a subdirectory, *e.g.* ``` <Location "/mirror/foo/"> ProxyPass "http://backend.example.com/" </Location> <Location "/mirror/foo/i"> ProxyPass "!" </Location> ``` ``` ProxyPass "/mirror/foo/i" "!" ProxyPass "/mirror/foo" "http://backend.example.com" ``` will proxy all requests to `/mirror/foo` to `backend.example.com` *except* requests made to `/mirror/foo/i`. Mixing ProxyPass settings in different contexts does not work: ``` ProxyPass "/mirror/foo/i" "!" <Location "/mirror/foo/"> ProxyPass "http://backend.example.com/" </Location> ``` In this case, a request to `/mirror/foo/i` will get proxied, because the `ProxyPass` directive in the Location block will be evaluated first. The fact that `ProxyPass` supports both server and directory contexts does not mean that their scope and position in the configuration file will guarantee any ordering or override. **Ordering ProxyPass Directives** The configured `[ProxyPass](#proxypass)` and `[ProxyPassMatch](#proxypassmatch)` rules are checked in the order of configuration. The first rule that matches wins. So usually you should sort conflicting `[ProxyPass](#proxypass)` rules starting with the longest URLs first. Otherwise, later rules for longer URLS will be hidden by any earlier rule which uses a leading substring of the URL. Note that there is some relation with worker sharing. **Ordering ProxyPass Directives in Locations** Only one `[ProxyPass](#proxypass)` directive can be placed in a `[Location](core#location)` block, and the most specific location will take precedence. **Exclusions and the no-proxy environment variable** Exclusions must come *before* the general `ProxyPass` directives. In 2.4.26 and later, the "no-proxy" environment variable is an alternative to exclusions, and is the only way to configure an exclusion of a `ProxyPass` directive in `[Location](core#location)` context. This variable should be set with `[SetEnvIf](mod_setenvif#setenvif)`, as `[SetEnv](mod_env#setenv)` is not evaluated early enough. **ProxyPass `key=value` Parameters** In Apache HTTP Server 2.1 and later, mod\_proxy supports pooled connections to a backend server. Connections created on demand can be retained in a pool for future use. Limits on the pool size and other settings can be coded on the `ProxyPass` directive using `key=value` parameters, described in the tables below. **Maximum connections to the backend** By default, mod\_proxy will allow and retain the maximum number of connections that could be used simultaneously by that web server child process. Use the `max` parameter to reduce the number from the default. The pool of connections is maintained per web server child process, and `max` and other settings are not coordinated among all child processes, except when only one child process is allowed by configuration or MPM design. Use the `ttl` parameter to set an optional time to live; connections which have been unused for at least `ttl` seconds will be closed. `ttl` can be used to avoid using a connection which is subject to closing because of the backend server's keep-alive timeout. ### Example ``` ProxyPass "/example" "http://backend.example.com" max=20 ttl=120 retry=300 ``` | Worker|BalancerMember parameters | | --- | | Parameter | Default | Description | | --- | --- | --- | | min | 0 | Minimum number of connection pool entries, unrelated to the actual number of connections. This only needs to be modified from the default for special circumstances where heap memory associated with the backend connections should be preallocated or retained. | | max | 1...n | Maximum number of connections that will be allowed to the backend server. The default for this limit is the number of threads per process in the active MPM. In the Prefork MPM, this is always 1, while with other MPMs, it is controlled by the `ThreadsPerChild` directive. | | smax | max | Retained connection pool entries above this limit are freed during certain operations if they have been unused for longer than the time to live, controlled by the `ttl` parameter. If the connection pool entry has an associated connection, it will be closed. This only needs to be modified from the default for special circumstances where connection pool entries and any associated connections which have exceeded the time to live need to be freed or closed more aggressively. | | acquire | - | If set, this will be the maximum time to wait for a free connection in the connection pool, in milliseconds. If there are no free connections in the pool, the Apache httpd will return `SERVER_BUSY` status to the client. | | connectiontimeout | timeout | Connect timeout in seconds. The number of seconds Apache httpd waits for the creation of a connection to the backend to complete. By adding a postfix of ms, the timeout can be also set in milliseconds. | | disablereuse | Off | This parameter should be used when you want to force mod\_proxy to immediately close a connection to the backend after being used, and thus, disable its persistent connection and pool for that backend. This helps in various situations where a firewall between Apache httpd and the backend server (regardless of protocol) tends to silently drop connections or when backends themselves may be under round- robin DNS. When connection reuse is enabled each backend domain is resolved (with a DNS query) only once per child process and cached for all further connections until the child is recycled. To disable connection reuse, set this property value to `On`. | | enablereuse | On | This is the inverse of 'disablereuse' above, provided as a convenience for scheme handlers that require opt-in for connection reuse (such as `<mod_proxy_fcgi>`). 2.4.11 and later only. | | flushpackets | off | Determines whether the proxy module will auto-flush the output brigade after each "chunk" of data. 'off' means that it will flush only when needed; 'on' means after each chunk is sent; and 'auto' means poll/wait for a period of time and flush if no input has been received for 'flushwait' milliseconds. Currently, this is in effect only for mod\_proxy\_ajp and mod\_proxy\_fcgi. | | flushwait | 10 | The time to wait for additional input, in milliseconds, before flushing the output brigade if 'flushpackets' is 'auto'. | | iobuffersize | 8192 | Adjusts the size of the internal scratchpad IO buffer. This allows you to override the `ProxyIOBufferSize` for a specific worker. This must be at least 512 or set to 0 for the system default of 8192. | | responsefieldsize | 8192 | Adjust the size of the proxy response field buffer. The buffer size should be at least the size of the largest expected header size from a proxied response. Setting the value to 0 will use the system default of 8192 bytes. Available in Apache HTTP Server 2.4.34 and later. | | keepalive | Off | This parameter should be used when you have a firewall between your Apache httpd and the backend server, which tends to drop inactive connections. This flag will tell the Operating System to send `KEEP_ALIVE` messages on inactive connections and thus prevent the firewall from dropping the connection. To enable keepalive, set this property value to `On`. The frequency of initial and subsequent TCP keepalive probes depends on global OS settings, and may be as high as 2 hours. To be useful, the frequency configured in the OS must be smaller than the threshold used by the firewall. | | lbset | 0 | Sets the load balancer cluster set that the worker is a member of. The load balancer will try all members of a lower numbered lbset before trying higher numbered ones. | | ping | 0 | Ping property tells the webserver to "test" the connection to the backend before forwarding the request. For AJP, it causes `<mod_proxy_ajp>` to send a `CPING` request on the ajp13 connection (implemented on Tomcat 3.3.2+, 4.1.28+ and 5.0.13+). For HTTP, it causes `<mod_proxy_http>` to send a `100-Continue` to the backend (only valid for HTTP/1.1 - for non HTTP/1.1 backends, this property has no effect). In both cases, the parameter is the delay in seconds to wait for the reply. This feature has been added to avoid problems with hung and busy backends. This will increase the network traffic during the normal operation which could be an issue, but it will lower the traffic in case some of the cluster nodes are down or busy. By adding a postfix of ms, the delay can be also set in milliseconds. | | receivebuffersize | 0 | Adjusts the size of the explicit (TCP/IP) network buffer size for proxied connections. This allows you to override the `ProxyReceiveBufferSize` for a specific worker. This must be at least 512 or set to 0 for the system default. | | redirect | - | Redirection Route of the worker. This value is usually set dynamically to enable safe removal of the node from the cluster. If set, all requests without session id will be redirected to the BalancerMember that has route parameter equal to this value. | | retry | 60 | Connection pool worker retry timeout in seconds. If the connection pool worker to the backend server is in the error state, Apache httpd will not forward any requests to that server until the timeout expires. This enables to shut down the backend server for maintenance and bring it back online later. A value of 0 means always retry workers in an error state with no timeout. | | route | - | Route of the worker when used inside load balancer. The route is a value appended to session id. | | status | - | Single letter value defining the initial status of this worker. | | | --- | | D: Worker is disabled and will not accept any requests. | | S: Worker is administratively stopped. | | I: Worker is in ignore-errors mode and will always be considered available. | | R: Worker is a hot spare. For each worker in a given lbset that is unusable (draining, stopped, in error, etc.), a usable hot spare with the same lbset will be used in its place. Hot spares can help ensure that a specific number of workers are always available for use by a balancer. | | H: Worker is in hot-standby mode and will only be used if no other viable workers or spares are available in the balancer set. | | E: Worker is in an error state. | | N: Worker is in drain mode and will only accept existing sticky sessions destined for itself and ignore all other requests. | Status can be set (which is the default) by prepending with '+' or cleared by prepending with '-'. Thus, a setting of 'S-E' sets this worker to Stopped and clears the in-error flag. | | timeout | `ProxyTimeout` | Connection timeout in seconds. The number of seconds Apache httpd waits for data sent by / to the backend. | | ttl | - | Time to live for inactive connections and associated connection pool entries, in seconds. Once reaching this limit, a connection will not be used again; it will be closed at some later time. | | flusher | flush | Name of the provider used by `<mod_proxy_fdpass>`. See the documentation of this module for more details. | | secret | - | Value of secret used by `<mod_proxy_ajp>`. It must be identical to the secret configured on the server side of the AJP connection. Available in Apache HTTP Server 2.4.42 and later. | | upgrade | WebSocket | Protocol accepted in the Upgrade header by `<mod_proxy_wstunnel>`. See the documentation of this module for more details. | | mapping | - | Type of mapping between the path and the url. This determines the normalization and/or (non-)decoding that `<mod_proxy>` will apply to the requested uri-path before matching the path. If a mapping matches, it's committed to the uri-path such that all the directory contexts that use a path (like `<Location>`) will be matched using the same mapping. `mapping=encoded` prevents the %-decoding of the uri-path so that one can use for instance configurations like: ``` ProxyPass "/special%3Fsegment" "https://example.com/special%3Fsegment" mapping=encoded ``` ``` <Location "/special%3Fsegment"> Require ip 172.17.2.0/24 </Location> ``` `mapping=servlet` refers to the normalization defined by the Servlet specification, which is for instance applied by Apache Tomcat for servlet containers (notably the path parameters are ignored for the mapping). An uri-path like `/some;foo/path` is then mapped as `/some/path` hence matches any of the below regardless of the requested path parameters: ``` ProxyPass "/some/path" "https://servlet.example.com/some/path" mapping=servlet ``` ``` <Location "/some/path"> Require valid-user </Location> ``` **Note** It is recommended to use the same mapping on the Apache httpd side than the one used on the backend side. For instance when configuring authorizations in `<Location>` blocks for paths that are mapped by `<mod_proxy>` to some servlet containers (like applications running on Apache Tomcat), one should use the `mapping=servlet` setting to prevent path parameters and alike from interfering with the authorizations that are to be enforced in by the Apache httpd. | If the Proxy directive scheme starts with the `balancer://` (eg: `balancer://cluster`, any path information is ignored), then a virtual worker that does not really communicate with the backend server will be created. Instead, it is responsible for the management of several "real" workers. In that case, the special set of parameters can be added to this virtual worker. See `<mod_proxy_balancer>` for more information about how the balancer works. | Balancer parameters | | --- | | Parameter | Default | Description | | --- | --- | --- | | lbmethod | byrequests | Balancer load-balance method. Select the load-balancing scheduler method to use. Either `byrequests`, to perform weighted request counting; `bytraffic`, to perform weighted traffic byte count balancing; or `bybusyness`, to perform pending request balancing. The default is `byrequests`. | | maxattempts | One less than the number of workers, or 1 with a single worker. | Maximum number of failover attempts before giving up. | | nofailover | Off | If set to `On`, the session will break if the worker is in error state or disabled. Set this value to `On` if backend servers do not support session replication. | | stickysession | - | Balancer sticky session name. The value is usually set to something like `JSESSIONID` or `PHPSESSIONID`, and it depends on the backend application server that support sessions. If the backend application server uses different name for cookies and url encoded id (like servlet containers) use | to separate them. The first part is for the cookie the second for the path. Available in Apache HTTP Server 2.4.4 and later. | | stickysessionsep | "." | Sets the separation symbol in the session cookie. Some backend application servers do not use the '.' as the symbol. For example, the Oracle Weblogic server uses '!'. The correct symbol can be set using this option. The setting of 'Off' signifies that no symbol is used. | | scolonpathdelim | Off | If set to `On`, the semi-colon character ';' will be used as an additional sticky session path delimiter/separator. This is mainly used to emulate mod\_jk's behavior when dealing with paths such as `JSESSIONID=6736bcf34;foo=aabfa` | | timeout | 0 | Balancer timeout in seconds. If set, this will be the maximum time to wait for a free worker. The default is to not wait. | | failonstatus | - | A single or comma-separated list of HTTP status codes. If set, this will force the worker into error state when the backend returns any status code in the list. Worker recovery behaves the same as other worker errors. | | failontimeout | Off | If set, an IO read timeout after a request is sent to the backend will force the worker into error state. Worker recovery behaves the same as other worker errors. Available in Apache HTTP Server 2.4.5 and later. | | nonce | <auto> | The protective nonce used in the `balancer-manager` application page. The default is to use an automatically determined UUID-based nonce, to provide for further protection for the page. If set, then the nonce is set to that value. A setting of `None` disables all nonce checking. **Note** In addition to the nonce, the `balancer-manager` page should be protected via an ACL. | | growth | 0 | Number of additional BalancerMembers to allow to be added to this balancer in addition to those defined at configuration. | | forcerecovery | On | Force the immediate recovery of all workers without considering the retry parameter of the workers if all workers of a balancer are in error state. There might be cases where an already overloaded backend can get into deeper trouble if the recovery of all workers is enforced without considering the retry parameter of each worker. In this case, set to `Off`. Available in Apache HTTP Server 2.4.2 and later. | A sample balancer setup: ``` ProxyPass "/special-area" "http://special.example.com" smax=5 max=10 ProxyPass "/" "balancer://mycluster/" stickysession=JSESSIONID|jsessionid nofailover=On <Proxy "balancer://mycluster"> BalancerMember "ajp://1.2.3.4:8009" BalancerMember "ajp://1.2.3.5:8009" loadfactor=20 # Less powerful server, don't send as many requests there, BalancerMember "ajp://1.2.3.6:8009" loadfactor=5 </Proxy> ``` Configuring hot spares can help ensure that a certain number of workers are always available for use per load balancer set: ``` ProxyPass "/" "balancer://sparecluster/" <Proxy balancer://sparecluster> BalancerMember ajp://1.2.3.4:8009 BalancerMember ajp://1.2.3.5:8009 # The servers below are hot spares. For each server above that is unusable # (draining, stopped, unreachable, in error state, etc.), one of these spares # will be used in its place. Two servers will always be available for a request # unless one or more of the spares is also unusable. BalancerMember ajp://1.2.3.6:8009 status=+R BalancerMember ajp://1.2.3.7:8009 status=+R </Proxy> ``` Setting up a hot-standby that will only be used if no other members (or spares) are available in the load balancer set: ``` ProxyPass "/" "balancer://hotcluster/" <Proxy "balancer://hotcluster"> BalancerMember "ajp://1.2.3.4:8009" loadfactor=1 BalancerMember "ajp://1.2.3.5:8009" loadfactor=2.25 # The server below is on hot standby BalancerMember "ajp://1.2.3.6:8009" status=+H ProxySet lbmethod=bytraffic </Proxy> ``` **Additional ProxyPass Keywords** Normally, mod\_proxy will canonicalise ProxyPassed URLs. But this may be incompatible with some backends, particularly those that make use of PATH\_INFO. The optional nocanon keyword suppresses this and passes the URL path "raw" to the backend. Note that this keyword may affect the security of your backend, as it removes the normal limited protection against URL-based attacks provided by the proxy. Normally, mod\_proxy will include the query string when generating the SCRIPT\_FILENAME environment variable. The optional noquery keyword (available in httpd 2.4.1 and later) prevents this. The optional interpolate keyword, in combination with `[ProxyPassInterpolateEnv](#proxypassinterpolateenv)`, causes the ProxyPass to interpolate environment variables, using the syntax ${VARNAME}. Note that many of the standard CGI-derived environment variables will not exist when this interpolation happens, so you may still have to resort to `<mod_rewrite>` for complex rules. Also note that interpolation is supported within the scheme/hostname/port portion of a URL only for variables that are available when the directive is parsed (like `[Define](core#define)`). Dynamic determination of those fields can be accomplished with `<mod_rewrite>`. The following example describes how to use `<mod_rewrite>` to dynamically set the scheme to http or https: ``` RewriteEngine On RewriteCond "%{HTTPS}" =off RewriteRule "." "-" [E=protocol:http] RewriteCond "%{HTTPS}" =on RewriteRule "." "-" [E=protocol:https] RewriteRule "^/mirror/foo/(.*)" "%{ENV:protocol}://backend.example.com/$1" [P] ProxyPassReverse "/mirror/foo/" "http://backend.example.com/" ProxyPassReverse "/mirror/foo/" "https://backend.example.com/" ``` ProxyPassInherit Directive -------------------------- | | | | --- | --- | | Description: | Inherit ProxyPass directives defined from the main server | | Syntax: | ``` ProxyPassInherit On|Off ``` | | Default: | ``` ProxyPassInherit On ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | ProxyPassInherit is only available in Apache HTTP Server 2.4.5 and later. | This directive will cause the current server/vhost to "inherit" `[ProxyPass](#proxypass)` directives defined in the main server. This can cause issues and inconsistent behavior if using the Balancer Manager for dynamic changes and so should be disabled if using that feature. The setting in the global server defines the default for all vhosts. Disabling ProxyPassInherit also disables `[BalancerInherit](#balancerinherit)`. ProxyPassInterpolateEnv Directive --------------------------------- | | | | --- | --- | | Description: | Enable Environment Variable interpolation in Reverse Proxy configurations | | Syntax: | ``` ProxyPassInterpolateEnv On|Off ``` | | Default: | ``` ProxyPassInterpolateEnv Off ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | Available in httpd 2.2.9 and later | This directive, together with the interpolate argument to `ProxyPass`, `ProxyPassReverse`, `ProxyPassReverseCookieDomain`, and `ProxyPassReverseCookiePath`, enables reverse proxies to be dynamically configured using environment variables which may be set by another module such as `<mod_rewrite>`. It affects the `ProxyPass`, `ProxyPassReverse`, `ProxyPassReverseCookieDomain`, and `ProxyPassReverseCookiePath` directives and causes them to substitute the value of an environment variable `varname` for the string `${varname}` in configuration directives if the interpolate option is set. The scheme/hostname/port portion of `ProxyPass` may contain variables, but only the ones available when the directive is parsed (for example, using `[Define](core#define)`). For all the other use cases, please consider using `<mod_rewrite>` instead. **Performance warning** Keep this turned off unless you need it! Adding variables to `ProxyPass` for example may lead to the use of the default mod\_proxy's workers configured (that don't allow any fine tuning like connections reuse, etc..). ProxyPassMatch Directive ------------------------ | | | | --- | --- | | Description: | Maps remote servers into the local server URL-space using regular expressions | | Syntax: | ``` ProxyPassMatch [regex] !|url [key=value [key=value ...]] ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy | This directive is equivalent to `[ProxyPass](#proxypass)` but makes use of regular expressions instead of simple prefix matching. The supplied regular expression is matched against the url, and if it matches, the server will substitute any parenthesized matches into the given string and use it as a new url. **Note:** This directive cannot be used within a `<Directory>` context. Suppose the local server has address `http://example.com/`; then ``` ProxyPassMatch "^/(.*\.gif)$" "http://backend.example.com/$1" ``` will cause a local request for `http://example.com/foo/bar.gif` to be internally converted into a proxy request to `http://backend.example.com/foo/bar.gif`. **Note** The URL argument must be parsable as a URL *before* regexp substitutions (as well as after). This limits the matches you can use. For instance, if we had used ``` ProxyPassMatch "^(/.*\.gif)$" "http://backend.example.com:8000$1" ``` in our previous example, it would fail with a syntax error at server startup. This is a bug (PR 46665 in the ASF bugzilla), and the workaround is to reformulate the match: ``` ProxyPassMatch "^/(.*\.gif)$" "http://backend.example.com:8000/$1" ``` The `!` directive is useful in situations where you don't want to reverse-proxy a subdirectory. When used inside a `[<LocationMatch>](core#locationmatch)` section, the first argument is omitted and the regexp is obtained from the `[<LocationMatch>](core#locationmatch)`. If you require a more flexible reverse-proxy configuration, see the `[RewriteRule](mod_rewrite#rewriterule)` directive with the `[P]` flag. **Default Substitution** When the URL parameter doesn't use any backreferences into the regular expression, the original URL will be appended to the URL parameter. **Security Warning** Take care when constructing the target URL of the rule, considering the security impact from allowing the client influence over the set of URLs to which your server will act as a proxy. Ensure that the scheme and hostname part of the URL is either fixed or does not allow the client undue influence. ProxyPassReverse Directive -------------------------- | | | | --- | --- | | Description: | Adjusts the URL in HTTP response headers sent from a reverse proxied server | | Syntax: | ``` ProxyPassReverse [path] url [interpolate] ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy | This directive lets Apache httpd adjust the URL in the `Location`, `Content-Location` and `URI` headers on HTTP redirect responses. This is essential when Apache httpd is used as a reverse proxy (or gateway) to avoid bypassing the reverse proxy because of HTTP redirects on the backend servers which stay behind the reverse proxy. Only the HTTP response headers specifically mentioned above will be rewritten. Apache httpd will not rewrite other response headers, nor will it by default rewrite URL references inside HTML pages. This means that if the proxied content contains absolute URL references, they will bypass the proxy. To rewrite HTML content to match the proxy, you must load and enable `<mod_proxy_html>`. path is the name of a local virtual path; url is a partial URL for the remote server. These parameters are used the same way as for the `[ProxyPass](#proxypass)` directive. For example, suppose the local server has address `http://example.com/`; then ``` ProxyPass "/mirror/foo/" "http://backend.example.com/" ProxyPassReverse "/mirror/foo/" "http://backend.example.com/" ProxyPassReverseCookieDomain "backend.example.com" "public.example.com" ProxyPassReverseCookiePath "/" "/mirror/foo/" ``` will not only cause a local request for the `http://example.com/mirror/foo/bar` to be internally converted into a proxy request to `http://backend.example.com/bar` (the functionality which `ProxyPass` provides here). It also takes care of redirects which the server `backend.example.com` sends when redirecting `http://backend.example.com/bar` to `http://backend.example.com/quux` . Apache httpd adjusts this to `http://example.com/mirror/foo/quux` before forwarding the HTTP redirect response to the client. Note that the hostname used for constructing the URL is chosen in respect to the setting of the `[UseCanonicalName](core#usecanonicalname)` directive. Note that this `ProxyPassReverse` directive can also be used in conjunction with the proxy feature (`RewriteRule ... [P]`) from `<mod_rewrite>` because it doesn't depend on a corresponding `[ProxyPass](#proxypass)` directive. The optional interpolate keyword, used together with `ProxyPassInterpolateEnv`, enables interpolation of environment variables specified using the format ${VARNAME}. Note that interpolation is not supported within the scheme portion of a URL. When used inside a `[<Location>](core#location)` section, the first argument is omitted and the local directory is obtained from the `[<Location>](core#location)`. The same occurs inside a `[<LocationMatch>](core#locationmatch)` section, but will probably not work as intended, as ProxyPassReverse will interpret the regexp literally as a path; if needed in this situation, specify the ProxyPassReverse outside the section or in a separate `[<Location>](core#location)` section. This directive is not supported in `[<Directory>](core#directory)` or `[<Files>](core#files)` sections. ProxyPassReverseCookieDomain Directive -------------------------------------- | | | | --- | --- | | Description: | Adjusts the Domain string in Set-Cookie headers from a reverse- proxied server | | Syntax: | ``` ProxyPassReverseCookieDomain internal-domain public-domain [interpolate] ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy | Usage is basically similar to `[ProxyPassReverse](#proxypassreverse)`, but instead of rewriting headers that are a URL, this rewrites the `domain` string in `Set-Cookie` headers. ProxyPassReverseCookiePath Directive ------------------------------------ | | | | --- | --- | | Description: | Adjusts the Path string in Set-Cookie headers from a reverse- proxied server | | Syntax: | ``` ProxyPassReverseCookiePath internal-path public-path [interpolate] ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy | Useful in conjunction with `[ProxyPassReverse](#proxypassreverse)` in situations where backend URL paths are mapped to public paths on the reverse proxy. This directive rewrites the `path` string in `Set-Cookie` headers. If the beginning of the cookie path matches internal-path, the cookie path will be replaced with public-path. In the example given with `[ProxyPassReverse](#proxypassreverse)`, the directive: ``` ProxyPassReverseCookiePath "/" "/mirror/foo/" ``` will rewrite a cookie with backend path `/` (or `/example` or, in fact, anything) to `/mirror/foo/`. ProxyPreserveHost Directive --------------------------- | | | | --- | --- | | Description: | Use incoming Host HTTP request header for proxy request | | Syntax: | ``` ProxyPreserveHost On|Off ``` | | Default: | ``` ProxyPreserveHost Off ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | Usable in directory context in 2.3.3 and later. | When enabled, this option will pass the Host: line from the incoming request to the proxied host, instead of the hostname specified in the `[ProxyPass](#proxypass)` line. This option should normally be turned `Off`. It is mostly useful in special configurations like proxied mass name-based virtual hosting, where the original Host header needs to be evaluated by the backend server. ProxyReceiveBufferSize Directive -------------------------------- | | | | --- | --- | | Description: | Network buffer size for proxied HTTP and FTP connections | | Syntax: | ``` ProxyReceiveBufferSize bytes ``` | | Default: | ``` ProxyReceiveBufferSize 0 ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | The `ProxyReceiveBufferSize` directive specifies an explicit (TCP/IP) network buffer size for proxied HTTP and FTP connections, for increased throughput. It has to be greater than `512` or set to `0` to indicate that the system's default buffer size should be used. ### Example ``` ProxyReceiveBufferSize 2048 ``` ProxyRemote Directive --------------------- | | | | --- | --- | | Description: | Remote proxy used to handle certain requests | | Syntax: | ``` ProxyRemote match remote-server ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | This defines remote proxies to this proxy. match is either the name of a URL-scheme that the remote server supports, or a partial URL for which the remote server should be used, or `*` to indicate the server should be contacted for all requests. remote-server is a partial URL for the remote server. Syntax: ``` remote-server = scheme://hostname[:port] ``` scheme is effectively the protocol that should be used to communicate with the remote server; only `http` and `https` are supported by this module. When using `https`, the requests are forwarded through the remote proxy using the HTTP CONNECT method. ### Example ``` ProxyRemote "http://goodguys.example.com/" "http://mirrorguys.example.com:8000" ProxyRemote "*" "http://cleverproxy.localdomain" ProxyRemote "ftp" "http://ftpproxy.mydomain:8080" ``` In the last example, the proxy will forward FTP requests, encapsulated as yet another HTTP proxy request, to another proxy which can handle them. This option also supports reverse proxy configuration; a backend webserver can be embedded within a virtualhost URL space even if that server is hidden by another forward proxy. ProxyRemoteMatch Directive -------------------------- | | | | --- | --- | | Description: | Remote proxy used to handle requests matched by regular expressions | | Syntax: | ``` ProxyRemoteMatch regex remote-server ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | The `ProxyRemoteMatch` is identical to the `[ProxyRemote](#proxyremote)` directive, except that the first argument is a [regular expression](https://httpd.apache.org/docs/2.4/en/glossary.html#regex "see glossary") match against the requested URL. ProxyRequests Directive ----------------------- | | | | --- | --- | | Description: | Enables forward (standard) proxy requests | | Syntax: | ``` ProxyRequests On|Off ``` | | Default: | ``` ProxyRequests Off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | This allows or prevents Apache httpd from functioning as a forward proxy server. (Setting ProxyRequests to `Off` does not disable use of the `[ProxyPass](#proxypass)` directive.) In a typical reverse proxy or gateway configuration, this option should be set to `Off`. In order to get the functionality of proxying HTTP or FTP sites, you need also `<mod_proxy_http>` or `<mod_proxy_ftp>` (or both) present in the server. In order to get the functionality of (forward) proxying HTTPS sites, you need `<mod_proxy_connect>` enabled in the server. **Warning** Do not enable proxying with `[ProxyRequests](#proxyrequests)` until you have [secured your server](#access). Open proxy servers are dangerous both to your network and to the Internet at large. ### See also * [Forward and Reverse Proxies/Gateways](#forwardreverse) ProxySet Directive ------------------ | | | | --- | --- | | Description: | Set various Proxy balancer or member parameters | | Syntax: | ``` ProxySet url key=value [key=value ...] ``` | | Context: | server config, virtual host, directory | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | ProxySet is only available in Apache HTTP Server 2.2 and later. | This directive is used as an alternate method of setting any of the parameters available to Proxy balancers and workers normally done via the `[ProxyPass](#proxypass)` directive. If used within a `<Proxy balancer url|worker url>` container directive, the url argument is not required. As a side effect the respective balancer or worker gets created. This can be useful when doing reverse proxying via a `[RewriteRule](mod_rewrite#rewriterule)` instead of a `[ProxyPass](#proxypass)` directive. ``` <Proxy "balancer://hotcluster"> BalancerMember "http://www2.example.com:8080" loadfactor=1 BalancerMember "http://www3.example.com:8080" loadfactor=2 ProxySet lbmethod=bytraffic </Proxy> ``` ``` <Proxy "http://backend"> ProxySet keepalive=On </Proxy> ``` ``` ProxySet "balancer://foo" lbmethod=bytraffic timeout=15 ``` ``` ProxySet "ajp://backend:7001" timeout=15 ``` **Warning** Keep in mind that the same parameter key can have a different meaning depending whether it is applied to a balancer or a worker, as shown by the two examples above regarding timeout. ProxySourceAddress Directive ---------------------------- | | | | --- | --- | | Description: | Set local IP address for outgoing proxy connections | | Syntax: | ``` ProxySourceAddress address ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | Available in version 2.3.9 and later | This directive allows to set a specific local address to bind to when connecting to a backend server. ProxyStatus Directive --------------------- | | | | --- | --- | | Description: | Show Proxy LoadBalancer status in mod\_status | | Syntax: | ``` ProxyStatus Off|On|Full ``` | | Default: | ``` ProxyStatus Off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | | Compatibility: | Available in version 2.2 and later | This directive determines whether or not proxy loadbalancer status data is displayed via the `<mod_status>` server-status page. **Note** **Full** is synonymous with **On** ProxyTimeout Directive ---------------------- | | | | --- | --- | | Description: | Network timeout for proxied requests | | Syntax: | ``` ProxyTimeout seconds ``` | | Default: | ``` Value of Timeout ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | This directive allows a user to specify a timeout on proxy requests. This is useful when you have a slow/buggy appserver which hangs, and you would rather just return a timeout and fail gracefully instead of waiting however long it takes the server to return. ProxyVia Directive ------------------ | | | | --- | --- | | Description: | Information provided in the `Via` HTTP response header for proxied requests | | Syntax: | ``` ProxyVia On|Off|Full|Block ``` | | Default: | ``` ProxyVia Off ``` | | Context: | server config, virtual host | | Status: | Extension | | Module: | mod\_proxy | This directive controls the use of the `Via:` HTTP header by the proxy. Its intended use is to control the flow of proxy requests along a chain of proxy servers. See [RFC 2616](http://www.ietf.org/rfc/rfc2616.txt) (HTTP/1.1), section 14.45 for an explanation of `Via:` header lines. * If set to `Off`, which is the default, no special processing is performed. If a request or reply contains a `Via:` header, it is passed through unchanged. * If set to `On`, each request and reply will get a `Via:` header line added for the current host. * If set to `Full`, each generated `Via:` header line will additionally have the Apache httpd server version shown as a `Via:` comment field. * If set to `Block`, every proxy request will have all its `Via:` header lines removed. No new `Via:` header will be generated.
programming_docs
apache_http_server Apache MPM prefork Apache MPM prefork ================== | | | | --- | --- | | Description: | Implements a non-threaded, pre-forking web server | | Status: | MPM | | Module Identifier: | mpm\_prefork\_module | | Source File: | prefork.c | ### Summary This Multi-Processing Module (MPM) implements a non-threaded, pre-forking web server. Each server process may answer incoming requests, and a parent process manages the size of the server pool. It is appropriate for sites that need to avoid threading for compatibility with non-thread-safe libraries. It is also the best MPM for isolating each request, so that a problem with a single request will not affect any other. This MPM is very self-regulating, so it is rarely necessary to adjust its configuration directives. Most important is that `[MaxRequestWorkers](mpm_common#maxrequestworkers)` be big enough to handle as many simultaneous requests as you expect to receive, but small enough to assure that there is enough physical RAM for all processes. How it Works ------------ A single control process is responsible for launching child processes which listen for connections and serve them when they arrive. Apache httpd always tries to maintain several spare or idle server processes, which stand ready to serve incoming requests. In this way, clients do not need to wait for a new child processes to be forked before their requests can be served. The `[StartServers](mpm_common#startservers)`, `[MinSpareServers](#minspareservers)`, `[MaxSpareServers](#maxspareservers)`, and `[MaxRequestWorkers](mpm_common#maxrequestworkers)` regulate how the parent process creates children to serve requests. In general, Apache httpd is very self-regulating, so most sites do not need to adjust these directives from their default values. Sites which need to serve more than 256 simultaneous requests may need to increase `[MaxRequestWorkers](mpm_common#maxrequestworkers)`, while sites with limited memory may need to decrease `[MaxRequestWorkers](mpm_common#maxrequestworkers)` to keep the server from thrashing (swapping memory to disk and back). More information about tuning process creation is provided in the [performance hints](../misc/perf-tuning) documentation. While the parent process is usually started as `root` under Unix in order to bind to port 80, the child processes are launched by Apache httpd as a less-privileged user. The `[User](mod_unixd#user)` and `[Group](mod_unixd#group)` directives are used to set the privileges of the Apache httpd child processes. The child processes must be able to read all the content that will be served, but should have as few privileges beyond that as possible. `[MaxConnectionsPerChild](mpm_common#maxconnectionsperchild)` controls how frequently the server recycles processes by killing old ones and launching new ones. This MPM uses the `mpm-accept` mutex to serialize access to incoming connections when subject to the thundering herd problem (generally, when there are multiple listening sockets). The implementation aspects of this mutex can be configured with the `[Mutex](core#mutex)` directive. The [performance hints](../misc/perf-tuning) documentation has additional information about this mutex. MaxSpareServers Directive ------------------------- | | | | --- | --- | | Description: | Maximum number of idle child server processes | | Syntax: | ``` MaxSpareServers number ``` | | Default: | ``` MaxSpareServers 10 ``` | | Context: | server config | | Status: | MPM | | Module: | prefork | The `MaxSpareServers` directive sets the desired maximum number of *idle* child server processes. An idle process is one which is not handling a request. If there are more than `MaxSpareServers` idle, then the parent process will kill off the excess processes. Tuning of this parameter should only be necessary on very busy sites. Setting this parameter to a large number is almost always a bad idea. If you are trying to set the value equal to or lower than `[MinSpareServers](#minspareservers)`, Apache HTTP Server will automatically adjust it to `MinSpareServers``+ 1`. ### See also * `[MinSpareServers](#minspareservers)` * `[StartServers](mpm_common#startservers)` * `[MaxSpareThreads](mpm_common#maxsparethreads)` MinSpareServers Directive ------------------------- | | | | --- | --- | | Description: | Minimum number of idle child server processes | | Syntax: | ``` MinSpareServers number ``` | | Default: | ``` MinSpareServers 5 ``` | | Context: | server config | | Status: | MPM | | Module: | prefork | The `MinSpareServers` directive sets the desired minimum number of *idle* child server processes. An idle process is one which is not handling a request. If there are fewer than `MinSpareServers` idle, then the parent process creates new children: It will spawn one, wait a second, then spawn two, wait a second, then spawn four, and it will continue exponentially until it is spawning 32 children per second. It will stop whenever it satisfies the `MinSpareServers` setting. Tuning of this parameter should only be necessary on very busy sites. Setting this parameter to a large number is almost always a bad idea. ### See also * `[MaxSpareServers](#maxspareservers)` * `[StartServers](mpm_common#startservers)` * `[MinSpareThreads](mpm_common#minsparethreads)` apache_http_server Apache Module mod_autoindex Apache Module mod\_autoindex ============================ | | | | --- | --- | | Description: | Generates directory indexes, automatically, similar to the Unix `ls` command or the Win32 `dir` shell command | | Status: | Base | | Module Identifier: | autoindex\_module | | Source File: | mod\_autoindex.c | ### Summary The index of a directory can come from one of two sources: * A file located in that directory, typically called `index.html`. The `[DirectoryIndex](mod_dir#directoryindex)` directive sets the name of the file or files to be used. This is controlled by `<mod_dir>`. * Otherwise, a listing generated by the server. The other directives control the format of this listing. The `[AddIcon](#addicon)`, `[AddIconByEncoding](#addiconbyencoding)` and `[AddIconByType](#addiconbytype)` are used to set a list of icons to display for various file types; for each file listed, the first icon listed that matches the file is displayed. These are controlled by `<mod_autoindex>`. The two functions are separated so that you can completely remove (or replace) automatic index generation should you want to. Automatic index generation is enabled with using `Options +Indexes`. See the `[Options](core#options)` directive for more details. If the `[FancyIndexing](#indexoptions.fancyindexing)` option is given with the `[IndexOptions](#indexoptions)` directive, the column headers are links that control the order of the display. If you select a header link, the listing will be regenerated, sorted by the values in that column. Selecting the same header repeatedly toggles between ascending and descending order. These column header links are suppressed with the `[IndexOptions](#indexoptions)` directive's `[SuppressColumnSorting](#indexoptions.suppresscolumnsorting)` option. Note that when the display is sorted by "Size", it's the *actual* size of the files that's used, not the displayed value - so a 1010-byte file will always be displayed before a 1011-byte file (if in ascending order) even though they both are shown as "1K". Autoindex Request Query Arguments --------------------------------- Various query string arguments are available to give the client some control over the ordering of the directory listing, as well as what files are listed. If you do not wish to give the client this control, the `[IndexOptions IgnoreClient](#indexoptions.ignoreclient)` option disables that functionality. The column sorting headers themselves are self-referencing hyperlinks that add the sort query options shown below. Any option below may be added to any request for the directory resource. * `C=N` sorts the directory by file name * `C=M` sorts the directory by last-modified date, then file name * `C=S` sorts the directory by size, then file name * `C=D` sorts the directory by description, then file name * `O=A` sorts the listing in Ascending Order * `O=D` sorts the listing in Descending Order * `F=0` formats the listing as a simple list (not FancyIndexed) * `F=1` formats the listing as a FancyIndexed list * `F=2` formats the listing as an HTMLTable FancyIndexed list * `V=0` disables version sorting * `V=1` enables version sorting * `P=pattern` lists only files matching the given pattern Note that the 'P'attern query argument is tested *after* the usual `[IndexIgnore](#indexignore)` directives are processed, and all file names are still subjected to the same criteria as any other autoindex listing. The Query Arguments parser in `<mod_autoindex>` will stop abruptly when an unrecognized option is encountered. The Query Arguments must be well formed, according to the table above. The simple example below, which can be clipped and saved in a header.html file, illustrates these query options. Note that the unknown "X" argument, for the submit button, is listed last to assure the arguments are all parsed before `<mod_autoindex>` encounters the X=Go input. ### Example ``` <form action="" method="get"> Show me a <select name="F"> <option value="0"> Plain list</option> <option value="1" selected="selected"> Fancy list</option> <option value="2"> Table list</option> </select> Sorted by <select name="C"> <option value="N" selected="selected"> Name</option> <option value="M"> Date Modified</option> <option value="S"> Size</option> <option value="D"> Description</option> </select> <select name="O"> <option value="A" selected="selected"> Ascending</option> <option value="D"> Descending</option> </select> <select name="V"> <option value="0" selected="selected"> in Normal order</option> <option value="1"> in Version order</option> </select> Matching <input type="text" name="P" value="*" /> <input type="submit" name="X" value="Go" /> </form> ``` AddAlt Directive ---------------- | | | | --- | --- | | Description: | Alternate text to display for a file, instead of an icon selected by filename | | Syntax: | ``` AddAlt string file [file] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | `AddAlt` provides the alternate text to display for a file, instead of an icon, for `[FancyIndexing](#indexoptions.fancyindexing)`. File is a file extension, partial filename, wild-card expression or full filename for files to describe. If String contains any whitespace, you have to enclose it in quotes (`"` or `'`). This alternate text is displayed if the client is image-incapable, has image loading disabled, or fails to retrieve the icon. ``` AddAlt "PDF file" *.pdf AddAlt Compressed *.gz *.zip *.Z ``` AddAltByEncoding Directive -------------------------- | | | | --- | --- | | Description: | Alternate text to display for a file instead of an icon selected by MIME-encoding | | Syntax: | ``` AddAltByEncoding string MIME-encoding [MIME-encoding] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | `AddAltByEncoding` provides the alternate text to display for a file, instead of an icon, for `[FancyIndexing](#indexoptions.fancyindexing)`. MIME-encoding is a valid content-encoding, such as `x-compress`. If String contains any whitespace, you have to enclose it in quotes (`"` or `'`). This alternate text is displayed if the client is image-incapable, has image loading disabled, or fails to retrieve the icon. ``` AddAltByEncoding gzip x-gzip ``` AddAltByType Directive ---------------------- | | | | --- | --- | | Description: | Alternate text to display for a file, instead of an icon selected by MIME content-type | | Syntax: | ``` AddAltByType string MIME-type [MIME-type] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | `AddAltByType` sets the alternate text to display for a file, instead of an icon, for `[FancyIndexing](#indexoptions.fancyindexing)`. MIME-type is a valid content-type, such as `text/html`. If String contains any whitespace, you have to enclose it in quotes (`"` or `'`). This alternate text is displayed if the client is image-incapable, has image loading disabled, or fails to retrieve the icon. ``` AddAltByType 'plain text' text/plain ``` AddDescription Directive ------------------------ | | | | --- | --- | | Description: | Description to display for a file | | Syntax: | ``` AddDescription string file [file] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | This sets the description to display for a file, for `[FancyIndexing](#indexoptions.fancyindexing)`. File is a file extension, partial filename, wild-card expression or full filename for files to describe. String is enclosed in double quotes (`"`). ``` AddDescription "The planet Mars" mars.gif AddDescription "My friend Marshall" friends/mars.gif ``` The typical, default description field is 23 bytes wide. 6 more bytes are added by the `[IndexOptions SuppressIcon](#indexoptions.suppressicon)` option, 7 bytes are added by the `[IndexOptions SuppressSize](#indexoptions.suppresssize)` option, and 19 bytes are added by the `[IndexOptions SuppressLastModified](#indexoptions.suppresslastmodified)` option. Therefore, the widest default the description column is ever assigned is 55 bytes. Since the File argument may be a partial file name, please remember that a too-short partial filename may match unintended files. For example, `le.html` will match the file `le.html` but will also match the file `example.html`. In the event that there may be ambiguity, use as complete a filename as you can, but keep in mind that the first match encountered will be used, and order your list of `AddDescription` directives accordingly. See the [DescriptionWidth](#indexoptions.descriptionwidth) `[IndexOptions](#indexoptions)` keyword for details on overriding the size of this column, or allowing descriptions of unlimited length. **Caution** Descriptive text defined with `AddDescription` may contain HTML markup, such as tags and character entities. If the width of the description column should happen to truncate a tagged element (such as cutting off the end of a bolded phrase), the results may affect the rest of the directory listing. **Arguments with path information** Absolute paths are not currently supported and do not match anything at runtime. Arguments with relative path information, which would normally only be used in htaccess context, are implicitly prefixed with '\*/' to avoid matching partial directory names. AddIcon Directive ----------------- | | | | --- | --- | | Description: | Icon to display for a file selected by name | | Syntax: | ``` AddIcon icon name [name] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | This sets the icon to display next to a file ending in name for `[FancyIndexing](#indexoptions.fancyindexing)`. Icon is either a (%-escaped) relative URL to the icon, a fully qualified remote URL, or of the format `(alttext,url)` where alttext is the text tag given for an icon for non-graphical browsers. Name is either `^^DIRECTORY^^` for directories, `^^BLANKICON^^` for blank lines (to format the list correctly), a file extension, a wildcard expression, a partial filename or a complete filename. `^^BLANKICON^^` is only used for formatting, and so is unnecessary if you're using `IndexOptions HTMLTable`. ``` #Examples AddIcon (IMG,/icons/image.png) .gif .jpg .png AddIcon /icons/dir.png ^^DIRECTORY^^ AddIcon /icons/backup.png *~ ``` `[AddIconByType](#addiconbytype)` should be used in preference to `AddIcon`, when possible. AddIconByEncoding Directive --------------------------- | | | | --- | --- | | Description: | Icon to display next to files selected by MIME content-encoding | | Syntax: | ``` AddIconByEncoding icon MIME-encoding [MIME-encoding] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | This sets the icon to display next to files with `[FancyIndexing](#indexoptions.fancyindexing)`. Icon is either a (%-escaped) relative URL to the icon, a fully qualified remote URL, or of the format `(alttext,url)` where alttext is the text tag given for an icon for non-graphical browsers. MIME-encoding is a valid content-encoding, such as `x-compress`. ``` AddIconByEncoding /icons/compress.png x-compress ``` AddIconByType Directive ----------------------- | | | | --- | --- | | Description: | Icon to display next to files selected by MIME content-type | | Syntax: | ``` AddIconByType icon MIME-type [MIME-type] ... ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | This sets the icon to display next to files of type MIME-type for `[FancyIndexing](#indexoptions.fancyindexing)`. Icon is either a (%-escaped) relative URL to the icon, a fully qualified remote URL, or of the format `(alttext,url)` where alttext is the text tag given for an icon for non-graphical browsers. MIME-type is a wildcard expression matching required the mime types. ``` AddIconByType (IMG,/icons/image.png) image/* ``` DefaultIcon Directive --------------------- | | | | --- | --- | | Description: | Icon to display for files when no specific icon is configured | | Syntax: | ``` DefaultIcon url-path ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | The `DefaultIcon` directive sets the icon to display for files when no specific icon is known, for `[FancyIndexing](#indexoptions.fancyindexing)`. Url-path is a (%-escaped) relative URL to the icon, or a fully qualified remote URL. ``` DefaultIcon /icon/unknown.png ``` HeaderName Directive -------------------- | | | | --- | --- | | Description: | Name of the file that will be inserted at the top of the index listing | | Syntax: | ``` HeaderName filename ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | The `HeaderName` directive sets the name of the file that will be inserted at the top of the index listing. Filename is the name of the file to include. ``` HeaderName HEADER.html ``` Both HeaderName and `[ReadmeName](#readmename)` now treat Filename as a URI path relative to the one used to access the directory being indexed. If Filename begins with a slash, it will be taken to be relative to the `[DocumentRoot](core#documentroot)`. ``` HeaderName /include/HEADER.html ``` Filename must resolve to a document with a major content type of `text/*` (*e.g.*, `text/html`, `text/plain`, etc.). This means that filename may refer to a CGI script if the script's actual file type (as opposed to its output) is marked as `text/html` such as with a directive like: ``` AddType text/html .cgi ``` [Content negotiation](../content-negotiation) will be performed if `[Options](core#options)` `MultiViews` is in effect. If filename resolves to a static `text/html` document (not a CGI script) and either one of the `[options](core#options)` `Includes` or `IncludesNOEXEC` is enabled, the file will be processed for server-side includes (see the `<mod_include>` documentation). If the file specified by `HeaderName` contains the beginnings of an HTML document (<html>, <head>, etc.) then you will probably want to set [`IndexOptions +SuppressHTMLPreamble`](#indexoptions.suppresshtmlpreamble), so that these tags are not repeated. ### See also * `[ReadmeName](#readmename)` IndexHeadInsert Directive ------------------------- | | | | --- | --- | | Description: | Inserts text in the HEAD section of an index page. | | Syntax: | ``` IndexHeadInsert "markup ..." ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | The `IndexHeadInsert` directive specifies a string to insert in the <head> section of the HTML generated for the index page. ``` IndexHeadInsert "<link rel=\"sitemap\" href=\"/sitemap.html\">" ``` IndexIgnore Directive --------------------- | | | | --- | --- | | Description: | Adds to the list of files to hide when listing a directory | | Syntax: | ``` IndexIgnore file [file] ... ``` | | Default: | ``` IndexIgnore "." ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | The `IndexIgnore` directive adds to the list of files to hide when listing a directory. File is a shell-style wildcard expression or full filename. Multiple IndexIgnore directives add to the list, rather than replacing the list of ignored files. By default, the list contains `.` (the current directory). ``` IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t ``` **Regular Expressions** This directive does not currently work in configuration sections that have regular expression arguments, such as `[<DirectoryMatch>](core#directorymatch)` IndexIgnoreReset Directive -------------------------- | | | | --- | --- | | Description: | Empties the list of files to hide when listing a directory | | Syntax: | ``` IndexIgnoreReset ON|OFF ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | | Compatibility: | 2.3.10 and later | The `IndexIgnoreReset` directive removes any files ignored by `[IndexIgnore](#indexignore)` otherwise inherited from other configuration sections. ``` <Directory "/var/www"> IndexIgnore *.bak .??* *~ *# HEADER* README* RCS CVS *,v *,t </Directory> <Directory "/var/www/backups"> IndexIgnoreReset ON IndexIgnore .??* *# HEADER* README* RCS CVS *,v *,t </Directory> ``` Review the default configuration for a list of patterns that you might want to explicitly ignore after using this directive. IndexOptions Directive ---------------------- | | | | --- | --- | | Description: | Various configuration settings for directory indexing | | Syntax: | ``` IndexOptions [+|-]option [[+|-]option] ... ``` | | Default: | ``` By default, no options are enabled. ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | The `IndexOptions` directive specifies the behavior of the directory indexing. Option can be one of AddAltClass Adds an additional CSS class declaration to each row of the directory listing table when `IndexOptions HTMLTable` is in effect and an `IndexStyleSheet` is defined. Rather than the standard `even` and `odd` classes that would otherwise be applied to each row of the table, a class of `even-*ALT*` or `odd-*ALT*` where *ALT* is either the standard alt text associated with the file style (eg. *snd*, *txt*, *img*, etc) or the alt text defined by one of the various `AddAlt*` directives. Charset=character-set The `Charset` keyword allows you to specify the character set of the generated page. The default is `UTF-8` on Windows and Mac OS X, and `ISO-8859-1` elsewhere. (It depends on whether the underlying file system uses Unicode filenames or not.) ``` IndexOptions Charset=UTF-8 ``` DescriptionWidth=[n | \*] The `DescriptionWidth` keyword allows you to specify the width of the description column in characters. `-DescriptionWidth` (or unset) allows `<mod_autoindex>` to calculate the best width. `DescriptionWidth=n` fixes the column width to n bytes wide. `DescriptionWidth=*` grows the column to the width necessary to accommodate the longest description string. **See the section on `[AddDescription](#adddescription)` for dangers inherent in truncating descriptions.** FancyIndexing This turns on fancy indexing of directories. FoldersFirst If this option is enabled, subdirectory listings will *always* appear first, followed by normal files in the directory. The listing is basically broken into two components, the files and the subdirectories, and each is sorted separately and then displayed subdirectories-first. For instance, if the sort order is descending by name, and `FoldersFirst` is enabled, subdirectory `Zed` will be listed before subdirectory `Beta`, which will be listed before normal files `Gamma` and `Alpha`. **This option only has an effect if [`FancyIndexing`](#indexoptions.fancyindexing) is also enabled.** HTMLTable This option with `FancyIndexing` constructs a simple table for the fancy directory listing. It is necessary for utf-8 enabled platforms or if file names or description text will alternate between left-to-right and right-to-left reading order. IconsAreLinks This makes the icons part of the anchor for the filename, for fancy indexing. IconHeight[=pixels] Presence of this option, when used with `IconWidth`, will cause the server to include `height` and `width` attributes in the `img` tag for the file icon. This allows browser to precalculate the page layout without having to wait until all the images have been loaded. If no value is given for the option, it defaults to the standard height of the icons supplied with the Apache httpd software. **This option only has an effect if [`FancyIndexing`](#indexoptions.fancyindexing) is also enabled.** IconWidth[=pixels] Presence of this option, when used with `IconHeight`, will cause the server to include `height` and `width` attributes in the `img` tag for the file icon. This allows browser to precalculate the page layout without having to wait until all the images have been loaded. If no value is given for the option, it defaults to the standard width of the icons supplied with the Apache httpd software. IgnoreCase If this option is enabled, names are sorted in a case-insensitive manner. For instance, if the sort order is ascending by name, and `IgnoreCase` is enabled, file Zeta will be listed after file alfa (Note: file GAMMA will always be listed before file gamma). IgnoreClient This option causes `<mod_autoindex>` to ignore all query variables from the client, including sort order (implies `[SuppressColumnSorting](#indexoptions.suppresscolumnsorting)`.) NameWidth=[n | \*] The `NameWidth` keyword allows you to specify the width of the filename column in bytes. `-NameWidth` (or unset) allows `<mod_autoindex>` to calculate the best width, but only up to 20 bytes wide. `NameWidth=n` fixes the column width to n bytes wide. `NameWidth=*` grows the column to the necessary width. ScanHTMLTitles This enables the extraction of the title from HTML documents for fancy indexing. If the file does not have a description given by `[AddDescription](#adddescription)` then httpd will read the document for the value of the `title` element. This is CPU and disk intensive. ShowForbidden If specified, Apache httpd will show files normally hidden because the subrequest returned `HTTP_UNAUTHORIZED` or `HTTP_FORBIDDEN` SuppressColumnSorting If specified, Apache httpd will not make the column headings in a FancyIndexed directory listing into links for sorting. The default behavior is for them to be links; selecting the column heading will sort the directory listing by the values in that column. However, query string arguments which are appended to the URL will still be honored. That behavior is controlled by [`IndexOptions IgnoreClient`](#indexoptions.ignoreclient). SuppressDescription This will suppress the file description in fancy indexing listings. By default, no file descriptions are defined, and so the use of this option will regain 23 characters of screen space to use for something else. See `[AddDescription](#adddescription)` for information about setting the file description. See also the `[DescriptionWidth](#indexoptions.descriptionwidth)` index option to limit the size of the description column. **This option only has an effect if [`FancyIndexing`](#indexoptions.fancyindexing) is also enabled.** SuppressHTMLPreamble If the directory actually contains a file specified by the `[HeaderName](#headername)` directive, the module usually includes the contents of the file after a standard HTML preamble (`<html>`, `<head>`, *et cetera*). The `SuppressHTMLPreamble` option disables this behaviour, causing the module to start the display with the header file contents. The header file must contain appropriate HTML instructions in this case. If there is no header file, the preamble is generated as usual. If you also specify a `[ReadmeName](#readmename)`, and if that file exists, The closing </body></html> tags are also omitted from the output, under the assumption that you'll likely put those closing tags in that file. SuppressIcon This will suppress the icon in fancy indexing listings. Combining both `SuppressIcon` and `SuppressRules` yields proper HTML 3.2 output, which by the final specification prohibits `img` and `hr` elements from the `pre` block (used to format FancyIndexed listings.) SuppressLastModified This will suppress the display of the last modification date, in fancy indexing listings. **This option only has an effect if [`FancyIndexing`](#indexoptions.fancyindexing) is also enabled.** SuppressRules This will suppress the horizontal rule lines (`hr` elements) in directory listings. Combining both `SuppressIcon` and `SuppressRules` yields proper HTML 3.2 output, which by the final specification prohibits `img` and `hr` elements from the `pre` block (used to format FancyIndexed listings.) **This option only has an effect if [`FancyIndexing`](#indexoptions.fancyindexing) is also enabled.** SuppressSize This will suppress the file size in fancy indexing listings. **This option only has an effect if [`FancyIndexing`](#indexoptions.fancyindexing) is also enabled.** TrackModified This returns the `Last-Modified` and `ETag` values for the listed directory in the HTTP header. It is only valid if the operating system and file system return appropriate stat() results. Some Unix systems do so, as do OS2's JFS and Win32's NTFS volumes. OS2 and Win32 FAT volumes, for example, do not. Once this feature is enabled, the client or proxy can track changes to the list of files when they perform a `HEAD` request. Note some operating systems correctly track new and removed files, but do not track changes for sizes or dates of the files within the directory. **Changes to the size or date stamp of an existing file will not update the `Last-Modified` header on all Unix platforms.** If this is a concern, leave this option disabled. Type=MIME content-type The `Type` keyword allows you to specify the MIME content-type of the generated page. The default is text/html. ``` IndexOptions Type=text/plain ``` UseOldDateFormat (*Apache HTTP Server 2.4.26 and later*) The date format used for the `Last Modified` field was inadvertently changed to `"%Y-%m-%d %H:%M"` from `"%d-%b-%Y %H:%M"` in 2.4.0. Setting this option restores the date format from 2.2 and earlier. VersionSort The `VersionSort` keyword causes files containing version numbers to sort in a natural way. Strings are sorted as usual, except that substrings of digits in the name and description are compared according to their numeric value. ### Example: ``` foo-1.7 foo-1.7.2 foo-1.7.12 foo-1.8.2 foo-1.8.2a foo-1.12 ``` If the number starts with a zero, then it is considered to be a fraction: ``` foo-1.001 foo-1.002 foo-1.030 foo-1.04 ``` XHTML The `XHTML` keyword forces `<mod_autoindex>` to emit XHTML 1.0 code instead of HTML 3.2. **This option only has an effect if [`FancyIndexing`](#indexoptions.fancyindexing) is also enabled.** Incremental IndexOptions Be aware of how multiple `IndexOptions` are handled. * Multiple `IndexOptions` directives for a single directory are now merged together. The result of: ``` <Directory "/foo"> IndexOptions HTMLTable IndexOptions SuppressColumnsorting </Directory> ``` will be the equivalent of ``` IndexOptions HTMLTable SuppressColumnsorting ``` * The addition of the incremental syntax (*i.e.*, prefixing keywords with `+` or `-`). Whenever a '+' or '-' prefixed keyword is encountered, it is applied to the current `IndexOptions` settings (which may have been inherited from an upper-level directory). However, whenever an unprefixed keyword is processed, it clears all inherited options and any incremental settings encountered so far. Consider the following example: ``` IndexOptions +ScanHTMLTitles -IconsAreLinks FancyIndexing IndexOptions +SuppressSize ``` The net effect is equivalent to `IndexOptions FancyIndexing +SuppressSize`, because the unprefixed `FancyIndexing` discarded the incremental keywords before it, but allowed them to start accumulating again afterward. To unconditionally set the `IndexOptions` for a particular directory, clearing the inherited settings, specify keywords without any `+` or `-` prefixes. IndexOrderDefault Directive --------------------------- | | | | --- | --- | | Description: | Sets the default ordering of the directory index | | Syntax: | ``` IndexOrderDefault Ascending|Descending Name|Date|Size|Description ``` | | Default: | ``` IndexOrderDefault Ascending Name ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | The `IndexOrderDefault` directive is used in combination with the `[FancyIndexing](#indexoptions.fancyindexing)` index option. By default, fancyindexed directory listings are displayed in ascending order by filename; the `IndexOrderDefault` allows you to change this initial display order. `IndexOrderDefault` takes two arguments. The first must be either `Ascending` or `Descending`, indicating the direction of the sort. The second argument must be one of the keywords `Name`, `Date`, `Size`, or `Description`, and identifies the primary key. The secondary key is *always* the ascending filename. You can, if desired, prevent the client from reordering the list by also adding the `[SuppressColumnSorting](#indexoptions.suppresscolumnsorting)` index option to remove the sort link from the top of the column, along with the `[IgnoreClient](#indexoptions.ignoreclient)` index option to prevent them from manually adding sort options to the query string in order to override your ordering preferences. IndexStyleSheet Directive ------------------------- | | | | --- | --- | | Description: | Adds a CSS stylesheet to the directory index | | Syntax: | ``` IndexStyleSheet url-path ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | The `IndexStyleSheet` directive sets the name of the file that will be used as the CSS for the index listing. ``` IndexStyleSheet "/css/style.css" ``` Using this directive in conjunction with `IndexOptions HTMLTable` adds a number of CSS classes to the resulting HTML. The entire table is given a CSS id of `indexlist` and the following classes are associated with the various parts of the listing: | Class | Definition | | --- | --- | | tr.indexhead | Header row of listing | | th.indexcolicon and td.indexcolicon | Icon column | | th.indexcolname and td.indexcolname | File name column | | th.indexcollastmod and td.indexcollastmod | Last modified column | | th.indexcolsize and td.indexcolsize | File size column | | th.indexcoldesc and td.indexcoldesc | Description column | | tr.breakrow | Horizontal rule at the bottom of the table | | tr.odd and tr.even | Alternating even and odd rows | ReadmeName Directive -------------------- | | | | --- | --- | | Description: | Name of the file that will be inserted at the end of the index listing | | Syntax: | ``` ReadmeName filename ``` | | Context: | server config, virtual host, directory, .htaccess | | Override: | Indexes | | Status: | Base | | Module: | mod\_autoindex | The `ReadmeName` directive sets the name of the file that will be appended to the end of the index listing. Filename is the name of the file to include, and is taken to be relative to the location being indexed. If Filename begins with a slash, as in example 2, it will be taken to be relative to the `[DocumentRoot](core#documentroot)`. ``` # Example 1 ReadmeName FOOTER.html ``` ``` # Example 2 ReadmeName /include/FOOTER.html ``` See also `[HeaderName](#headername)`, where this behavior is described in greater detail.
programming_docs
apache_http_server Name-based Virtual Host Support Name-based Virtual Host Support =============================== This document describes when and how to use name-based virtual hosts. Name-based vs. IP-based Virtual Hosts ------------------------------------- [IP-based virtual hosts](ip-based) use the IP address of the connection to determine the correct virtual host to serve. Therefore you need to have a separate IP address for each host. With name-based virtual hosting, the server relies on the client to report the hostname as part of the HTTP headers. Using this technique, many different hosts can share the same IP address. Name-based virtual hosting is usually simpler, since you need only configure your DNS server to map each hostname to the correct IP address and then configure the Apache HTTP Server to recognize the different hostnames. Name-based virtual hosting also eases the demand for scarce IP addresses. Therefore you should use name-based virtual hosting unless you are using equipment that explicitly demands IP-based hosting. Historical reasons for IP-based virtual hosting based on client support are no longer applicable to a general-purpose web server. Name-based virtual hosting builds off of the IP-based virtual host selection algorithm, meaning that searches for the proper server name occur only between virtual hosts that have the best IP-based address. How the server selects the proper name-based virtual host --------------------------------------------------------- It is important to recognize that the first step in name-based virtual host resolution is IP-based resolution. Name-based virtual host resolution only chooses the most appropriate name-based virtual host after narrowing down the candidates to the best IP-based match. Using a wildcard (\*) for the IP address in all of the VirtualHost directives makes this IP-based mapping irrelevant. When a request arrives, the server will find the best (most specific) matching `[<VirtualHost>](../mod/core#virtualhost)` argument based on the IP address and port used by the request. If there is more than one virtual host containing this best-match address and port combination, Apache will further compare the `[ServerName](../mod/core#servername)` and `[ServerAlias](../mod/core#serveralias)` directives to the server name present in the request. If you omit the `[ServerName](../mod/core#servername)` directive from any name-based virtual host, the server will default to a fully qualified domain name (FQDN) derived from the system hostname. This implicitly set server name can lead to counter-intuitive virtual host matching and is discouraged. ### The default name-based vhost for an IP and port combination If no matching ServerName or ServerAlias is found in the set of virtual hosts containing the most specific matching IP address and port combination, then **the first listed virtual host** that matches that will be used. Using Name-based Virtual Hosts ------------------------------ | Related Modules | Related Directives | | --- | --- | | * `[core](../mod/core)` | * `[DocumentRoot](../mod/core#documentroot)` * `[ServerAlias](../mod/core#serveralias)` * `[ServerName](../mod/core#servername)` * `[<VirtualHost>](../mod/core#virtualhost)` | The first step is to create a `[<VirtualHost>](../mod/core#virtualhost)` block for each different host that you would like to serve. Inside each `[<VirtualHost>](../mod/core#virtualhost)` block, you will need at minimum a `[ServerName](../mod/core#servername)` directive to designate which host is served and a `[DocumentRoot](../mod/core#documentroot)` directive to show where in the filesystem the content for that host lives. **Main host goes away** Any request that doesn't match an existing `[<VirtualHost>](../mod/core#virtualhost)` is handled by the global server configuration, regardless of the hostname or ServerName. When you add a name-based virtual host to an existing server, and the virtual host arguments match preexisting IP and port combinations, requests will now be handled by an explicit virtual host. In this case, it's usually wise to create a [default virtual host](#defaultvhost) with a `[ServerName](../mod/core#servername)` matching that of the base server. New domains on the same interface and port, but requiring separate configurations, can then be added as subsequent (non-default) virtual hosts. **ServerName inheritance** It is best to always explicitly list a `[ServerName](../mod/core#servername)` in every name-based virtual host. If a `[VirtualHost](../mod/core#virtualhost)` doesn't specify a `[ServerName](../mod/core#servername)`, a server name will be inherited from the base server configuration. If no server name was specified globally, one is detected at startup through reverse DNS resolution of the first listening address. In either case, this inherited server name will influence name-based virtual host resolution, so it is best to always explicitly list a `[ServerName](../mod/core#servername)` in every name-based virtual host. For example, suppose that you are serving the domain `www.example.com` and you wish to add the virtual host `other.example.com`, which points at the same IP address. Then you simply add the following to `httpd.conf`: ``` <VirtualHost *:80> # This first-listed virtual host is also the default for *:80 ServerName www.example.com ServerAlias example.com DocumentRoot "/www/domain" </VirtualHost> <VirtualHost *:80> ServerName other.example.com DocumentRoot "/www/otherdomain" </VirtualHost> ``` You can alternatively specify an explicit IP address in place of the `*` in `[<VirtualHost>](../mod/core#virtualhost)` directives. For example, you might want to do this in order to run some name-based virtual hosts on one IP address, and either IP-based, or another set of name-based virtual hosts on another address. Many servers want to be accessible by more than one name. This is possible with the `[ServerAlias](../mod/core#serveralias)` directive, placed inside the `[<VirtualHost>](../mod/core#virtualhost)` section. For example in the first `[<VirtualHost>](../mod/core#virtualhost)` block above, the `[ServerAlias](../mod/core#serveralias)` directive indicates that the listed names are other names which people can use to see that same web site: ``` ServerAlias example.com *.example.com ``` then requests for all hosts in the `example.com` domain will be served by the `www.example.com` virtual host. The wildcard characters `*` and `?` can be used to match names. Of course, you can't just make up names and place them in `[ServerName](../mod/core#servername)` or `ServerAlias`. You must first have your DNS server properly configured to map those names to an IP address associated with your server. Name-based virtual hosts for the best-matching set of `[<virtualhost>](../mod/core#virtualhost)`s are processed in the order they appear in the configuration. The first matching `[ServerName](../mod/core#servername)` or `[ServerAlias](../mod/core#serveralias)` is used, with no different precedence for wildcards (nor for ServerName vs. ServerAlias). The complete list of names in the `[VirtualHost](../mod/core#virtualhost)` directive are treated just like a (non wildcard) `[ServerAlias](../mod/core#serveralias)`. Finally, you can fine-tune the configuration of the virtual hosts by placing other directives inside the `[<VirtualHost>](../mod/core#virtualhost)` containers. Most directives can be placed in these containers and will then change the configuration only of the relevant virtual host. To find out if a particular directive is allowed, check the Context of the directive. Configuration directives set in the *main server context* (outside any `[<VirtualHost>](../mod/core#virtualhost)` container) will be used only if they are not overridden by the virtual host settings. apache_http_server Apache Virtual Host documentation Apache Virtual Host documentation ================================= The term Virtual Host refers to the practice of running more than one web site (such as `company1.example.com` and `company2.example.com`) on a single machine. Virtual hosts can be "[IP-based](ip-based)", meaning that you have a different IP address for every web site, or "<name-based>", meaning that you have multiple names running on each IP address. The fact that they are running on the same physical server is not apparent to the end user. Apache was one of the first servers to support IP-based virtual hosts right out of the box. Versions 1.1 and later of Apache support both IP-based and name-based virtual hosts (vhosts). The latter variant of virtual hosts is sometimes also called *host-based* or *non-IP virtual hosts*. Below is a list of documentation pages which explain all details of virtual host support in Apache HTTP Server: Virtual Host Support -------------------- * [Name-based Virtual Hosts](name-based) (More than one web site per IP address) * [IP-based Virtual Hosts](ip-based) (An IP address for each web site) * [Virtual Host examples for common setups](examples) * [File Descriptor Limits](fd-limits) (or, *Too many log files*) * [Dynamically Configured Mass Virtual Hosting](mass) * [In-Depth Discussion of Virtual Host Matching](details) Configuration directives ------------------------ * `[<VirtualHost>](../mod/core#virtualhost)` * `[ServerName](../mod/core#servername)` * `[ServerAlias](../mod/core#serveralias)` * `[ServerPath](../mod/core#serverpath)` If you are trying to debug your virtual host configuration, you may find the `-S` command line switch useful. ### Unix example ``` apachectl -S ``` ### Windows example ``` httpd.exe -S ``` This command will dump out a description of how Apache parsed the configuration file. Careful examination of the IP addresses and server names may help uncover configuration mistakes. (See the docs for the `[httpd](../programs/httpd)` program for other command line options) apache_http_server Apache IP-based Virtual Host Support Apache IP-based Virtual Host Support ==================================== What is IP-based virtual hosting -------------------------------- IP-based virtual hosting is a method to apply different directives based on the IP address and port a request is received on. Most commonly, this is used to serve different websites on different ports or interfaces. In many cases, [name-based virtual hosts](name-based) are more convenient, because they allow many virtual hosts to share a single address/port. See [Name-based vs. IP-based Virtual Hosts](name-based#namevip) to help you decide. System requirements ------------------- As the term IP-based indicates, the server **must have a different IP address/port combination for each IP-based virtual host**. This can be achieved by the machine having several physical network connections, or by use of virtual interfaces which are supported by most modern operating systems (see system documentation for details, these are frequently called "ip aliases", and the "ifconfig" command is most commonly used to set them up), and/or using multiple port numbers. In the terminology of Apache HTTP Server, using a single IP address but multiple TCP ports, is also IP-based virtual hosting. How to set up Apache -------------------- There are two ways of configuring apache to support multiple hosts. Either by running a separate `[httpd](../programs/httpd)` daemon for each hostname, or by running a single daemon which supports all the virtual hosts. Use multiple daemons when: * There are security partitioning issues, such as company1 does not want anyone at company2 to be able to read their data except via the web. In this case you would need two daemons, each running with different `[User](../mod/mod_unixd#user)`, `[Group](../mod/mod_unixd#group)`, `[Listen](../mod/mpm_common#listen)`, and `[ServerRoot](../mod/core#serverroot)` settings. * You can afford the memory and file descriptor requirements of listening to every IP alias on the machine. It's only possible to `[Listen](../mod/mpm_common#listen)` to the "wildcard" address, or to specific addresses. So if you have a need to listen to a specific address for whatever reason, then you will need to listen to all specific addresses. (Although one `[httpd](../programs/httpd)` could listen to N-1 of the addresses, and another could listen to the remaining address.) Use a single daemon when: * Sharing of the httpd configuration between virtual hosts is acceptable. * The machine services a large number of requests, and so the performance loss in running separate daemons may be significant. Setting up multiple daemons --------------------------- Create a separate `[httpd](../programs/httpd)` installation for each virtual host. For each installation, use the `[Listen](../mod/mpm_common#listen)` directive in the configuration file to select which IP address (or virtual host) that daemon services. e.g. ``` Listen 192.0.2.100:80 ``` It is recommended that you use an IP address instead of a hostname (see [DNS caveats](../dns-caveats)). Setting up a single daemon with virtual hosts --------------------------------------------- For this case, a single `[httpd](../programs/httpd)` will service requests for the main server and all the virtual hosts. The `[VirtualHost](../mod/core#virtualhost)` directive in the configuration file is used to set the values of `[ServerAdmin](../mod/core#serveradmin)`, `[ServerName](../mod/core#servername)`, `[DocumentRoot](../mod/core#documentroot)`, `[ErrorLog](../mod/core#errorlog)` and `[TransferLog](../mod/mod_log_config#transferlog)` or `[CustomLog](../mod/mod_log_config#customlog)` configuration directives to different values for each virtual host. e.g. ``` <VirtualHost 172.20.30.40:80> ServerAdmin [email protected] DocumentRoot "/www/vhosts/www1" ServerName www1.example.com ErrorLog "/www/logs/www1/error_log" CustomLog "/www/logs/www1/access_log" combined </VirtualHost> <VirtualHost 172.20.30.50:80> ServerAdmin [email protected] DocumentRoot "/www/vhosts/www2" ServerName www2.example.org ErrorLog "/www/logs/www2/error_log" CustomLog "/www/logs/www2/access_log" combined </VirtualHost> ``` It is recommended that you use an IP address instead of a hostname in the <VirtualHost> directive (see [DNS caveats](../dns-caveats)). Specific IP addresses or ports have precedence over their wildcard equivalents, and any virtual host that matches has precedence over the servers base configuration. Almost **any** configuration directive can be put in the VirtualHost directive, with the exception of directives that control process creation and a few other directives. To find out if a directive can be used in the VirtualHost directive, check the Context using the [directive index](https://httpd.apache.org/docs/2.4/en/mod/quickreference.html). `[SuexecUserGroup](../mod/mod_suexec#suexecusergroup)` may be used inside a VirtualHost directive if the [suEXEC wrapper](../suexec) is used. *SECURITY:* When specifying where to write log files, be aware of some security risks which are present if anyone other than the user that starts Apache has write access to the directory where they are written. See the [security tips](../misc/security_tips) document for details. apache_http_server An In-Depth Discussion of Virtual Host Matching An In-Depth Discussion of Virtual Host Matching =============================================== This document attempts to explain exactly what Apache HTTP Server does when deciding what virtual host to serve a request from. Most users should read about [Name-based vs. IP-based Virtual Hosts](name-based#namevip) to decide which type they want to use, then read more about <name-based> or [IP-based](ip-based) virtualhosts, and then see [some examples](examples). If you want to understand all the details, then you can come back to this page. Configuration File ------------------ There is a *main server* which consists of all the definitions appearing outside of `<VirtualHost>` sections. There are virtual servers, called *vhosts*, which are defined by `[<VirtualHost>](../mod/core#virtualhost)` sections. Each `VirtualHost` directive includes one or more addresses and optional ports. Hostnames can be used in place of IP addresses in a virtual host definition, but they are resolved at startup and if any name resolutions fail, those virtual host definitions are ignored. This is, therefore, not recommended. The address can be specified as `*`, which will match a request if no other vhost has the explicit address on which the request was received. The address appearing in the `VirtualHost` directive can have an optional port. If the port is unspecified, it is treated as a wildcard port, which can also be indicated explicitly using `*`. The wildcard port matches any port. (Port numbers specified in the `VirtualHost` directive do not influence what port numbers Apache will listen on, they only control which `VirtualHost` will be selected to handle a request. Use the `[Listen](../mod/mpm_common#listen)` directive to control the addresses and ports on which the server listens.) Collectively the entire set of addresses (including multiple results from DNS lookups) are called the vhost's *address set*. Apache automatically discriminates on the basis of the HTTP `Host` header supplied by the client whenever the most specific match for an IP address and port combination is listed in multiple virtual hosts. The `[ServerName](../mod/core#servername)` directive may appear anywhere within the definition of a server. However, each appearance overrides the previous appearance (within that server). If no `ServerName` is specified, the server attempts to deduce it from the server's IP address. The first name-based vhost in the configuration file for a given IP:port pair is significant because it is used for all requests received on that address and port for which no other vhost for that IP:port pair has a matching ServerName or ServerAlias. It is also used for all SSL connections if the server does not support [Server Name Indication](https://httpd.apache.org/docs/2.4/en/glossary.html#servernameindication "see glossary"). The complete list of names in the `VirtualHost` directive are treated just like a (non wildcard) `ServerAlias` (but are not overridden by any `ServerAlias` statement). For every vhost various default values are set. In particular: 1. If a vhost has no `[ServerAdmin](../mod/core#serveradmin)`, `[Timeout](../mod/core#timeout)`, `[KeepAliveTimeout](../mod/core#keepalivetimeout)`, `[KeepAlive](../mod/core#keepalive)`, `[MaxKeepAliveRequests](../mod/core#maxkeepaliverequests)`, `[ReceiveBufferSize](../mod/mpm_common#receivebuffersize)`, or `[SendBufferSize](../mod/mpm_common#sendbuffersize)` directive then the respective value is inherited from the main server. (That is, inherited from whatever the final setting of that value is in the main server.) 2. The "lookup defaults" that define the default directory permissions for a vhost are merged with those of the main server. This includes any per-directory configuration information for any module. 3. The per-server configs for each module from the main server are merged into the vhost server. Essentially, the main server is treated as "defaults" or a "base" on which to build each vhost. But the positioning of these main server definitions in the config file is largely irrelevant -- the entire config of the main server has been parsed when this final merging occurs. So even if a main server definition appears after a vhost definition it might affect the vhost definition. If the main server has no `ServerName` at this point, then the hostname of the machine that `[httpd](../programs/httpd)` is running on is used instead. We will call the *main server address set* those IP addresses returned by a DNS lookup on the `ServerName` of the main server. For any undefined `ServerName` fields, a name-based vhost defaults to the address given first in the `VirtualHost` statement defining the vhost. Any vhost that includes the magic `_default_` wildcard is given the same `ServerName` as the main server. Virtual Host Matching --------------------- The server determines which vhost to use for a request as follows: ### IP address lookup When the connection is first received on some address and port, the server looks for all the `VirtualHost` definitions that have the same IP address and port. If there are no exact matches for the address and port, then wildcard (`*`) matches are considered. If no matches are found, the request is served by the main server. If there are `VirtualHost` definitions for the IP address, the next step is to decide if we have to deal with an IP-based or a name-based vhost. ### IP-based vhost If there is exactly one `VirtualHost` directive listing the IP address and port combination that was determined to be the best match, no further actions are performed and the request is served from the matching vhost. ### Name-based vhost If there are multiple `VirtualHost` directives listing the IP address and port combination that was determined to be the best match, the "list" in the remaining steps refers to the list of vhosts that matched, in the order they were in the configuration file. If the connection is using SSL, the server supports [Server Name Indication](https://httpd.apache.org/docs/2.4/en/glossary.html#servernameindication "see glossary"), and the SSL client handshake includes the TLS extension with the requested hostname, then that hostname is used below just like the `Host:` header would be used on a non-SSL connection. Otherwise, the first name-based vhost whose address matched is used for SSL connections. This is significant because the vhost determines which certificate the server will use for the connection. If the request contains a `Host:` header field, the list is searched for the first vhost with a matching `ServerName` or `ServerAlias`, and the request is served from that vhost. A `Host:` header field can contain a port number, but Apache always ignores it and matches against the real port to which the client sent the request. The first vhost in the config file with the specified IP address has the highest priority and catches any request to an unknown server name, or a request without a `Host:` header field (such as a HTTP/1.0 request). ### Persistent connections The *IP lookup* described above is only done *once* for a particular TCP/IP session while the *name lookup* is done on *every* request during a KeepAlive/persistent connection. In other words, a client may request pages from different name-based vhosts during a single persistent connection. ### Absolute URI If the URI from the request is an absolute URI, and its hostname and port match the main server or one of the configured virtual hosts *and* match the address and port to which the client sent the request, then the scheme/hostname/port prefix is stripped off and the remaining relative URI is served by the corresponding main server or virtual host. If it does not match, then the URI remains untouched and the request is taken to be a proxy request. ### Observations * Name-based virtual hosting is a process applied after the server has selected the best matching IP-based virtual host. * If you don't care what IP address the client has connected to, use a "\*" as the address of every virtual host, and name-based virtual hosting is applied across all configured virtual hosts. * `ServerName` and `ServerAlias` checks are never performed for an IP-based vhost. * Only the ordering of name-based vhosts for a specific address set is significant. The one name-based vhosts that comes first in the configuration file has the highest priority for its corresponding address set. * Any port in the `Host:` header field is never used during the matching process. Apache always uses the real port to which the client sent the request. * If two vhosts have an address in common, those common addresses act as name-based virtual hosts implicitly. This is new behavior as of 2.3.11. * The main server is only used to serve a request if the IP address and port number to which the client connected does not match any vhost (including a `*` vhost). In other words, the main server only catches a request for an unspecified address/port combination (unless there is a `_default_` vhost which matches that port). * You should never specify DNS names in `VirtualHost` directives because it will force your server to rely on DNS to boot. Furthermore it poses a security threat if you do not control the DNS for all the domains listed. There's [more information](../dns-caveats) available on this and the next two topics. * `ServerName` should always be set for each vhost. Otherwise a DNS lookup is required for each vhost. Tips ---- In addition to the tips on the [DNS Issues](../dns-caveats#tips) page, here are some further tips: * Place all main server definitions before any `VirtualHost` definitions. (This is to aid the readability of the configuration -- the post-config merging process makes it non-obvious that definitions mixed in around virtual hosts might affect all virtual hosts.)
programming_docs
apache_http_server Dynamically Configured Mass Virtual Hosting Dynamically Configured Mass Virtual Hosting =========================================== This document describes how to efficiently serve an arbitrary number of virtual hosts with the Apache HTTP Server. A [separate document](../rewrite/vhosts) discusses using `[mod\_rewrite](../mod/mod_rewrite)` to create dynamic mass virtual hosts. Motivation ---------- The techniques described here are of interest if your `httpd.conf` contains many `<VirtualHost>` sections that are substantially the same, for example: ``` <VirtualHost 111.22.33.44> ServerName customer-1.example.com DocumentRoot "/www/hosts/customer-1.example.com/docs" ScriptAlias "/cgi-bin/" "/www/hosts/customer-1.example.com/cgi-bin" </VirtualHost> <VirtualHost 111.22.33.44> ServerName customer-2.example.com DocumentRoot "/www/hosts/customer-2.example.com/docs" ScriptAlias "/cgi-bin/" "/www/hosts/customer-2.example.com/cgi-bin" </VirtualHost> <VirtualHost 111.22.33.44> ServerName customer-N.example.com DocumentRoot "/www/hosts/customer-N.example.com/docs" ScriptAlias "/cgi-bin/" "/www/hosts/customer-N.example.com/cgi-bin" </VirtualHost> ``` We wish to replace these multiple `<VirtualHost>` blocks with a mechanism that works them out dynamically. This has a number of advantages: 1. Your configuration file is smaller, so Apache starts more quickly and uses less memory. Perhaps more importantly, the smaller configuration is easier to maintain, and leaves less room for errors. 2. Adding virtual hosts is simply a matter of creating the appropriate directories in the filesystem and entries in the DNS - you don't need to reconfigure or restart Apache. The main disadvantage is that you cannot have a different log file for each virtual host; however, if you have many virtual hosts, doing this can be a bad idea anyway, because of the [number of file descriptors needed](fd-limits). It is better to [log to a pipe or a fifo](../logs#piped), and arrange for the process at the other end to split up the log files into one per virtual host. One example of such a process can be found in the [split-logfile](../programs/split-logfile) utility. Overview -------- A virtual host is defined by two pieces of information: its IP address, and the contents of the `Host:` header in the HTTP request. The dynamic mass virtual hosting technique used here is based on automatically inserting this information into the pathname of the file that is used to satisfy the request. This can be most easily done by using `[mod\_vhost\_alias](../mod/mod_vhost_alias)` with Apache httpd. Alternatively, [mod\_rewrite can be used](../rewrite/vhosts). Both of these modules are disabled by default; you must enable one of them when configuring and building Apache httpd if you want to use this technique. A couple of things need to be determined from the request in order to make the dynamic virtual host look like a normal one. The most important is the server name, which is used by the server to generate self-referential URLs etc. It is configured with the `ServerName` directive, and it is available to CGIs via the `SERVER_NAME` environment variable. The actual value used at run time is controlled by the `[UseCanonicalName](../mod/core#usecanonicalname)` setting. With `UseCanonicalName Off`, the server name is taken from the contents of the `Host:` header in the request. With `UseCanonicalName DNS`, it is taken from a reverse DNS lookup of the virtual host's IP address. The former setting is used for name-based dynamic virtual hosting, and the latter is used for IP-based hosting. If httpd cannot work out the server name because there is no `Host:` header, or the DNS lookup fails, then the value configured with `ServerName` is used instead. The other thing to determine is the document root (configured with `DocumentRoot` and available to CGI scripts via the `DOCUMENT_ROOT` environment variable). In a normal configuration, this is used by the core module when mapping URIs to filenames, but when the server is configured to do dynamic virtual hosting, that job must be taken over by another module (either `[mod\_vhost\_alias](../mod/mod_vhost_alias)` or `[mod\_rewrite](../mod/mod_rewrite)`), which has a different way of doing the mapping. Neither of these modules is responsible for setting the `DOCUMENT_ROOT` environment variable so if any CGIs or SSI documents make use of it, they will get a misleading value. Dynamic Virtual Hosts with mod\_vhost\_alias -------------------------------------------- This extract from `httpd.conf` implements the virtual host arrangement outlined in the [Motivation](#motivation) section above using `[mod\_vhost\_alias](../mod/mod_vhost_alias)`. ``` # get the server name from the Host: header UseCanonicalName Off # this log format can be split per-virtual-host based on the first field # using the split-logfile utility. LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon CustomLog "logs/access_log" vcommon # include the server name in the filenames used to satisfy requests VirtualDocumentRoot "/www/hosts/%0/docs" VirtualScriptAlias "/www/hosts/%0/cgi-bin" ``` This configuration can be changed into an IP-based virtual hosting solution by just turning `UseCanonicalName Off` into `UseCanonicalName DNS`. The server name that is inserted into the filename is then derived from the IP address of the virtual host. The variable `%0` references the requested servername, as indicated in the `Host:` header. See the `[mod\_vhost\_alias](../mod/mod_vhost_alias)` documentation for more usage examples. Simplified Dynamic Virtual Hosts -------------------------------- This is an adjustment of the above system, tailored for an ISP's web hosting server. Using `%2`, we can select substrings of the server name to use in the filename so that, for example, the documents for `www.user.example.com` are found in `/home/user/www`. It uses a single `cgi-bin` directory instead of one per virtual host. ``` UseCanonicalName Off LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon CustomLog "logs/access_log" vcommon # include part of the server name in the filenames VirtualDocumentRoot "/home/%2/www" # single cgi-bin directory ScriptAlias "/cgi-bin/" "/www/std-cgi/" ``` There are examples of more complicated `VirtualDocumentRoot` settings in the `[mod\_vhost\_alias](../mod/mod_vhost_alias)` documentation. Using Multiple Virtual Hosting Systems on the Same Server --------------------------------------------------------- With more complicated setups, you can use httpd's normal `<VirtualHost>` directives to control the scope of the various virtual hosting configurations. For example, you could have one IP address for general customers' homepages, and another for commercial customers, with the following setup. This can be combined with conventional `<VirtualHost>` configuration sections, as shown below. ``` UseCanonicalName Off LogFormat "%V %h %l %u %t \"%r\" %s %b" vcommon <Directory "/www/commercial"> Options FollowSymLinks AllowOverride All </Directory> <Directory "/www/homepages"> Options FollowSymLinks AllowOverride None </Directory> <VirtualHost 111.22.33.44> ServerName www.commercial.example.com CustomLog "logs/access_log.commercial" vcommon VirtualDocumentRoot "/www/commercial/%0/docs" VirtualScriptAlias "/www/commercial/%0/cgi-bin" </VirtualHost> <VirtualHost 111.22.33.45> ServerName www.homepages.example.com CustomLog "logs/access_log.homepages" vcommon VirtualDocumentRoot "/www/homepages/%0/docs" ScriptAlias "/cgi-bin/" "/www/std-cgi/" </VirtualHost> ``` **Note** If the first VirtualHost block does *not* include a `[ServerName](../mod/core#servername)` directive, the reverse DNS of the relevant IP will be used instead. If this is not the server name you wish to use, a bogus entry (eg. `ServerName none.example.com`) can be added to get around this behaviour. More Efficient IP-Based Virtual Hosting --------------------------------------- The configuration changes suggested to turn [the first example](#simple) into an IP-based virtual hosting setup result in a rather inefficient setup. A new DNS lookup is required for every request. To avoid this overhead, the filesystem can be arranged to correspond to the IP addresses, instead of to the host names, thereby negating the need for a DNS lookup. Logging will also have to be adjusted to fit this system. ``` # get the server name from the reverse DNS of the IP address UseCanonicalName DNS # include the IP address in the logs so they may be split LogFormat "%A %h %l %u %t \"%r\" %s %b" vcommon CustomLog "logs/access_log" vcommon # include the IP address in the filenames VirtualDocumentRootIP "/www/hosts/%0/docs" VirtualScriptAliasIP "/www/hosts/%0/cgi-bin" ``` Mass virtual hosts with mod\_rewrite ------------------------------------ Mass virtual hosting may also be accomplished using `[mod\_rewrite](../mod/mod_rewrite)`, either using simple `[RewriteRule](../mod/mod_rewrite#rewriterule)` directives, or using more complicated techniques such as storing the vhost definitions externally and accessing them via `[RewriteMap](../mod/mod_rewrite#rewritemap)`. These techniques are discussed in the [rewrite documentation](../rewrite/vhosts). Mass virtual hosts with mod\_macro ---------------------------------- Another option for dynamically generated virtual hosts is `[mod\_macro](../mod/mod_macro)`, with which you can create a virtualhost template, and invoke it for multiple hostnames. An example of this is provided in the **Usage** section of the module documentation. apache_http_server VirtualHost Examples VirtualHost Examples ==================== This document attempts to answer the commonly-asked questions about setting up [virtual hosts](index). These scenarios are those involving multiple web sites running on a single server, via <name-based> or [IP-based](ip-based) virtual hosts. Running several name-based web sites on a single IP address. ------------------------------------------------------------ Your server has multiple hostnames that resolve to a single address, and you want to respond differently for `www.example.com` and `www.example.org`. **Note** Creating virtual host configurations on your Apache server does not magically cause DNS entries to be created for those host names. You *must* have the names in DNS, resolving to your IP address, or nobody else will be able to see your web site. You can put entries in your `hosts` file for local testing, but that will work only from the machine with those `hosts` entries. ``` # Ensure that Apache listens on port 80 Listen 80 <VirtualHost *:80> DocumentRoot "/www/example1" ServerName www.example.com # Other directives here </VirtualHost> <VirtualHost *:80> DocumentRoot "/www/example2" ServerName www.example.org # Other directives here </VirtualHost> ``` The asterisks match all addresses, so the main server serves no requests. Due to the fact that the virtual host with `ServerName www.example.com` is first in the configuration file, it has the highest priority and can be seen as the default or primary server. That means that if a request is received that does not match one of the specified `[ServerName](../mod/core#servername)` directives, it will be served by this first `[<VirtualHost>](../mod/core#virtualhost)`. The above configuration is what you will want to use in almost all name-based virtual hosting situations. The only thing that this configuration will not work for, in fact, is when you are serving different content based on differing IP addresses or ports. **Note** You may replace `*` with a specific IP address on the system. Such virtual hosts will only be used for HTTP requests received on connection to the specified IP address. However, it is additionally useful to use `*` on systems where the IP address is not predictable - for example if you have a dynamic IP address with your ISP, and you are using some variety of dynamic DNS solution. Since `*` matches any IP address, this configuration would work without changes whenever your IP address changes. Name-based hosts on more than one IP address. --------------------------------------------- **Note** Any of the techniques discussed here can be extended to any number of IP addresses. The server has two IP addresses. On one (`172.20.30.40`), we will serve the "main" server, `server.example.com` and on the other (`172.20.30.50`), we will serve two or more virtual hosts. ``` Listen 80 # This is the "main" server running on 172.20.30.40 ServerName server.example.com DocumentRoot "/www/mainserver" <VirtualHost 172.20.30.50> DocumentRoot "/www/example1" ServerName www.example.com # Other directives here ... </VirtualHost> <VirtualHost 172.20.30.50> DocumentRoot "/www/example2" ServerName www.example.org # Other directives here ... </VirtualHost> ``` Any request to an address other than `172.20.30.50` will be served from the main server. A request to `172.20.30.50` with an unknown hostname, or no `Host:` header, will be served from `www.example.com`. Serving the same content on different IP addresses (such as an internal and external address). ---------------------------------------------------------------------------------------------- The server machine has two IP addresses (`192.168.1.1` and `172.20.30.40`). The machine is sitting between an internal (intranet) network and an external (internet) network. Outside of the network, the name `server.example.com` resolves to the external address (`172.20.30.40`), but inside the network, that same name resolves to the internal address (`192.168.1.1`). The server can be made to respond to internal and external requests with the same content, with just one `[<VirtualHost>](../mod/core#virtualhost)` section. ``` <VirtualHost 192.168.1.1 172.20.30.40> DocumentRoot "/www/server1" ServerName server.example.com ServerAlias server </VirtualHost> ``` Now requests from both networks will be served from the same `[<VirtualHost>](../mod/core#virtualhost)`. **Note:** On the internal network, one can just use the name `server` rather than the fully qualified host name `server.example.com`. Note also that, in the above example, you can replace the list of IP addresses with `*`, which will cause the server to respond the same on all addresses. Running different sites on different ports. ------------------------------------------- You have multiple domains going to the same IP and also want to serve multiple ports. The example below illustrates that the name-matching takes place after the best matching IP address and port combination is determined. ``` Listen 80 Listen 8080 <VirtualHost 172.20.30.40:80> ServerName www.example.com DocumentRoot "/www/domain-80" </VirtualHost> <VirtualHost 172.20.30.40:8080> ServerName www.example.com DocumentRoot "/www/domain-8080" </VirtualHost> <VirtualHost 172.20.30.40:80> ServerName www.example.org DocumentRoot "/www/otherdomain-80" </VirtualHost> <VirtualHost 172.20.30.40:8080> ServerName www.example.org DocumentRoot "/www/otherdomain-8080" </VirtualHost> ``` IP-based virtual hosting ------------------------ The server has two IP addresses (`172.20.30.40` and `172.20.30.50`) which resolve to the names `www.example.com` and `www.example.org` respectively. ``` Listen 80 <VirtualHost 172.20.30.40> DocumentRoot "/www/example1" ServerName www.example.com </VirtualHost> <VirtualHost 172.20.30.50> DocumentRoot "/www/example2" ServerName www.example.org </VirtualHost> ``` Requests for any address not specified in one of the `<VirtualHost>` directives (such as `localhost`, for example) will go to the main server, if there is one. Mixed port-based and ip-based virtual hosts ------------------------------------------- The server machine has two IP addresses (`172.20.30.40` and `172.20.30.50`) which resolve to the names `www.example.com` and `www.example.org` respectively. In each case, we want to run hosts on ports 80 and 8080. ``` Listen 172.20.30.40:80 Listen 172.20.30.40:8080 Listen 172.20.30.50:80 Listen 172.20.30.50:8080 <VirtualHost 172.20.30.40:80> DocumentRoot "/www/example1-80" ServerName www.example.com </VirtualHost> <VirtualHost 172.20.30.40:8080> DocumentRoot "/www/example1-8080" ServerName www.example.com </VirtualHost> <VirtualHost 172.20.30.50:80> DocumentRoot "/www/example2-80" ServerName www.example.org </VirtualHost> <VirtualHost 172.20.30.50:8080> DocumentRoot "/www/example2-8080" ServerName www.example.org </VirtualHost> ``` Mixed name-based and IP-based vhosts ------------------------------------ Any address mentioned in the argument to a virtualhost that never appears in another virtual host is a strictly IP-based virtual host. ``` Listen 80 <VirtualHost 172.20.30.40> DocumentRoot "/www/example1" ServerName www.example.com </VirtualHost> <VirtualHost 172.20.30.40> DocumentRoot "/www/example2" ServerName www.example.org </VirtualHost> <VirtualHost 172.20.30.40> DocumentRoot "/www/example3" ServerName www.example.net </VirtualHost> # IP-based <VirtualHost 172.20.30.50> DocumentRoot "/www/example4" ServerName www.example.edu </VirtualHost> <VirtualHost 172.20.30.60> DocumentRoot "/www/example5" ServerName www.example.gov </VirtualHost> ``` Using `Virtual_host` and mod\_proxy together -------------------------------------------- The following example allows a front-end machine to proxy a virtual host through to a server running on another machine. In the example, a virtual host of the same name is configured on a machine at `192.168.111.2`. The `[ProxyPreserveHost On](../mod/mod_proxy#proxypreservehost)` directive is used so that the desired hostname is passed through, in case we are proxying multiple hostnames to a single machine. ``` <VirtualHost *:*> ProxyPreserveHost On ProxyPass "/" "http://192.168.111.2/" ProxyPassReverse "/" "http://192.168.111.2/" ServerName hostname.example.com </VirtualHost> ``` Using `_default_` vhosts ------------------------ ### `_default_` vhosts for all ports Catching *every* request to any unspecified IP address and port, *i.e.*, an address/port combination that is not used for any other virtual host. ``` <VirtualHost _default_:*> DocumentRoot "/www/default" </VirtualHost> ``` Using such a default vhost with a wildcard port effectively prevents any request going to the main server. A default vhost never serves a request that was sent to an address/port that is used for name-based vhosts. If the request contained an unknown or no `Host:` header it is always served from the primary name-based vhost (the vhost for that address/port appearing first in the configuration file). You can use `[AliasMatch](../mod/mod_alias#aliasmatch)` or `[RewriteRule](../mod/mod_rewrite#rewriterule)` to rewrite any request to a single information page (or script). ### `_default_` vhosts for different ports Same as setup 1, but the server listens on several ports and we want to use a second `_default_` vhost for port 80. ``` <VirtualHost _default_:80> DocumentRoot "/www/default80" # ... </VirtualHost> <VirtualHost _default_:*> DocumentRoot "/www/default" # ... </VirtualHost> ``` The default vhost for port 80 (which *must* appear before any default vhost with a wildcard port) catches all requests that were sent to an unspecified IP address. The main server is never used to serve a request. ### `_default_` vhosts for one port We want to have a default vhost for port 80, but no other default vhosts. ``` <VirtualHost _default_:80> DocumentRoot "/www/default" ... </VirtualHost> ``` A request to an unspecified address on port 80 is served from the default vhost. Any other request to an unspecified address and port is served from the main server. Any use of `*` in a virtual host declaration will have higher precedence than `_default_`. Migrating a name-based vhost to an IP-based vhost ------------------------------------------------- The name-based vhost with the hostname `www.example.org` (from our [name-based](#name) example, setup 2) should get its own IP address. To avoid problems with name servers or proxies who cached the old IP address for the name-based vhost we want to provide both variants during a migration phase. The solution is easy, because we can simply add the new IP address (`172.20.30.50`) to the `VirtualHost` directive. ``` Listen 80 ServerName www.example.com DocumentRoot "/www/example1" <VirtualHost 172.20.30.40 172.20.30.50> DocumentRoot "/www/example2" ServerName www.example.org # ... </VirtualHost> <VirtualHost 172.20.30.40> DocumentRoot "/www/example3" ServerName www.example.net ServerAlias *.example.net # ... </VirtualHost> ``` The vhost can now be accessed through the new address (as an IP-based vhost) and through the old address (as a name-based vhost). Using the `ServerPath` directive -------------------------------- We have a server with two name-based vhosts. In order to match the correct virtual host a client must send the correct `Host:` header. Old HTTP/1.0 clients do not send such a header and Apache has no clue what vhost the client tried to reach (and serves the request from the primary vhost). To provide as much backward compatibility as possible we create a primary vhost which returns a single page containing links with an URL prefix to the name-based virtual hosts. ``` <VirtualHost 172.20.30.40> # primary vhost DocumentRoot "/www/subdomain" RewriteEngine On RewriteRule "." "/www/subdomain/index.html" # ... </VirtualHost> <VirtualHost 172.20.30.40> DocumentRoot "/www/subdomain/sub1" ServerName www.sub1.domain.tld ServerPath "/sub1/" RewriteEngine On RewriteRule "^(/sub1/.*)" "/www/subdomain$1" # ... </VirtualHost> <VirtualHost 172.20.30.40> DocumentRoot "/www/subdomain/sub2" ServerName www.sub2.domain.tld ServerPath "/sub2/" RewriteEngine On RewriteRule "^(/sub2/.*)" "/www/subdomain$1" # ... </VirtualHost> ``` Due to the `[ServerPath](../mod/core#serverpath)` directive a request to the URL `http://www.sub1.domain.tld/sub1/` is *always* served from the sub1-vhost. A request to the URL `http://www.sub1.domain.tld/` is only served from the sub1-vhost if the client sent a correct `Host:` header. If no `Host:` header is sent the client gets the information page from the primary host. Please note that there is one oddity: A request to `http://www.sub2.domain.tld/sub1/` is also served from the sub1-vhost if the client sent no `Host:` header. The `[RewriteRule](../mod/mod_rewrite#rewriterule)` directives are used to make sure that a client which sent a correct `Host:` header can use both URL variants, *i.e.*, with or without URL prefix.
programming_docs
apache_http_server File Descriptor Limits File Descriptor Limits ====================== When using a large number of Virtual Hosts, Apache may run out of available file descriptors (sometimes called file handles) if each Virtual Host specifies different log files. The total number of file descriptors used by Apache is one for each distinct error log file, one for every other log file directive, plus 10-20 for internal use. Unix operating systems limit the number of file descriptors that may be used by a process; the limit is typically 64, and may usually be increased up to a large hard-limit. Although Apache attempts to increase the limit as required, this may not work if: 1. Your system does not provide the `setrlimit()` system call. 2. The `setrlimit(RLIMIT_NOFILE)` call does not function on your system (such as Solaris 2.3) 3. The number of file descriptors required exceeds the hard limit. 4. Your system imposes other limits on file descriptors, such as a limit on stdio streams only using file descriptors below 256. (Solaris 2) In the event of problems you can: * Reduce the number of log files; don't specify log files in the `[<VirtualHost>](../mod/core#virtualhost)` sections, but only log to the main log files. (See [Splitting up your log files](#splitlogs), below, for more information on doing this.) * If your system falls into 1 or 2 (above), then increase the file descriptor limit before starting Apache, using a script like: ``` #!/bin/sh ulimit -S -n 100 exec httpd ``` Splitting up your log files --------------------------- If you want to log multiple virtual hosts to the same log file, you may want to split up the log files afterwards in order to run statistical analysis of the various virtual hosts. This can be accomplished in the following manner. First, you will need to add the virtual host information to the log entries. This can be done using the `[LogFormat](../mod/mod_log_config#logformat)` directive, and the `%v` variable. Add this to the beginning of your log format string: ``` LogFormat "%v %h %l %u %t \"%r\" %>s %b" vhost CustomLog logs/multiple_vhost_log vhost ``` This will create a log file in the common log format, but with the canonical virtual host (whatever appears in the `[ServerName](../mod/core#servername)` directive) prepended to each line. (See `[mod\_log\_config](../mod/mod_log_config)` for more about customizing your log files.) When you wish to split your log file into its component parts (one file per virtual host), you can use the program `[split-logfile](https://httpd.apache.org/docs/2.4/en/programs/other.html)` to accomplish this. You'll find this program in the `support` directory of the Apache distribution. Run this program with the command: ``` split-logfile < /logs/multiple_vhost_log ``` This program, when run with the name of your vhost log file, will generate one file for each virtual host that appears in your log file. Each file will be called `hostname.log`. bash Installation Names Installation Names ================== By default, ‘`make install`’ will install into `/usr/local/bin`, `/usr/local/man`, etc.; that is, the *installation prefix* defaults to `/usr/local`. You can specify an installation prefix other than `/usr/local` by giving `configure` the option `--prefix=PATH`, or by specifying a value for the `prefix` ‘`make`’ variable when running ‘`make install`’ (e.g., ‘`make install prefix=PATH`’). The `prefix` variable provides a default for `exec_prefix` and other variables used when installing bash. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you give `configure` the option `--exec-prefix=PATH`, ‘`make install`’ will use PATH as the prefix for installing programs and libraries. Documentation and other data files will still use the regular prefix. If you would like to change the installation locations for a single run, you can specify these variables as arguments to `make`: ‘`make install exec\_prefix=/`’ will install `bash` and `bashbug` into `/bin` instead of the default `/usr/local/bin`. If you want to see the files bash will install and where it will install them without changing anything on your system, specify the variable `DESTDIR` as an argument to `make`. Its value should be the absolute directory path you’d like to use as the root of your sample installation tree. For example, ``` mkdir /fs1/bash-install make install DESTDIR=/fs1/bash-install ``` will install `bash` into `/fs1/bash-install/usr/local/bin/bash`, the documentation into directories within `/fs1/bash-install/usr/local/share`, the example loadable builtins into `/fs1/bash-install/usr/local/lib/bash`, and so on. You can use the usual `exec_prefix` and `prefix` variables to alter the directory paths beneath the value of `DESTDIR`. The GNU Makefile standards provide a more complete description of these variables and their effects. bash Command Search and Execution Command Search and Execution ============================ After a command has been split into words, if it results in a simple command and an optional list of arguments, the following actions are taken. 1. If the command name contains no slashes, the shell attempts to locate it. If there exists a shell function by that name, that function is invoked as described in [Shell Functions](shell-functions). 2. If the name does not match a function, the shell searches for it in the list of shell builtins. If a match is found, that builtin is invoked. 3. If the name is neither a shell function nor a builtin, and contains no slashes, Bash searches each element of `$PATH` for a directory containing an executable file by that name. Bash uses a hash table to remember the full pathnames of executable files to avoid multiple `PATH` searches (see the description of `hash` in [Bourne Shell Builtins](bourne-shell-builtins)). A full search of the directories in `$PATH` is performed only if the command is not found in the hash table. If the search is unsuccessful, the shell searches for a defined shell function named `command_not_found_handle`. If that function exists, it is invoked in a separate execution environment with the original command and the original command’s arguments as its arguments, and the function’s exit status becomes the exit status of that subshell. If that function is not defined, the shell prints an error message and returns an exit status of 127. 4. If the search is successful, or if the command name contains one or more slashes, the shell executes the named program in a separate execution environment. Argument 0 is set to the name given, and the remaining arguments to the command are set to the arguments supplied, if any. 5. If this execution fails because the file is not in executable format, and the file is not a directory, it is assumed to be a *shell script* and the shell executes it as described in [Shell Scripts](shell-scripts). 6. If the command was not begun asynchronously, the shell waits for the command to complete and collects its exit status. bash Filename Expansion Filename Expansion ================== After word splitting, unless the `-f` option has been set (see [The Set Builtin](the-set-builtin)), Bash scans each word for the characters ‘`\*`’, ‘`?`’, and ‘`[`’. If one of these characters appears, and is not quoted, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of filenames matching the pattern (see [Pattern Matching](pattern-matching)). If no matching filenames are found, and the shell option `nullglob` is disabled, the word is left unchanged. If the `nullglob` option is set, and no matches are found, the word is removed. If the `failglob` shell option is set, and no matches are found, an error message is printed and the command is not executed. If the shell option `nocaseglob` is enabled, the match is performed without regard to the case of alphabetic characters. When a pattern is used for filename expansion, the character ‘`.`’ at the start of a filename or immediately following a slash must be matched explicitly, unless the shell option `dotglob` is set. In order to match the filenames ‘`.`’ and ‘`..`’, the pattern must begin with ‘`.`’ (for example, ‘`.?`’), even if `dotglob` is set. If the `globskipdots` shell option is enabled, the filenames ‘`.`’ and ‘`..`’ are never matched, even if the pattern begins with a ‘`.`’. When not matching filenames, the ‘`.`’ character is not treated specially. When matching a filename, the slash character must always be matched explicitly by a slash in the pattern, but in other matching contexts it can be matched by a special pattern character as described below (see [Pattern Matching](pattern-matching)). See the description of `shopt` in [The Shopt Builtin](the-shopt-builtin), for a description of the `nocaseglob`, `nullglob`, `globskipdots`, `failglob`, and `dotglob` options. The `GLOBIGNORE` shell variable may be used to restrict the set of file names matching a pattern. If `GLOBIGNORE` is set, each matching file name that also matches one of the patterns in `GLOBIGNORE` is removed from the list of matches. If the `nocaseglob` option is set, the matching against the patterns in `GLOBIGNORE` is performed without regard to case. The filenames `.` and `..` are always ignored when `GLOBIGNORE` is set and not null. However, setting `GLOBIGNORE` to a non-null value has the effect of enabling the `dotglob` shell option, so all other filenames beginning with a ‘`.`’ will match. To get the old behavior of ignoring filenames beginning with a ‘`.`’, make ‘`.\*`’ one of the patterns in `GLOBIGNORE`. The `dotglob` option is disabled when `GLOBIGNORE` is unset. * [Pattern Matching](pattern-matching) bash Readline Init File Readline Init File ================== Although the Readline library comes with a set of Emacs-like keybindings installed by default, it is possible to use a different set of keybindings. Any user can customize programs that use Readline by putting commands in an *inputrc* file, conventionally in their home directory. The name of this file is taken from the value of the shell variable `INPUTRC`. If that variable is unset, the default is `~/.inputrc`. If that file does not exist or cannot be read, the ultimate default is `/etc/inputrc`. The `bind` builtin command can also be used to set Readline keybindings and variables. See [Bash Builtin Commands](bash-builtins). When a program which uses the Readline library starts up, the init file is read, and the key bindings are set. In addition, the `C-x C-r` command re-reads this init file, thus incorporating any changes that you might have made to it. * [Readline Init File Syntax](readline-init-file-syntax) * [Conditional Init Constructs](conditional-init-constructs) * [Sample Init File](sample-init-file) bash Modifying Shell Behavior Modifying Shell Behavior ======================== * [The Set Builtin](the-set-builtin) * [The Shopt Builtin](the-shopt-builtin) bash Shell Arithmetic Shell Arithmetic ================ The shell allows arithmetic expressions to be evaluated, as one of the shell expansions or by using the `((` compound command, the `let` builtin, or the `-i` option to the `declare` builtin. Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error. The operators and their precedence, associativity, and values are the same as in the C language. The following list of operators is grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence. `id++ id--` variable post-increment and post-decrement `++id --id` variable pre-increment and pre-decrement `- +` unary minus and plus `! ~` logical and bitwise negation `**` exponentiation `* / %` multiplication, division, remainder `+ -` addition, subtraction `<< >>` left and right bitwise shifts `<= >= < >` comparison `== !=` equality and inequality `&` bitwise AND `^` bitwise exclusive OR `|` bitwise OR `&&` logical AND `||` logical OR `expr ? expr : expr` conditional operator `= *= /= %= += -= <<= >>= &= ^= |=` assignment `expr1 , expr2` comma Shell variables are allowed as operands; parameter expansion is performed before the expression is evaluated. Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax. A shell variable that is null or unset evaluates to 0 when referenced by name without using the parameter expansion syntax. The value of a variable is evaluated as an arithmetic expression when it is referenced, or when a variable which has been given the `integer` attribute using ‘`declare -i`’ is assigned a value. A null value evaluates to 0. A shell variable need not have its `integer` attribute turned on to be used in an expression. Integer constants follow the C language definition, without suffixes or character constants. Constants with a leading 0 are interpreted as octal numbers. A leading ‘`0x`’ or ‘`0X`’ denotes hexadecimal. Otherwise, numbers take the form [base`#`]n, where the optional base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base`#` is omitted, then base 10 is used. When specifying n, if a non-digit is required, the digits greater than 9 are represented by the lowercase letters, the uppercase letters, ‘`@`’, and ‘`\_`’, in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35. Operators are evaluated in order of precedence. Sub-expressions in parentheses are evaluated first and may override the precedence rules above. bash Job Control Builtins Job Control Builtins ==================== `bg` ``` bg [jobspec …] ``` Resume each suspended job jobspec in the background, as if it had been started with ‘`&`’. If jobspec is not supplied, the current job is used. The return status is zero unless it is run when job control is not enabled, or, when run with job control enabled, any jobspec was not found or specifies a job that was started without job control. `fg` ``` fg [jobspec] ``` Resume the job jobspec in the foreground and make it the current job. If jobspec is not supplied, the current job is used. The return status is that of the command placed into the foreground, or non-zero if run when job control is disabled or, when run with job control enabled, jobspec does not specify a valid job or jobspec specifies a job that was started without job control. `jobs` ``` jobs [-lnprs] [jobspec] jobs -x command [arguments] ``` The first form lists the active jobs. The options have the following meanings: `-l` List process IDs in addition to the normal information. `-n` Display information only about jobs that have changed status since the user was last notified of their status. `-p` List only the process ID of the job’s process group leader. `-r` Display only running jobs. `-s` Display only stopped jobs. If jobspec is given, output is restricted to information about that job. If jobspec is not supplied, the status of all jobs is listed. If the `-x` option is supplied, `jobs` replaces any jobspec found in command or arguments with the corresponding process group ID, and executes command, passing it arguments, returning its exit status. `kill` ``` kill [-s sigspec] [-n signum] [-sigspec] jobspec or pid kill -l|-L [exit_status] ``` Send a signal specified by sigspec or signum to the process named by job specification jobspec or process ID pid. sigspec is either a case-insensitive signal name such as `SIGINT` (with or without the `SIG` prefix) or a signal number; signum is a signal number. If sigspec and signum are not present, `SIGTERM` is used. The `-l` option lists the signal names. If any arguments are supplied when `-l` is given, the names of the signals corresponding to the arguments are listed, and the return status is zero. exit\_status is a number specifying a signal number or the exit status of a process terminated by a signal. The `-L` option is equivalent to `-l`. The return status is zero if at least one signal was successfully sent, or non-zero if an error occurs or an invalid option is encountered. `wait` ``` wait [-fn] [-p varname] [jobspec or pid …] ``` Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, `wait` waits for all running background jobs and the last-executed process substitution, if its process id is the same as $!, and the return status is zero. If the `-n` option is supplied, `wait` waits for a single job from the list of pids or jobspecs or, if no arguments are supplied, any job, to complete and returns its exit status. If none of the supplied arguments is a child of the shell, or if no arguments are supplied and the shell has no unwaited-for children, the exit status is 127. If the `-p` option is supplied, the process or job identifier of the job for which the exit status is returned is assigned to the variable varname named by the option argument. The variable will be unset initially, before any assignment. This is useful only when the `-n` option is supplied. Supplying the `-f` option, when job control is enabled, forces `wait` to wait for each pid or jobspec to terminate before returning its status, instead of returning when it changes status. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127. If `wait` is interrupted by a signal, the return status will be greater than 128, as described above (see [Signals](signals)). Otherwise, the return status is the exit status of the last process or job waited for. `disown` ``` disown [-ar] [-h] [jobspec … | pid … ] ``` Without options, remove each jobspec from the table of active jobs. If the `-h` option is given, the job is not removed from the table, but is marked so that `SIGHUP` is not sent to the job if the shell receives a `SIGHUP`. If jobspec is not present, and neither the `-a` nor the `-r` option is supplied, the current job is used. If no jobspec is supplied, the `-a` option means to remove or mark all jobs; the `-r` option without a jobspec argument restricts operation to running jobs. `suspend` ``` suspend [-f] ``` Suspend the execution of this shell until it receives a `SIGCONT` signal. A login shell, or a shell without job control enabled, cannot be suspended; the `-f` option can be used to override this and force the suspension. The return status is 0 unless the shell is a login shell or job control is not enabled and `-f` is not supplied. When job control is not active, the `kill` and `wait` builtins do not accept jobspec arguments. They must be supplied process IDs. bash Appendix D Indexes Appendix D Indexes ================== * [Index of Shell Builtin Commands](builtin-index) * [Index of Shell Reserved Words](reserved-word-index) * [Parameter and Variable Index](variable-index) * [Function Index](function-index) * [Concept Index](concept-index) bash Shell Scripts Shell Scripts ============= A shell script is a text file containing shell commands. When such a file is used as the first non-option argument when invoking Bash, and neither the `-c` nor `-s` option is supplied (see [Invoking Bash](invoking-bash)), Bash reads and executes commands from the file, then exits. This mode of operation creates a non-interactive shell. The shell first searches for the file in the current directory, and looks in the directories in `$PATH` if not found there. When Bash runs a shell script, it sets the special parameter `0` to the name of the file, rather than the name of the shell, and the positional parameters are set to the remaining arguments, if any are given. If no additional arguments are supplied, the positional parameters are unset. A shell script may be made executable by using the `chmod` command to turn on the execute bit. When Bash finds such a file while searching the `$PATH` for a command, it creates a new instance of itself to execute it. In other words, executing ``` filename arguments ``` is equivalent to executing ``` bash filename arguments ``` if `filename` is an executable shell script. This subshell reinitializes itself, so that the effect is as if a new shell had been invoked to interpret the script, with the exception that the locations of commands remembered by the parent (see the description of `hash` in [Bourne Shell Builtins](bourne-shell-builtins)) are retained by the child. Most versions of Unix make this a part of the operating system’s command execution mechanism. If the first line of a script begins with the two characters ‘`#!`’, the remainder of the line specifies an interpreter for the program and, depending on the operating system, one or more optional arguments for that interpreter. Thus, you can specify Bash, `awk`, Perl, or some other interpreter and write the rest of the script file in that language. The arguments to the interpreter consist of one or more optional arguments following the interpreter name on the first line of the script file, followed by the name of the script file, followed by the rest of the arguments supplied to the script. The details of how the interpreter line is split into an interpreter name and a set of arguments vary across systems. Bash will perform this action on operating systems that do not handle it themselves. Note that some older versions of Unix limit the interpreter name and a single argument to a maximum of 32 characters, so it’s not portable to assume that using more than one argument will work. Bash scripts often begin with `#! /bin/bash` (assuming that Bash has been installed in `/bin`), since this ensures that Bash will be used to interpret the script, even if it is executed under another shell. It’s a common idiom to use `env` to find `bash` even if it’s been installed in another directory: `#!/usr/bin/env bash` will find the first occurrence of `bash` in `$PATH`.
programming_docs
bash Optional Features Optional Features ================= The Bash `configure` has a number of `--enable-feature` options, where feature indicates an optional part of Bash. There are also several `--with-package` options, where package is something like ‘`bash-malloc`’ or ‘`purify`’. To turn off the default use of a package, use `--without-package`. To configure Bash without a feature that is enabled by default, use `--disable-feature`. Here is a complete list of the `--enable-` and `--with-` options that the Bash `configure` recognizes. `--with-afs` Define if you are using the Andrew File System from Transarc. `--with-bash-malloc` Use the Bash version of `malloc` in the directory `lib/malloc`. This is not the same `malloc` that appears in GNU libc, but an older version originally derived from the 4.2 BSD `malloc`. This `malloc` is very fast, but wastes some space on each allocation. This option is enabled by default. The `NOTES` file contains a list of systems for which this should be turned off, and `configure` disables this option automatically for a number of systems. `--with-curses` Use the curses library instead of the termcap library. This should be supplied if your system has an inadequate or incomplete termcap database. `--with-gnu-malloc` A synonym for `--with-bash-malloc`. `--with-installed-readline[=PREFIX]` Define this to make Bash link with a locally-installed version of Readline rather than the version in `lib/readline`. This works only with Readline 5.0 and later versions. If PREFIX is `yes` or not supplied, `configure` uses the values of the make variables `includedir` and `libdir`, which are subdirectories of `prefix` by default, to find the installed version of Readline if it is not in the standard system include and library directories. If PREFIX is `no`, Bash links with the version in `lib/readline`. If PREFIX is set to any other value, `configure` treats it as a directory pathname and looks for the installed version of Readline in subdirectories of that directory (include files in PREFIX/`include` and the library in PREFIX/`lib`). `--with-libintl-prefix[=PREFIX]` Define this to make Bash link with a locally-installed version of the libintl library instead of the version in `lib/intl`. `--with-libiconv-prefix[=PREFIX]` Define this to make Bash look for libiconv in PREFIX instead of the standard system locations. There is no version included with Bash. `--enable-minimal-config` This produces a shell with minimal features, close to the historical Bourne shell. There are several `--enable-` options that alter how Bash is compiled, linked, and installed, rather than changing run-time features. `--enable-largefile` Enable support for [large files](http://www.unix.org/version2/whatsnew/lfs20mar.html) if the operating system requires special compiler options to build programs which can access large files. This is enabled by default, if the operating system provides large file support. `--enable-profiling` This builds a Bash binary that produces profiling information to be processed by `gprof` each time it is executed. `--enable-separate-helpfiles` Use external files for the documentation displayed by the `help` builtin instead of storing the text internally. `--enable-static-link` This causes Bash to be linked statically, if `gcc` is being used. This could be used to build a version to use as root’s shell. The ‘`minimal-config`’ option can be used to disable all of the following options, but it is processed first, so individual options may be enabled using ‘`enable-feature`’. All of the following options except for ‘`alt-array-implementation`’, ‘`disabled-builtins`’, ‘`direxpand-default`’, ‘`strict-posix-default`’, and ‘`xpg-echo-default`’ are enabled by default, unless the operating system does not provide the necessary support. `--enable-alias` Allow alias expansion and include the `alias` and `unalias` builtins (see [Aliases](aliases)). `--enable-alt-array-implementation` This builds bash using an alternate implementation of arrays (see [Arrays](arrays)) that provides faster access at the expense of using more memory (sometimes many times more, depending on how sparse an array is). `--enable-arith-for-command` Include support for the alternate form of the `for` command that behaves like the C language `for` statement (see [Looping Constructs](looping-constructs)). `--enable-array-variables` Include support for one-dimensional array shell variables (see [Arrays](arrays)). `--enable-bang-history` Include support for `csh`-like history substitution (see [History Expansion](history-interaction)). `--enable-brace-expansion` Include `csh`-like brace expansion ( `b{a,b}c` → `bac bbc` ). See [Brace Expansion](brace-expansion), for a complete description. `--enable-casemod-attributes` Include support for case-modifying attributes in the `declare` builtin and assignment statements. Variables with the `uppercase` attribute, for example, will have their values converted to uppercase upon assignment. `--enable-casemod-expansion` Include support for case-modifying word expansions. `--enable-command-timing` Include support for recognizing `time` as a reserved word and for displaying timing statistics for the pipeline following `time` (see [Pipelines](pipelines)). This allows pipelines as well as shell builtins and functions to be timed. `--enable-cond-command` Include support for the `[[` conditional command. (see [Conditional Constructs](conditional-constructs)). `--enable-cond-regexp` Include support for matching POSIX regular expressions using the ‘`=~`’ binary operator in the `[[` conditional command. (see [Conditional Constructs](conditional-constructs)). `--enable-coprocesses` Include support for coprocesses and the `coproc` reserved word (see [Pipelines](pipelines)). `--enable-debugger` Include support for the bash debugger (distributed separately). `--enable-dev-fd-stat-broken` If calling `stat` on /dev/fd/N returns different results than calling `fstat` on file descriptor N, supply this option to enable a workaround. This has implications for conditional commands that test file attributes. `--enable-direxpand-default` Cause the `direxpand` shell option (see [The Shopt Builtin](the-shopt-builtin)) to be enabled by default when the shell starts. It is normally disabled by default. `--enable-directory-stack` Include support for a `csh`-like directory stack and the `pushd`, `popd`, and `dirs` builtins (see [The Directory Stack](the-directory-stack)). `--enable-disabled-builtins` Allow builtin commands to be invoked via ‘`builtin xxx`’ even after `xxx` has been disabled using ‘`enable -n xxx`’. See [Bash Builtin Commands](bash-builtins), for details of the `builtin` and `enable` builtin commands. `--enable-dparen-arithmetic` Include support for the `((…))` command (see [Conditional Constructs](conditional-constructs)). `--enable-extended-glob` Include support for the extended pattern matching features described above under [Pattern Matching](pattern-matching). `--enable-extended-glob-default` Set the default value of the `extglob` shell option described above under [The Shopt Builtin](the-shopt-builtin) to be enabled. `--enable-function-import` Include support for importing function definitions exported by another instance of the shell from the environment. This option is enabled by default. `--enable-glob-asciirange-default` Set the default value of the `globasciiranges` shell option described above under [The Shopt Builtin](the-shopt-builtin) to be enabled. This controls the behavior of character ranges when used in pattern matching bracket expressions. `--enable-help-builtin` Include the `help` builtin, which displays help on shell builtins and variables (see [Bash Builtin Commands](bash-builtins)). `--enable-history` Include command history and the `fc` and `history` builtin commands (see [Bash History Facilities](bash-history-facilities)). `--enable-job-control` This enables the job control features (see [Job Control](job-control)), if the operating system supports them. `--enable-multibyte` This enables support for multibyte characters if the operating system provides the necessary support. `--enable-net-redirections` This enables the special handling of filenames of the form `/dev/tcp/host/port` and `/dev/udp/host/port` when used in redirections (see [Redirections](redirections)). `--enable-process-substitution` This enables process substitution (see [Process Substitution](process-substitution)) if the operating system provides the necessary support. `--enable-progcomp` Enable the programmable completion facilities (see [Programmable Completion](programmable-completion)). If Readline is not enabled, this option has no effect. `--enable-prompt-string-decoding` Turn on the interpretation of a number of backslash-escaped characters in the `$PS0`, `$PS1`, `$PS2`, and `$PS4` prompt strings. See [Controlling the Prompt](controlling-the-prompt), for a complete list of prompt string escape sequences. `--enable-readline` Include support for command-line editing and history with the Bash version of the Readline library (see [Command Line Editing](command-line-editing)). `--enable-restricted` Include support for a *restricted shell*. If this is enabled, Bash, when called as `rbash`, enters a restricted mode. See [The Restricted Shell](the-restricted-shell), for a description of restricted mode. `--enable-select` Include the `select` compound command, which allows the generation of simple menus (see [Conditional Constructs](conditional-constructs)). `--enable-single-help-strings` Store the text displayed by the `help` builtin as a single string for each help topic. This aids in translating the text to different languages. You may need to disable this if your compiler cannot handle very long string literals. `--enable-strict-posix-default` Make Bash POSIX-conformant by default (see [Bash POSIX Mode](bash-posix-mode)). `--enable-translatable-strings` Enable support for `$"string"` translatable strings (see [Locale-Specific Translation](locale-translation)). `--enable-usg-echo-default` A synonym for `--enable-xpg-echo-default`. `--enable-xpg-echo-default` Make the `echo` builtin expand backslash-escaped characters by default, without requiring the `-e` option. This sets the default value of the `xpg_echo` shell option to `on`, which makes the Bash `echo` behave more like the version specified in the Single Unix Specification, version 3. See [Bash Builtin Commands](bash-builtins), for a description of the escape sequences that `echo` recognizes. The file `config-top.h` contains C Preprocessor ‘`#define`’ statements for options which are not settable from `configure`. Some of these are not meant to be changed; beware of the consequences if you do. Read the comments associated with each definition for more information about its effect. bash Conditional Init Constructs Conditional Init Constructs =========================== Readline implements a facility similar in spirit to the conditional compilation features of the C preprocessor which allows key bindings and variable settings to be performed as the result of tests. There are four parser directives used. `$if` The `$if` construct allows bindings to be made based on the editing mode, the terminal being used, or the application using Readline. The text of the test, after any comparison operator, extends to the end of the line; unless otherwise noted, no characters are required to isolate it. `mode` The `mode=` form of the `$if` directive is used to test whether Readline is in `emacs` or `vi` mode. This may be used in conjunction with the ‘`set keymap`’ command, for instance, to set bindings in the `emacs-standard` and `emacs-ctlx` keymaps only if Readline is starting out in `emacs` mode. `term` The `term=` form may be used to include terminal-specific key bindings, perhaps to bind the key sequences output by the terminal’s function keys. The word on the right side of the ‘`=`’ is tested against both the full name of the terminal and the portion of the terminal name before the first ‘`-`’. This allows `sun` to match both `sun` and `sun-cmd`, for instance. `version` The `version` test may be used to perform comparisons against specific Readline versions. The `version` expands to the current Readline version. The set of comparison operators includes ‘`=`’ (and ‘`==`’), ‘`!=`’, ‘`<=`’, ‘`>=`’, ‘`<`’, and ‘`>`’. The version number supplied on the right side of the operator consists of a major version number, an optional decimal point, and an optional minor version (e.g., ‘`7.1`’). If the minor version is omitted, it is assumed to be ‘`0`’. The operator may be separated from the string `version` and from the version number argument by whitespace. The following example sets a variable if the Readline version being used is 7.0 or newer: ``` $if version >= 7.0 set show-mode-in-prompt on $endif ``` `application` The application construct is used to include application-specific settings. Each program using the Readline library sets the application name, and you can test for a particular value. This could be used to bind key sequences to functions useful for a specific program. For instance, the following command adds a key sequence that quotes the current or previous word in Bash: ``` $if Bash # Quote the current or previous word "\C-xq": "\eb\"\ef\"" $endif ``` `variable` The variable construct provides simple equality tests for Readline variables and values. The permitted comparison operators are ‘`=`’, ‘`==`’, and ‘`!=`’. The variable name must be separated from the comparison operator by whitespace; the operator may be separated from the value on the right hand side by whitespace. Both string and boolean variables may be tested. Boolean variables must be tested against the values on and off. The following example is equivalent to the `mode=emacs` test described above: ``` $if editing-mode == emacs set show-mode-in-prompt on $endif ``` `$endif` This command, as seen in the previous example, terminates an `$if` command. `$else` Commands in this branch of the `$if` directive are executed if the test fails. `$include` This directive takes a single filename as an argument and reads commands and bindings from that file. For example, the following directive reads from `/etc/inputrc`: ``` $include /etc/inputrc ``` bash Bash Conditional Expressions Bash Conditional Expressions ============================ Conditional expressions are used by the `[[` compound command (see [Conditional Constructs](conditional-constructs)) and the `test` and `[` builtin commands (see [Bourne Shell Builtins](bourne-shell-builtins)). The `test` and `[` commands determine their behavior based on the number of arguments; see the descriptions of those commands for any other command-specific actions. Expressions may be unary or binary, and are formed from the following primaries. Unary expressions are often used to examine the status of a file. There are string operators and numeric comparison operators as well. Bash handles several filenames specially when they are used in expressions. If the operating system on which Bash is running provides these special files, Bash will use them; otherwise it will emulate them internally with this behavior: If the file argument to one of the primaries is of the form `/dev/fd/N`, then file descriptor N is checked. If the file argument to one of the primaries is one of `/dev/stdin`, `/dev/stdout`, or `/dev/stderr`, file descriptor 0, 1, or 2, respectively, is checked. When used with `[[`, the ‘`<`’ and ‘`>`’ operators sort lexicographically using the current locale. The `test` command uses ASCII ordering. Unless otherwise specified, primaries that operate on files follow symbolic links and operate on the target of the link, rather than the link itself. `-a file` True if file exists. `-b file` True if file exists and is a block special file. `-c file` True if file exists and is a character special file. `-d file` True if file exists and is a directory. `-e file` True if file exists. `-f file` True if file exists and is a regular file. `-g file` True if file exists and its set-group-id bit is set. `-h file` True if file exists and is a symbolic link. `-k file` True if file exists and its "sticky" bit is set. `-p file` True if file exists and is a named pipe (FIFO). `-r file` True if file exists and is readable. `-s file` True if file exists and has a size greater than zero. `-t fd` True if file descriptor fd is open and refers to a terminal. `-u file` True if file exists and its set-user-id bit is set. `-w file` True if file exists and is writable. `-x file` True if file exists and is executable. `-G file` True if file exists and is owned by the effective group id. `-L file` True if file exists and is a symbolic link. `-N file` True if file exists and has been modified since it was last read. `-O file` True if file exists and is owned by the effective user id. `-S file` True if file exists and is a socket. `file1 -ef file2` True if file1 and file2 refer to the same device and inode numbers. `file1 -nt file2` True if file1 is newer (according to modification date) than file2, or if file1 exists and file2 does not. `file1 -ot file2` True if file1 is older than file2, or if file2 exists and file1 does not. `-o optname` True if the shell option optname is enabled. The list of options appears in the description of the `-o` option to the `set` builtin (see [The Set Builtin](the-set-builtin)). `-v varname` True if the shell variable varname is set (has been assigned a value). `-R varname` True if the shell variable varname is set and is a name reference. `-z string` True if the length of string is zero. `-n string` `string` True if the length of string is non-zero. `string1 == string2` `string1 = string2` True if the strings are equal. When used with the `[[` command, this performs pattern matching as described above (see [Conditional Constructs](conditional-constructs)). ‘`=`’ should be used with the `test` command for POSIX conformance. `string1 != string2` True if the strings are not equal. `string1 < string2` True if string1 sorts before string2 lexicographically. `string1 > string2` True if string1 sorts after string2 lexicographically. `arg1 OP arg2` `OP` is one of ‘`-eq`’, ‘`-ne`’, ‘`-lt`’, ‘`-le`’, ‘`-gt`’, or ‘`-ge`’. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 may be positive or negative integers. When used with the `[[` command, Arg1 and Arg2 are evaluated as arithmetic expressions (see [Shell Arithmetic](shell-arithmetic)). bash Command Substitution Command Substitution ==================== Command substitution allows the output of a command to replace the command itself. Command substitution occurs when a command is enclosed as follows: ``` $(command) ``` or ``` `command` ``` Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution `$(cat file)` can be replaced by the equivalent but faster `$(< file)`. When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by ‘`$`’, ‘```’, or ‘`\`’. The first backquote not preceded by a backslash terminates the command substitution. When using the `$(command)` form, all characters between the parentheses make up the command; none are treated specially. Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes. If the substitution appears within double quotes, word splitting and filename expansion are not performed on the results.
programming_docs
bash Job Control Basics Job Control Basics ================== Job control refers to the ability to selectively stop (suspend) the execution of processes and continue (resume) their execution at a later point. A user typically employs this facility via an interactive interface supplied jointly by the operating system kernel’s terminal driver and Bash. The shell associates a job with each pipeline. It keeps a table of currently executing jobs, which may be listed with the `jobs` command. When Bash starts a job asynchronously, it prints a line that looks like: ``` [1] 25647 ``` indicating that this job is job number 1 and that the process ID of the last process in the pipeline associated with this job is 25647. All of the processes in a single pipeline are members of the same job. Bash uses the job abstraction as the basis for job control. To facilitate the implementation of the user interface to job control, the operating system maintains the notion of a current terminal process group ID. Members of this process group (processes whose process group ID is equal to the current terminal process group ID) receive keyboard-generated signals such as `SIGINT`. These processes are said to be in the foreground. Background processes are those whose process group ID differs from the terminal’s; such processes are immune to keyboard-generated signals. Only foreground processes are allowed to read from or, if the user so specifies with `stty tostop`, write to the terminal. Background processes which attempt to read from (write to when `stty tostop` is in effect) the terminal are sent a `SIGTTIN` (`SIGTTOU`) signal by the kernel’s terminal driver, which, unless caught, suspends the process. If the operating system on which Bash is running supports job control, Bash contains facilities to use it. Typing the *suspend* character (typically ‘`^Z`’, Control-Z) while a process is running causes that process to be stopped and returns control to Bash. Typing the *delayed suspend* character (typically ‘`^Y`’, Control-Y) causes the process to be stopped when it attempts to read input from the terminal, and control to be returned to Bash. The user then manipulates the state of this job, using the `bg` command to continue it in the background, the `fg` command to continue it in the foreground, or the `kill` command to kill it. A ‘`^Z`’ takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded. There are a number of ways to refer to a job in the shell. The character ‘`%`’ introduces a job specification (*jobspec*). Job number `n` may be referred to as ‘`%n`’. The symbols ‘`%%`’ and ‘`%+`’ refer to the shell’s notion of the current job, which is the last job stopped while it was in the foreground or started in the background. A single ‘`%`’ (with no accompanying job specification) also refers to the current job. The previous job may be referenced using ‘`%-`’. If there is only a single job, ‘`%+`’ and ‘`%-`’ can both be used to refer to that job. In output pertaining to jobs (e.g., the output of the `jobs` command), the current job is always flagged with a ‘`+`’, and the previous job with a ‘`-`’. A job may also be referred to using a prefix of the name used to start it, or using a substring that appears in its command line. For example, ‘`%ce`’ refers to a stopped job whose command name begins with ‘`ce`’. Using ‘`%?ce`’, on the other hand, refers to any job containing the string ‘`ce`’ in its command line. If the prefix or substring matches more than one job, Bash reports an error. Simply naming a job can be used to bring it into the foreground: ‘`%1`’ is a synonym for ‘`fg %1`’, bringing job 1 from the background into the foreground. Similarly, ‘`%1 &`’ resumes job 1 in the background, equivalent to ‘`bg %1`’ The shell learns immediately whenever a job changes state. Normally, Bash waits until it is about to print a prompt before reporting changes in a job’s status so as to not interrupt any other output. If the `-b` option to the `set` builtin is enabled, Bash reports such changes immediately (see [The Set Builtin](the-set-builtin)). Any trap on `SIGCHLD` is executed for each child process that exits. If an attempt to exit Bash is made while jobs are stopped, (or running, if the `checkjobs` option is enabled – see [The Shopt Builtin](the-shopt-builtin)), the shell prints a warning message, and if the `checkjobs` option is enabled, lists the jobs and their statuses. The `jobs` command may then be used to inspect their status. If a second attempt to exit is made without an intervening command, Bash does not print another warning, and any stopped jobs are terminated. When the shell is waiting for a job or process using the `wait` builtin, and job control is enabled, `wait` will return when the job changes state. The `-f` option causes `wait` to wait until the job or process terminates before returning. bash Commands For Changing Text Commands For Changing Text ========================== `*end-of-file* (usually C-d)` The character indicating end-of-file as set, for example, by `stty`. If this character is read when there are no characters on the line, and point is at the beginning of the line, Readline interprets it as the end of input and returns EOF. `delete-char (C-d)` Delete the character at point. If this function is bound to the same character as the tty EOF character, as `C-d` commonly is, see above for the effects. `backward-delete-char (Rubout)` Delete the character behind the cursor. A numeric argument means to kill the characters instead of deleting them. `forward-backward-delete-char ()` Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. By default, this is not bound to a key. `quoted-insert (C-q or C-v)` Add the next character typed to the line verbatim. This is how to insert key sequences like `C-q`, for example. `self-insert (a, b, A, 1, !, …)` Insert yourself. `bracketed-paste-begin ()` This function is intended to be bound to the "bracketed paste" escape sequence sent by some terminals, and such a binding is assigned by default. It allows Readline to insert the pasted text as a single unit without treating each character as if it had been read from the keyboard. The characters are inserted as if each one was bound to `self-insert` instead of executing any editing commands. Bracketed paste sets the region (the characters between point and the mark) to the inserted text. It uses the concept of an *active mark*: when the mark is active, Readline redisplay uses the terminal’s standout mode to denote the region. `transpose-chars (C-t)` Drag the character before the cursor forward over the character at the cursor, moving the cursor forward as well. If the insertion point is at the end of the line, then this transposes the last two characters of the line. Negative arguments have no effect. `transpose-words (M-t)` Drag the word before point past the word after point, moving point past that word as well. If the insertion point is at the end of the line, this transposes the last two words on the line. `upcase-word (M-u)` Uppercase the current (or following) word. With a negative argument, uppercase the previous word, but do not move the cursor. `downcase-word (M-l)` Lowercase the current (or following) word. With a negative argument, lowercase the previous word, but do not move the cursor. `capitalize-word (M-c)` Capitalize the current (or following) word. With a negative argument, capitalize the previous word, but do not move the cursor. `overwrite-mode ()` Toggle overwrite mode. With an explicit positive numeric argument, switches to overwrite mode. With an explicit non-positive numeric argument, switches to insert mode. This command affects only `emacs` mode; `vi` mode does overwrite differently. Each call to `readline()` starts in insert mode. In overwrite mode, characters bound to `self-insert` replace the text at point rather than pushing the text to the right. Characters bound to `backward-delete-char` replace the character before point with a space. By default, this command is unbound. bash Environment Environment =========== When a program is invoked it is given an array of strings called the *environment*. This is a list of name-value pairs, of the form `name=value`. Bash provides several ways to manipulate the environment. On invocation, the shell scans its own environment and creates a parameter for each name found, automatically marking it for `export` to child processes. Executed commands inherit the environment. The `export` and ‘`declare -x`’ commands allow parameters and functions to be added to and deleted from the environment. If the value of a parameter in the environment is modified, the new value becomes part of the environment, replacing the old. The environment inherited by any executed command consists of the shell’s initial environment, whose values may be modified in the shell, less any pairs removed by the `unset` and ‘`export -n`’ commands, plus any additions via the `export` and ‘`declare -x`’ commands. The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in [Shell Parameters](shell-parameters). These assignment statements affect only the environment seen by that command. If the `-k` option is set (see [The Set Builtin](the-set-builtin)), then all parameter assignments are placed in the environment for a command, not just those that precede the command name. When Bash invokes an external command, the variable ‘`$\_`’ is set to the full pathname of the command and passed to that command in its environment. bash Index of Shell Builtin Commands Index of Shell Builtin Commands =============================== | | | | --- | --- | | Jump to: | [**.**](#Builtin-Index_bt_symbol-1) [**:**](#Builtin-Index_bt_symbol-2) [**[**](#Builtin-Index_bt_symbol-3) [**A**](#Builtin-Index_bt_letter-A) [**B**](#Builtin-Index_bt_letter-B) [**C**](#Builtin-Index_bt_letter-C) [**D**](#Builtin-Index_bt_letter-D) [**E**](#Builtin-Index_bt_letter-E) [**F**](#Builtin-Index_bt_letter-F) [**G**](#Builtin-Index_bt_letter-G) [**H**](#Builtin-Index_bt_letter-H) [**J**](#Builtin-Index_bt_letter-J) [**K**](#Builtin-Index_bt_letter-K) [**L**](#Builtin-Index_bt_letter-L) [**M**](#Builtin-Index_bt_letter-M) [**P**](#Builtin-Index_bt_letter-P) [**R**](#Builtin-Index_bt_letter-R) [**S**](#Builtin-Index_bt_letter-S) [**T**](#Builtin-Index_bt_letter-T) [**U**](#Builtin-Index_bt_letter-U) [**W**](#Builtin-Index_bt_letter-W) | | | | | | --- | --- | --- | | | Index Entry | Section | | . | | | | | [`.`](bourne-shell-builtins#.) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | : | | | | | [`:`](bourne-shell-builtins#:) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | [ | | | | | [`[`](bourne-shell-builtins#%5B) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | A | | | | | [`alias`](bash-builtins#alias) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | B | | | | | [`bg`](job-control-builtins#bg) | [Job Control Builtins](job-control-builtins#Job%20Control%20Builtins) | | | [`bind`](bash-builtins#bind) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`break`](bourne-shell-builtins#break) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`builtin`](bash-builtins#builtin) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | C | | | | | [`caller`](bash-builtins#caller) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`cd`](bourne-shell-builtins#cd) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`command`](bash-builtins#command) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`compgen`](programmable-completion-builtins#compgen) | [Programmable Completion Builtins](programmable-completion-builtins#Programmable%20Completion%20Builtins) | | | [`complete`](programmable-completion-builtins#complete) | [Programmable Completion Builtins](programmable-completion-builtins#Programmable%20Completion%20Builtins) | | | [`compopt`](programmable-completion-builtins#compopt) | [Programmable Completion Builtins](programmable-completion-builtins#Programmable%20Completion%20Builtins) | | | [`continue`](bourne-shell-builtins#continue) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | D | | | | | [`declare`](bash-builtins#declare) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`dirs`](directory-stack-builtins#dirs) | [Directory Stack Builtins](directory-stack-builtins#Directory%20Stack%20Builtins) | | | [`disown`](job-control-builtins#disown) | [Job Control Builtins](job-control-builtins#Job%20Control%20Builtins) | | E | | | | | [`echo`](bash-builtins#echo) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`enable`](bash-builtins#enable) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`eval`](bourne-shell-builtins#eval) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`exec`](bourne-shell-builtins#exec) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`exit`](bourne-shell-builtins#exit) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`export`](bourne-shell-builtins#export) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | F | | | | | [`fc`](bash-history-builtins#fc) | [Bash History Builtins](bash-history-builtins#Bash%20History%20Builtins) | | | [`fg`](job-control-builtins#fg) | [Job Control Builtins](job-control-builtins#Job%20Control%20Builtins) | | G | | | | | [`getopts`](bourne-shell-builtins#getopts) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | H | | | | | [`hash`](bourne-shell-builtins#hash) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`help`](bash-builtins#help) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`history`](bash-history-builtins#history) | [Bash History Builtins](bash-history-builtins#Bash%20History%20Builtins) | | J | | | | | [`jobs`](job-control-builtins#jobs) | [Job Control Builtins](job-control-builtins#Job%20Control%20Builtins) | | K | | | | | [`kill`](job-control-builtins#kill) | [Job Control Builtins](job-control-builtins#Job%20Control%20Builtins) | | L | | | | | [`let`](bash-builtins#let) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`local`](bash-builtins#local) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`logout`](bash-builtins#logout) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | M | | | | | [`mapfile`](bash-builtins#mapfile) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | P | | | | | [`popd`](directory-stack-builtins#popd) | [Directory Stack Builtins](directory-stack-builtins#Directory%20Stack%20Builtins) | | | [`printf`](bash-builtins#printf) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`pushd`](directory-stack-builtins#pushd) | [Directory Stack Builtins](directory-stack-builtins#Directory%20Stack%20Builtins) | | | [`pwd`](bourne-shell-builtins#pwd) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | R | | | | | [`read`](bash-builtins#read) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`readarray`](bash-builtins#readarray) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`readonly`](bourne-shell-builtins#readonly) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`return`](bourne-shell-builtins#return) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | S | | | | | [`set`](the-set-builtin#set) | [The Set Builtin](the-set-builtin#The%20Set%20Builtin) | | | [`shift`](bourne-shell-builtins#shift) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`shopt`](the-shopt-builtin#shopt) | [The Shopt Builtin](the-shopt-builtin#The%20Shopt%20Builtin) | | | [`source`](bash-builtins#source) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`suspend`](job-control-builtins#suspend) | [Job Control Builtins](job-control-builtins#Job%20Control%20Builtins) | | T | | | | | [`test`](bourne-shell-builtins#test) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`times`](bourne-shell-builtins#times) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`trap`](bourne-shell-builtins#trap) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`type`](bash-builtins#type) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`typeset`](bash-builtins#typeset) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | U | | | | | [`ulimit`](bash-builtins#ulimit) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`umask`](bourne-shell-builtins#umask) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | | [`unalias`](bash-builtins#unalias) | [Bash Builtins](bash-builtins#Bash%20Builtins) | | | [`unset`](bourne-shell-builtins#unset) | [Bourne Shell Builtins](bourne-shell-builtins#Bourne%20Shell%20Builtins) | | W | | | | | [`wait`](job-control-builtins#wait) | [Job Control Builtins](job-control-builtins#Job%20Control%20Builtins) | | | | | --- | --- | | Jump to: | [**.**](#Builtin-Index_bt_symbol-1) [**:**](#Builtin-Index_bt_symbol-2) [**[**](#Builtin-Index_bt_symbol-3) [**A**](#Builtin-Index_bt_letter-A) [**B**](#Builtin-Index_bt_letter-B) [**C**](#Builtin-Index_bt_letter-C) [**D**](#Builtin-Index_bt_letter-D) [**E**](#Builtin-Index_bt_letter-E) [**F**](#Builtin-Index_bt_letter-F) [**G**](#Builtin-Index_bt_letter-G) [**H**](#Builtin-Index_bt_letter-H) [**J**](#Builtin-Index_bt_letter-J) [**K**](#Builtin-Index_bt_letter-K) [**L**](#Builtin-Index_bt_letter-L) [**M**](#Builtin-Index_bt_letter-M) [**P**](#Builtin-Index_bt_letter-P) [**R**](#Builtin-Index_bt_letter-R) [**S**](#Builtin-Index_bt_letter-S) [**T**](#Builtin-Index_bt_letter-T) [**U**](#Builtin-Index_bt_letter-U) [**W**](#Builtin-Index_bt_letter-W) | bash Bash Features Bash Features ============= This text is a brief description of the features that are present in the Bash shell (version 5.2, 19 September 2022). The Bash home page is <http://www.gnu.org/software/bash/>. This is Edition 5.2, last updated 19 September 2022, of The GNU Bash Reference Manual, for `Bash`, Version 5.2. Bash contains features that appear in other popular shells, and some features that only appear in Bash. Some of the shells that Bash has borrowed concepts from are the Bourne Shell (`sh`), the Korn Shell (`ksh`), and the C-shell (`csh` and its successor, `tcsh`). The following menu breaks the features up into categories, noting which features were inspired by other shells and which are specific to Bash. This manual is meant as a brief introduction to features found in Bash. The Bash manual page should be used as the definitive reference on shell behavior. Table of Contents ----------------- * [1 Introduction](introduction) + [1.1 What is Bash?](what-is-bash_003f) + [1.2 What is a shell?](what-is-a-shell_003f) * [2 Definitions](definitions) * [3 Basic Shell Features](basic-shell-features) + [3.1 Shell Syntax](shell-syntax) - [3.1.1 Shell Operation](shell-operation) - [3.1.2 Quoting](quoting) * [3.1.2.1 Escape Character](escape-character) * [3.1.2.2 Single Quotes](single-quotes) * [3.1.2.3 Double Quotes](double-quotes) * [3.1.2.4 ANSI-C Quoting](ansi_002dc-quoting) * [3.1.2.5 Locale-Specific Translation](locale-translation) - [3.1.3 Comments](comments) + [3.2 Shell Commands](shell-commands) - [3.2.1 Reserved Words](reserved-words) - [3.2.2 Simple Commands](simple-commands) - [3.2.3 Pipelines](pipelines) - [3.2.4 Lists of Commands](lists) - [3.2.5 Compound Commands](compound-commands) * [3.2.5.1 Looping Constructs](looping-constructs) * [3.2.5.2 Conditional Constructs](conditional-constructs) * [3.2.5.3 Grouping Commands](command-grouping) - [3.2.6 Coprocesses](coprocesses) - [3.2.7 GNU Parallel](gnu-parallel) + [3.3 Shell Functions](shell-functions) + [3.4 Shell Parameters](shell-parameters) - [3.4.1 Positional Parameters](positional-parameters) - [3.4.2 Special Parameters](special-parameters) + [3.5 Shell Expansions](shell-expansions) - [3.5.1 Brace Expansion](brace-expansion) - [3.5.2 Tilde Expansion](tilde-expansion) - [3.5.3 Shell Parameter Expansion](shell-parameter-expansion) - [3.5.4 Command Substitution](command-substitution) - [3.5.5 Arithmetic Expansion](arithmetic-expansion) - [3.5.6 Process Substitution](process-substitution) - [3.5.7 Word Splitting](word-splitting) - [3.5.8 Filename Expansion](filename-expansion) * [3.5.8.1 Pattern Matching](pattern-matching) - [3.5.9 Quote Removal](quote-removal) + [3.6 Redirections](redirections) - [3.6.1 Redirecting Input](redirections#Redirecting-Input) - [3.6.2 Redirecting Output](redirections#Redirecting-Output) - [3.6.3 Appending Redirected Output](redirections#Appending-Redirected-Output) - [3.6.4 Redirecting Standard Output and Standard Error](redirections#Redirecting-Standard-Output-and-Standard-Error) - [3.6.5 Appending Standard Output and Standard Error](redirections#Appending-Standard-Output-and-Standard-Error) - [3.6.6 Here Documents](redirections#Here-Documents) - [3.6.7 Here Strings](redirections#Here-Strings) - [3.6.8 Duplicating File Descriptors](redirections#Duplicating-File-Descriptors) - [3.6.9 Moving File Descriptors](redirections#Moving-File-Descriptors) - [3.6.10 Opening File Descriptors for Reading and Writing](redirections#Opening-File-Descriptors-for-Reading-and-Writing) + [3.7 Executing Commands](executing-commands) - [3.7.1 Simple Command Expansion](simple-command-expansion) - [3.7.2 Command Search and Execution](command-search-and-execution) - [3.7.3 Command Execution Environment](command-execution-environment) - [3.7.4 Environment](environment) - [3.7.5 Exit Status](exit-status) - [3.7.6 Signals](signals) + [3.8 Shell Scripts](shell-scripts) * [4 Shell Builtin Commands](shell-builtin-commands) + [4.1 Bourne Shell Builtins](bourne-shell-builtins) + [4.2 Bash Builtin Commands](bash-builtins) + [4.3 Modifying Shell Behavior](modifying-shell-behavior) - [4.3.1 The Set Builtin](the-set-builtin) - [4.3.2 The Shopt Builtin](the-shopt-builtin) + [4.4 Special Builtins](special-builtins) * [5 Shell Variables](shell-variables) + [5.1 Bourne Shell Variables](bourne-shell-variables) + [5.2 Bash Variables](bash-variables) * [6 Bash Features](bash-features) + [6.1 Invoking Bash](invoking-bash) + [6.2 Bash Startup Files](bash-startup-files) + [6.3 Interactive Shells](interactive-shells) - [6.3.1 What is an Interactive Shell?](what-is-an-interactive-shell_003f) - [6.3.2 Is this Shell Interactive?](is-this-shell-interactive_003f) - [6.3.3 Interactive Shell Behavior](interactive-shell-behavior) + [6.4 Bash Conditional Expressions](bash-conditional-expressions) + [6.5 Shell Arithmetic](shell-arithmetic) + [6.6 Aliases](aliases) + [6.7 Arrays](arrays) + [6.8 The Directory Stack](the-directory-stack) - [6.8.1 Directory Stack Builtins](directory-stack-builtins) + [6.9 Controlling the Prompt](controlling-the-prompt) + [6.10 The Restricted Shell](the-restricted-shell) + [6.11 Bash POSIX Mode](bash-posix-mode) + [6.12 Shell Compatibility Mode](shell-compatibility-mode) * [7 Job Control](job-control) + [7.1 Job Control Basics](job-control-basics) + [7.2 Job Control Builtins](job-control-builtins) + [7.3 Job Control Variables](job-control-variables) * [8 Command Line Editing](command-line-editing) + [8.1 Introduction to Line Editing](introduction-and-notation) + [8.2 Readline Interaction](readline-interaction) - [8.2.1 Readline Bare Essentials](readline-bare-essentials) - [8.2.2 Readline Movement Commands](readline-movement-commands) - [8.2.3 Readline Killing Commands](readline-killing-commands) - [8.2.4 Readline Arguments](readline-arguments) - [8.2.5 Searching for Commands in the History](searching) + [8.3 Readline Init File](readline-init-file) - [8.3.1 Readline Init File Syntax](readline-init-file-syntax) - [8.3.2 Conditional Init Constructs](conditional-init-constructs) - [8.3.3 Sample Init File](sample-init-file) + [8.4 Bindable Readline Commands](bindable-readline-commands) - [8.4.1 Commands For Moving](commands-for-moving) - [8.4.2 Commands For Manipulating The History](commands-for-history) - [8.4.3 Commands For Changing Text](commands-for-text) - [8.4.4 Killing And Yanking](commands-for-killing) - [8.4.5 Specifying Numeric Arguments](numeric-arguments) - [8.4.6 Letting Readline Type For You](commands-for-completion) - [8.4.7 Keyboard Macros](keyboard-macros) - [8.4.8 Some Miscellaneous Commands](miscellaneous-commands) + [8.5 Readline vi Mode](readline-vi-mode) + [8.6 Programmable Completion](programmable-completion) + [8.7 Programmable Completion Builtins](programmable-completion-builtins) + [8.8 A Programmable Completion Example](a-programmable-completion-example) * [9 Using History Interactively](using-history-interactively) + [9.1 Bash History Facilities](bash-history-facilities) + [9.2 Bash History Builtins](bash-history-builtins) + [9.3 History Expansion](history-interaction) - [9.3.1 Event Designators](event-designators) - [9.3.2 Word Designators](word-designators) - [9.3.3 Modifiers](modifiers) * [10 Installing Bash](installing-bash) + [10.1 Basic Installation](basic-installation) + [10.2 Compilers and Options](compilers-and-options) + [10.3 Compiling For Multiple Architectures](compiling-for-multiple-architectures) + [10.4 Installation Names](installation-names) + [10.5 Specifying the System Type](specifying-the-system-type) + [10.6 Sharing Defaults](sharing-defaults) + [10.7 Operation Controls](operation-controls) + [10.8 Optional Features](optional-features) * [Appendix A Reporting Bugs](reporting-bugs) * [Appendix B Major Differences From The Bourne Shell](major-differences-from-the-bourne-shell) + [B.1 Implementation Differences From The SVR4.2 Shell](major-differences-from-the-bourne-shell#Implementation-Differences-From-The-SVR4_002e2-Shell) * [Appendix C GNU Free Documentation License](gnu-free-documentation-license) * [Appendix D Indexes](indexes) + [D.1 Index of Shell Builtin Commands](builtin-index) + [D.2 Index of Shell Reserved Words](reserved-word-index) + [D.3 Parameter and Variable Index](variable-index) + [D.4 Function Index](function-index) + [D.5 Concept Index](concept-index)
programming_docs
bash Signals Signals ======= When Bash is interactive, in the absence of any traps, it ignores `SIGTERM` (so that ‘`kill 0`’ does not kill an interactive shell), and `SIGINT` is caught and handled (so that the `wait` builtin is interruptible). When Bash receives a `SIGINT`, it breaks out of any executing loops. In all cases, Bash ignores `SIGQUIT`. If job control is in effect (see [Job Control](job-control)), Bash ignores `SIGTTIN`, `SIGTTOU`, and `SIGTSTP`. Non-builtin commands started by Bash have signal handlers set to the values inherited by the shell from its parent. When job control is not in effect, asynchronous commands ignore `SIGINT` and `SIGQUIT` in addition to these inherited handlers. Commands run as a result of command substitution ignore the keyboard-generated job control signals `SIGTTIN`, `SIGTTOU`, and `SIGTSTP`. The shell exits by default upon receipt of a `SIGHUP`. Before exiting, an interactive shell resends the `SIGHUP` to all jobs, running or stopped. Stopped jobs are sent `SIGCONT` to ensure that they receive the `SIGHUP`. To prevent the shell from sending the `SIGHUP` signal to a particular job, it should be removed from the jobs table with the `disown` builtin (see [Job Control Builtins](job-control-builtins)) or marked to not receive `SIGHUP` using `disown -h`. If the `huponexit` shell option has been set with `shopt` (see [The Shopt Builtin](the-shopt-builtin)), Bash sends a `SIGHUP` to all jobs when an interactive login shell exits. If Bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes. When Bash is waiting for an asynchronous command via the `wait` builtin, the reception of a signal for which a trap has been set will cause the `wait` builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed. When job control is not enabled, and Bash is waiting for a foreground command to complete, the shell receives keyboard-generated signals such as `SIGINT` (usually generated by ‘`^C`’) that users commonly intend to send to that command. This happens because the shell and the command are in the same process group as the terminal, and ‘`^C`’ sends `SIGINT` to all processes in that process group. See [Job Control](job-control), for a more in-depth discussion of process groups. When Bash is running without job control enabled and receives `SIGINT` while waiting for a foreground command, it waits until that foreground command terminates and then decides what to do about the `SIGINT`: 1. If the command terminates due to the `SIGINT`, Bash concludes that the user meant to end the entire script, and acts on the `SIGINT` (e.g., by running a `SIGINT` trap or exiting itself); 2. If the pipeline does not terminate due to `SIGINT`, the program handled the `SIGINT` itself and did not treat it as a fatal signal. In that case, Bash does not treat `SIGINT` as a fatal signal, either, instead assuming that the `SIGINT` was used as part of the program’s normal operation (e.g., `emacs` uses it to abort editing commands) or deliberately discarded. However, Bash will run any trap set on `SIGINT`, as it does with any other trapped signal it receives while it is waiting for the foreground command to complete, for compatibility. bash Searching for Commands in the History Searching for Commands in the History ===================================== Readline provides commands for searching through the command history (see [Bash History Facilities](bash-history-facilities)) for lines containing a specified string. There are two search modes: *incremental* and *non-incremental*. Incremental searches begin before the user has finished typing the search string. As each character of the search string is typed, Readline displays the next entry from the history matching the string typed so far. An incremental search requires only as many characters as needed to find the desired history entry. To search backward in the history for a particular string, type `C-r`. Typing `C-s` searches forward through the history. The characters present in the value of the `isearch-terminators` variable are used to terminate an incremental search. If that variable has not been assigned a value, the `ESC` and `C-J` characters will terminate an incremental search. `C-g` will abort an incremental search and restore the original line. When the search is terminated, the history entry containing the search string becomes the current line. To find other matching entries in the history list, type `C-r` or `C-s` as appropriate. This will search backward or forward in the history for the next entry matching the search string typed so far. Any other key sequence bound to a Readline command will terminate the search and execute that command. For instance, a `RET` will terminate the search and accept the line, thereby executing the command from the history list. A movement command will terminate the search, make the last line found the current line, and begin editing. Readline remembers the last incremental search string. If two `C-r`s are typed without any intervening characters defining a new search string, any remembered search string is used. Non-incremental searches read the entire search string before starting to search for matching history lines. The search string may be typed by the user or be part of the contents of the current line. bash Word Splitting Word Splitting ============== The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting. The shell treats each character of `$IFS` as a delimiter, and splits the results of the other expansions into words using these characters as field terminators. If `IFS` is unset, or its value is exactly `<space><tab><newline>`, the default, then sequences of `<space>`, `<tab>`, and `<newline>` at the beginning and end of the results of the previous expansions are ignored, and any sequence of `IFS` characters not at the beginning or end serves to delimit words. If `IFS` has a value other than the default, then sequences of the whitespace characters `space`, `tab`, and `newline` are ignored at the beginning and end of the word, as long as the whitespace character is in the value of `IFS` (an `IFS` whitespace character). Any character in `IFS` that is not `IFS` whitespace, along with any adjacent `IFS` whitespace characters, delimits a field. A sequence of `IFS` whitespace characters is also treated as a delimiter. If the value of `IFS` is null, no word splitting occurs. Explicit null arguments (`""` or `''`) are retained and passed to commands as empty strings. Unquoted implicit null arguments, resulting from the expansion of parameters that have no values, are removed. If a parameter with no value is expanded within double quotes, a null argument results and is retained and passed to a command as an empty string. When a quoted null argument appears as part of a word whose expansion is non-null, the null argument is removed. That is, the word `-d''` becomes `-d` after word splitting and null argument removal. Note that if no expansion occurs, no splitting is performed. bash Specifying the System Type Specifying the System Type ========================== There may be some features `configure` can not figure out automatically, but needs to determine by the type of host Bash will run on. Usually `configure` can figure that out, but if it prints a message saying it can not guess the host type, give it the `--host=TYPE` option. ‘`TYPE`’ can either be a short name for the system type, such as ‘`sun4`’, or a canonical name with three fields: ‘`CPU-COMPANY-SYSTEM`’ (e.g., ‘`i386-unknown-freebsd4.2`’). See the file `support/config.sub` for the possible values of each field. bash Readline Interaction Readline Interaction ==================== Often during an interactive session you type in a long line of text, only to notice that the first word on the line is misspelled. The Readline library gives you a set of commands for manipulating the text as you type it in, allowing you to just fix your typo, and not forcing you to retype the majority of the line. Using these editing commands, you move the cursor to the place that needs correction, and delete or insert the text of the corrections. Then, when you are satisfied with the line, you simply press `RET`. You do not have to be at the end of the line to press `RET`; the entire line is accepted regardless of the location of the cursor within the line. * [Readline Bare Essentials](readline-bare-essentials) * [Readline Movement Commands](readline-movement-commands) * [Readline Killing Commands](readline-killing-commands) * [Readline Arguments](readline-arguments) * [Searching for Commands in the History](searching) bash Appendix C GNU Free Documentation License Appendix C GNU Free Documentation License ========================================= Version 1.3, 3 November 2008 ``` Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. http://fsf.org/ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. ``` 0. PREAMBLE The purpose of this License is to make a manual, textbook, or other functional and useful document *free* in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of “copyleft”, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference. 1. APPLICABILITY AND DEFINITIONS This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The “Document”, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as “you”. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law. A “Modified Version” of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language. A “Secondary Section” is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document’s overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them. The “Invariant Sections” are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none. The “Cover Texts” are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words. A “Transparent” copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not “Transparent” is called “Opaque”. Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only. The “Title Page” means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, “Title Page” means the text near the most prominent appearance of the work’s title, preceding the beginning of the body of the text. The “publisher” means any person or entity that distributes copies of the Document to the public. A section “Entitled XYZ” means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.) To “Preserve the Title” of such a section when you modify the Document means that it remains a section “Entitled XYZ” according to this definition. The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License. 2. VERBATIM COPYING You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies. 3. COPYING IN QUANTITY If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document’s license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document. 4. MODIFICATIONS You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: 1. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission. 2. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement. 3. State on the Title page the name of the publisher of the Modified Version, as the publisher. 4. Preserve all the copyright notices of the Document. 5. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices. 6. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below. 7. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document’s license notice. 8. Include an unaltered copy of this License. 9. Preserve the section Entitled “History”, Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled “History” in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence. 10. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the “History” section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission. 11. For any section Entitled “Acknowledgements” or “Dedications”, Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein. 12. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles. 13. Delete any section Entitled “Endorsements”. Such a section may not be included in the Modified Version. 14. Do not retitle any existing section to be Entitled “Endorsements” or to conflict in title with any Invariant Section. 15. Preserve any Warranty Disclaimers.If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version’s license notice. These titles must be distinct from any other section titles. You may add a section Entitled “Endorsements”, provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard. You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version. 5. COMBINING DOCUMENTS You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled “History” in the various original documents, forming one section Entitled “History”; likewise combine any sections Entitled “Acknowledgements”, and any sections Entitled “Dedications”. You must delete all sections Entitled “Endorsements.” 6. COLLECTIONS OF DOCUMENTS You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document. 7. AGGREGATION WITH INDEPENDENT WORKS A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an “aggregate” if the copyright resulting from the compilation is not used to limit the legal rights of the compilation’s users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document. If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document’s Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate. 8. TRANSLATION Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail. If a section in the Document is Entitled “Acknowledgements”, “Dedications”, or “History”, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title. 9. TERMINATION You may not copy, modify, sublicense, or distribute the Document except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, or distribute it is void, and will automatically terminate your rights under this License. However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, receipt of a copy of some or all of the same material does not give you any rights to use it. 10. FUTURE REVISIONS OF THIS LICENSE The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See <http://www.gnu.org/copyleft/>. Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License “or any later version” applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation. If the Document specifies that a proxy can decide which future versions of this License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Document. 11. RELICENSING “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any World Wide Web server that publishes copyrightable works and also provides prominent facilities for anybody to edit those works. A public wiki that anybody can edit is an example of such a server. A “Massive Multiauthor Collaboration” (or “MMC”) contained in the site means any set of copyrightable works thus published on the MMC site. “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0 license published by Creative Commons Corporation, a not-for-profit corporation with a principal place of business in San Francisco, California, as well as future copyleft versions of that license published by that same organization. “Incorporate” means to publish or republish a Document, in whole or in part, as part of another Document. An MMC is “eligible for relicensing” if it is licensed under this License, and if all works that were first published under this License somewhere other than this MMC, and subsequently incorporated in whole or in part into the MMC, (1) had no cover texts or invariant sections, and (2) were thus incorporated prior to November 1, 2008. The operator of an MMC Site may republish an MMC contained in the site under CC-BY-SA on the same site at any time before August 1, 2009, provided the MMC is eligible for relicensing. ### ADDENDUM: How to use this License for your documents To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: ``` Copyright (C) year your name. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. ``` If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the “with…Texts.” line with this: ``` with the Invariant Sections being list their titles, with the Front-Cover Texts being list, and with the Back-Cover Texts being list. ``` If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation. If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.
programming_docs
bash Bash History Facilities Bash History Facilities ======================= When the `-o history` option to the `set` builtin is enabled (see [The Set Builtin](the-set-builtin)), the shell provides access to the *command history*, the list of commands previously typed. The value of the `HISTSIZE` shell variable is used as the number of commands to save in a history list. The text of the last `$HISTSIZE` commands (default 500) is saved. The shell stores each command in the history list prior to parameter and variable expansion but after history expansion is performed, subject to the values of the shell variables `HISTIGNORE` and `HISTCONTROL`. When the shell starts up, the history is initialized from the file named by the `HISTFILE` variable (default `~/.bash\_history`). The file named by the value of `HISTFILE` is truncated, if necessary, to contain no more than the number of lines specified by the value of the `HISTFILESIZE` variable. When a shell with history enabled exits, the last `$HISTSIZE` lines are copied from the history list to the file named by `$HISTFILE`. If the `histappend` shell option is set (see [Bash Builtin Commands](bash-builtins)), the lines are appended to the history file, otherwise the history file is overwritten. If `HISTFILE` is unset, or if the history file is unwritable, the history is not saved. After saving the history, the history file is truncated to contain no more than `$HISTFILESIZE` lines. If `HISTFILESIZE` is unset, or set to null, a non-numeric value, or a numeric value less than zero, the history file is not truncated. If the `HISTTIMEFORMAT` is set, the time stamp information associated with each history entry is written to the history file, marked with the history comment character. When the history file is read, lines beginning with the history comment character followed immediately by a digit are interpreted as timestamps for the following history entry. The builtin command `fc` may be used to list or edit and re-execute a portion of the history list. The `history` builtin may be used to display or modify the history list and manipulate the history file. When using command-line editing, search commands are available in each editing mode that provide access to the history list (see [Commands For Manipulating The History](commands-for-history)). The shell allows control over which commands are saved on the history list. The `HISTCONTROL` and `HISTIGNORE` variables may be set to cause the shell to save only a subset of the commands entered. The `cmdhist` shell option, if enabled, causes the shell to attempt to save each line of a multi-line command in the same history entry, adding semicolons where necessary to preserve syntactic correctness. The `lithist` shell option causes the shell to save the command with embedded newlines instead of semicolons. The `shopt` builtin is used to set these options. See [The Shopt Builtin](the-shopt-builtin), for a description of `shopt`. bash Arithmetic Expansion Arithmetic Expansion ==================== Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is: ``` $(( expression )) ``` The expression undergoes the same expansions as if it were within double quotes, but double quote characters in expression are not treated specially and are removed. All tokens in the expression undergo parameter and variable expansion, command substitution, and quote removal. The result is treated as the arithmetic expression to be evaluated. Arithmetic expansions may be nested. The evaluation is performed according to the rules listed below (see [Shell Arithmetic](shell-arithmetic)). If the expression is invalid, Bash prints a message indicating failure to the standard error and no substitution occurs. bash The Shopt Builtin The Shopt Builtin ================= This builtin allows you to change additional shell optional behavior. `shopt` ``` shopt [-pqsu] [-o] [optname …] ``` Toggle the values of settings controlling optional shell behavior. The settings can be either those listed below, or, if the `-o` option is used, those available with the `-o` option to the `set` builtin command (see [The Set Builtin](the-set-builtin)). With no options, or with the `-p` option, a list of all settable options is displayed, with an indication of whether or not each is set; if optnames are supplied, the output is restricted to those options. The `-p` option causes output to be displayed in a form that may be reused as input. Other options have the following meanings: `-s` Enable (set) each optname. `-u` Disable (unset) each optname. `-q` Suppresses normal output; the return status indicates whether the optname is set or unset. If multiple optname arguments are given with `-q`, the return status is zero if all optnames are enabled; non-zero otherwise. `-o` Restricts the values of optname to be those defined for the `-o` option to the `set` builtin (see [The Set Builtin](the-set-builtin)). If either `-s` or `-u` is used with no optname arguments, `shopt` shows only those options which are set or unset, respectively. Unless otherwise noted, the `shopt` options are disabled (off) by default. The return status when listing options is zero if all optnames are enabled, non-zero otherwise. When setting or unsetting options, the return status is zero unless an optname is not a valid shell option. The list of `shopt` options is: `assoc_expand_once` If set, the shell suppresses multiple evaluation of associative array subscripts during arithmetic expression evaluation, while executing builtins that can perform variable assignments, and while executing builtins that perform array dereferencing. `autocd` If set, a command name that is the name of a directory is executed as if it were the argument to the `cd` command. This option is only used by interactive shells. `cdable_vars` If this is set, an argument to the `cd` builtin command that is not a directory is assumed to be the name of a variable whose value is the directory to change to. `cdspell` If set, minor errors in the spelling of a directory component in a `cd` command will be corrected. The errors checked for are transposed characters, a missing character, and a character too many. If a correction is found, the corrected path is printed, and the command proceeds. This option is only used by interactive shells. `checkhash` If this is set, Bash checks that a command found in the hash table exists before trying to execute it. If a hashed command no longer exists, a normal path search is performed. `checkjobs` If set, Bash lists the status of any stopped and running jobs before exiting an interactive shell. If any jobs are running, this causes the exit to be deferred until a second exit is attempted without an intervening command (see [Job Control](job-control)). The shell always postpones exiting if any jobs are stopped. `checkwinsize` If set, Bash checks the window size after each external (non-builtin) command and, if necessary, updates the values of `LINES` and `COLUMNS`. This option is enabled by default. `cmdhist` If set, Bash attempts to save all lines of a multiple-line command in the same history entry. This allows easy re-editing of multi-line commands. This option is enabled by default, but only has an effect if command history is enabled (see [Bash History Facilities](bash-history-facilities)). `compat31` `compat32` `compat40` `compat41` `compat42` `compat43` `compat44` These control aspects of the shell’s compatibility mode (see [Shell Compatibility Mode](shell-compatibility-mode)). `complete_fullquote` If set, Bash quotes all shell metacharacters in filenames and directory names when performing completion. If not set, Bash removes metacharacters such as the dollar sign from the set of characters that will be quoted in completed filenames when these metacharacters appear in shell variable references in words to be completed. This means that dollar signs in variable names that expand to directories will not be quoted; however, any dollar signs appearing in filenames will not be quoted, either. This is active only when bash is using backslashes to quote completed filenames. This variable is set by default, which is the default Bash behavior in versions through 4.2. `direxpand` If set, Bash replaces directory names with the results of word expansion when performing filename completion. This changes the contents of the Readline editing buffer. If not set, Bash attempts to preserve what the user typed. `dirspell` If set, Bash attempts spelling correction on directory names during word completion if the directory name initially supplied does not exist. `dotglob` If set, Bash includes filenames beginning with a ‘.’ in the results of filename expansion. The filenames ‘`.`’ and ‘`..`’ must always be matched explicitly, even if `dotglob` is set. `execfail` If this is set, a non-interactive shell will not exit if it cannot execute the file specified as an argument to the `exec` builtin command. An interactive shell does not exit if `exec` fails. `expand_aliases` If set, aliases are expanded as described below under Aliases, [Aliases](aliases). This option is enabled by default for interactive shells. `extdebug` If set at shell invocation, or in a shell startup file, arrange to execute the debugger profile before the shell starts, identical to the `--debugger` option. If set after invocation, behavior intended for use by debuggers is enabled: 1. The `-F` option to the `declare` builtin (see [Bash Builtin Commands](bash-builtins)) displays the source file name and line number corresponding to each function name supplied as an argument. 2. If the command run by the `DEBUG` trap returns a non-zero value, the next command is skipped and not executed. 3. If the command run by the `DEBUG` trap returns a value of 2, and the shell is executing in a subroutine (a shell function or a shell script executed by the `.` or `source` builtins), the shell simulates a call to `return`. 4. `BASH_ARGC` and `BASH_ARGV` are updated as described in their descriptions (see [Bash Variables](bash-variables)). 5. Function tracing is enabled: command substitution, shell functions, and subshells invoked with `( command )` inherit the `DEBUG` and `RETURN` traps. 6. Error tracing is enabled: command substitution, shell functions, and subshells invoked with `( command )` inherit the `ERR` trap. `extglob` If set, the extended pattern matching features described above (see [Pattern Matching](pattern-matching)) are enabled. `extquote` If set, `$'string'` and `$"string"` quoting is performed within `${parameter}` expansions enclosed in double quotes. This option is enabled by default. `failglob` If set, patterns which fail to match filenames during filename expansion result in an expansion error. `force_fignore` If set, the suffixes specified by the `FIGNORE` shell variable cause words to be ignored when performing word completion even if the ignored words are the only possible completions. See [Bash Variables](bash-variables), for a description of `FIGNORE`. This option is enabled by default. `globasciiranges` If set, range expressions used in pattern matching bracket expressions (see [Pattern Matching](pattern-matching)) behave as if in the traditional C locale when performing comparisons. That is, the current locale’s collating sequence is not taken into account, so ‘`b`’ will not collate between ‘`A`’ and ‘`B`’, and upper-case and lower-case ASCII characters will collate together. `globskipdots` If set, filename expansion will never match the filenames ‘`.`’ and ‘`..`’, even if the pattern begins with a ‘`.`’. This option is enabled by default. `globstar` If set, the pattern ‘`\*\*`’ used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a ‘`/`’, only directories and subdirectories match. `gnu_errfmt` If set, shell error messages are written in the standard GNU error message format. `histappend` If set, the history list is appended to the file named by the value of the `HISTFILE` variable when the shell exits, rather than overwriting the file. `histreedit` If set, and Readline is being used, a user is given the opportunity to re-edit a failed history substitution. `histverify` If set, and Readline is being used, the results of history substitution are not immediately passed to the shell parser. Instead, the resulting line is loaded into the Readline editing buffer, allowing further modification. `hostcomplete` If set, and Readline is being used, Bash will attempt to perform hostname completion when a word containing a ‘`@`’ is being completed (see [Letting Readline Type For You](commands-for-completion)). This option is enabled by default. `huponexit` If set, Bash will send `SIGHUP` to all jobs when an interactive login shell exits (see [Signals](signals)). `inherit_errexit` If set, command substitution inherits the value of the `errexit` option, instead of unsetting it in the subshell environment. This option is enabled when POSIX mode is enabled. `interactive_comments` Allow a word beginning with ‘`#`’ to cause that word and all remaining characters on that line to be ignored in an interactive shell. This option is enabled by default. `lastpipe` If set, and job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment. `lithist` If enabled, and the `cmdhist` option is enabled, multi-line commands are saved to the history with embedded newlines rather than using semicolon separators where possible. `localvar_inherit` If set, local variables inherit the value and attributes of a variable of the same name that exists at a previous scope before any new value is assigned. The `nameref` attribute is not inherited. `localvar_unset` If set, calling `unset` on local variables in previous function scopes marks them so subsequent lookups find them unset until that function returns. This is identical to the behavior of unsetting local variables at the current function scope. `login_shell` The shell sets this option if it is started as a login shell (see [Invoking Bash](invoking-bash)). The value may not be changed. `mailwarn` If set, and a file that Bash is checking for mail has been accessed since the last time it was checked, the message `"The mail in mailfile has been read"` is displayed. `no_empty_cmd_completion` If set, and Readline is being used, Bash will not attempt to search the `PATH` for possible completions when completion is attempted on an empty line. `nocaseglob` If set, Bash matches filenames in a case-insensitive fashion when performing filename expansion. `nocasematch` If set, Bash matches patterns in a case-insensitive fashion when performing matching while executing `case` or `[[` conditional commands (see [Conditional Constructs](conditional-constructs), when performing pattern substitution word expansions, or when filtering possible completions as part of programmable completion. `noexpand_translation` If set, Bash encloses the translated results of $"..." quoting in single quotes instead of double quotes. If the string is not translated, this has no effect. `nullglob` If set, Bash allows filename patterns which match no files to expand to a null string, rather than themselves. `patsub_replacement` If set, Bash expands occurrences of ‘`&`’ in the replacement string of pattern substitution to the text matched by the pattern, as described above (see [Shell Parameter Expansion](shell-parameter-expansion)). This option is enabled by default. `progcomp` If set, the programmable completion facilities (see [Programmable Completion](programmable-completion)) are enabled. This option is enabled by default. `progcomp_alias` If set, and programmable completion is enabled, Bash treats a command name that doesn’t have any completions as a possible alias and attempts alias expansion. If it has an alias, Bash attempts programmable completion using the command word resulting from the expanded alias. `promptvars` If set, prompt strings undergo parameter expansion, command substitution, arithmetic expansion, and quote removal after being expanded as described below (see [Controlling the Prompt](controlling-the-prompt)). This option is enabled by default. `restricted_shell` The shell sets this option if it is started in restricted mode (see [The Restricted Shell](the-restricted-shell)). The value may not be changed. This is not reset when the startup files are executed, allowing the startup files to discover whether or not a shell is restricted. `shift_verbose` If this is set, the `shift` builtin prints an error message when the shift count exceeds the number of positional parameters. `sourcepath` If set, the `.` (`source`) builtin uses the value of `PATH` to find the directory containing the file supplied as an argument. This option is enabled by default. `varredir_close` If set, the shell automatically closes file descriptors assigned using the `{varname}` redirection syntax (see [Redirections](redirections)) instead of leaving them open when the command completes. `xpg_echo` If set, the `echo` builtin expands backslash-escape sequences by default. bash Basic Installation Basic Installation ================== These are installation instructions for Bash. The simplest way to compile Bash is: 1. `cd` to the directory containing the source code and type ‘`./configure`’ to configure Bash for your system. If you’re using `csh` on an old version of System V, you might need to type ‘`sh ./configure`’ instead to prevent `csh` from trying to execute `configure` itself. Running `configure` takes some time. While running, it prints messages telling which features it is checking for. 2. Type ‘`make`’ to compile Bash and build the `bashbug` bug reporting script. 3. Optionally, type ‘`make tests`’ to run the Bash test suite. 4. Type ‘`make install`’ to install `bash` and `bashbug`. This will also install the manual pages and Info file, message translation files, some supplemental documentation, a number of example loadable builtin commands, and a set of header files for developing loadable builtins. You may need additional privileges to install `bash` to your desired destination, so ‘`sudo make install`’ might be required. More information about controlling the locations where `bash` and other files are installed is below (see [Installation Names](installation-names)). The `configure` shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile` in each directory of the package (the top directory, the `builtins`, `doc`, `po`, and `support` directories, each directory under `lib`, and several others). It also creates a `config.h` file containing system-dependent definitions. Finally, it creates a shell script named `config.status` that you can run in the future to recreate the current configuration, a file `config.cache` that saves the results of its tests to speed up reconfiguring, and a file `config.log` containing compiler output (useful mainly for debugging `configure`). If at some point `config.cache` contains results you don’t want to keep, you may remove or edit it. To find out more about the options and arguments that the `configure` script understands, type ``` bash-4.2$ ./configure --help ``` at the Bash prompt in your Bash source directory. If you want to build Bash in a directory separate from the source directory – to build for multiple architectures, for example – just use the full path to the configure script. The following commands will build bash in a directory under `/usr/local/build` from the source code in `/usr/local/src/bash-4.4`: ``` mkdir /usr/local/build/bash-4.4 cd /usr/local/build/bash-4.4 bash /usr/local/src/bash-4.4/configure make ``` See [Compiling For Multiple Architectures](compiling-for-multiple-architectures) for more information about building in a directory separate from the source. If you need to do unusual things to compile Bash, please try to figure out how `configure` could check whether or not to do them, and mail diffs or instructions to [[email protected]](mailto:[email protected]) so they can be considered for the next release. The file `configure.ac` is used to create `configure` by a program called Autoconf. You only need `configure.ac` if you want to change it or regenerate `configure` using a newer version of Autoconf. If you do this, make sure you are using Autoconf version 2.69 or newer. You can remove the program binaries and object files from the source code directory by typing ‘`make clean`’. To also remove the files that `configure` created (so you can compile Bash for a different kind of computer), type ‘`make distclean`’.
programming_docs