caddy.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. // Package caddy provides a PHP module for the Caddy web server.
  2. // FrankenPHP embeds the PHP interpreter directly in Caddy, giving it the ability to run your PHP scripts directly.
  3. // No PHP FPM required!
  4. package caddy
  5. import (
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "github.com/dunglas/frankenphp/internal/fastabs"
  10. "github.com/prometheus/client_golang/prometheus"
  11. "net/http"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "github.com/caddyserver/caddy/v2"
  16. "github.com/caddyserver/caddy/v2/caddyconfig"
  17. "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
  18. "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
  19. "github.com/caddyserver/caddy/v2/modules/caddyhttp"
  20. "github.com/caddyserver/caddy/v2/modules/caddyhttp/fileserver"
  21. "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite"
  22. "github.com/dunglas/frankenphp"
  23. "go.uber.org/zap"
  24. )
  25. const defaultDocumentRoot = "public"
  26. var iniError = errors.New("'php_ini' must be in the format: php_ini \"<key>\" \"<value>\"")
  27. func init() {
  28. caddy.RegisterModule(FrankenPHPApp{})
  29. caddy.RegisterModule(FrankenPHPModule{})
  30. caddy.RegisterModule(FrankenPHPAdmin{})
  31. httpcaddyfile.RegisterGlobalOption("frankenphp", parseGlobalOption)
  32. httpcaddyfile.RegisterHandlerDirective("php", parseCaddyfile)
  33. httpcaddyfile.RegisterDirectiveOrder("php", "before", "file_server")
  34. httpcaddyfile.RegisterDirective("php_server", parsePhpServer)
  35. httpcaddyfile.RegisterDirectiveOrder("php_server", "before", "file_server")
  36. }
  37. var metrics = frankenphp.NewPrometheusMetrics(prometheus.DefaultRegisterer)
  38. type workerConfig struct {
  39. // FileName sets the path to the worker script.
  40. FileName string `json:"file_name,omitempty"`
  41. // Num sets the number of workers to start.
  42. Num int `json:"num,omitempty"`
  43. // Env sets an extra environment variable to the given value. Can be specified more than once for multiple environment variables.
  44. Env map[string]string `json:"env,omitempty"`
  45. // Directories to watch for file changes
  46. Watch []string `json:"watch,omitempty"`
  47. }
  48. type FrankenPHPApp struct {
  49. // NumThreads sets the number of PHP threads to start. Default: 2x the number of available CPUs.
  50. NumThreads int `json:"num_threads,omitempty"`
  51. // MaxThreads limits how many threads can be started at runtime. Default 2x NumThreads
  52. MaxThreads int `json:"max_threads,omitempty"`
  53. // Workers configures the worker scripts to start.
  54. Workers []workerConfig `json:"workers,omitempty"`
  55. // Overwrites the default php ini configuration
  56. PhpIni map[string]string `json:"php_ini,omitempty"`
  57. }
  58. // CaddyModule returns the Caddy module information.
  59. func (f FrankenPHPApp) CaddyModule() caddy.ModuleInfo {
  60. return caddy.ModuleInfo{
  61. ID: "frankenphp",
  62. New: func() caddy.Module { return &f },
  63. }
  64. }
  65. func (f *FrankenPHPApp) Start() error {
  66. repl := caddy.NewReplacer()
  67. logger := caddy.Log()
  68. opts := []frankenphp.Option{
  69. frankenphp.WithNumThreads(f.NumThreads),
  70. frankenphp.WithMaxThreads(f.MaxThreads),
  71. frankenphp.WithLogger(logger),
  72. frankenphp.WithMetrics(metrics),
  73. frankenphp.WithPhpIni(f.PhpIni),
  74. }
  75. for _, w := range f.Workers {
  76. opts = append(opts, frankenphp.WithWorkers(repl.ReplaceKnown(w.FileName, ""), w.Num, w.Env, w.Watch))
  77. }
  78. frankenphp.Shutdown()
  79. if err := frankenphp.Init(opts...); err != nil {
  80. return err
  81. }
  82. return nil
  83. }
  84. func (f *FrankenPHPApp) Stop() error {
  85. caddy.Log().Info("FrankenPHP stopped 🐘")
  86. // attempt a graceful shutdown if caddy is exiting
  87. // note: Exiting() is currently marked as 'experimental'
  88. // https://github.com/caddyserver/caddy/blob/e76405d55058b0a3e5ba222b44b5ef00516116aa/caddy.go#L810
  89. if caddy.Exiting() {
  90. frankenphp.Shutdown()
  91. }
  92. // reset configuration so it doesn't bleed into later tests
  93. f.Workers = nil
  94. f.NumThreads = 0
  95. return nil
  96. }
  97. // UnmarshalCaddyfile implements caddyfile.Unmarshaler.
  98. func (f *FrankenPHPApp) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
  99. for d.Next() {
  100. for d.NextBlock(0) {
  101. switch d.Val() {
  102. case "num_threads":
  103. if !d.NextArg() {
  104. return d.ArgErr()
  105. }
  106. v, err := strconv.Atoi(d.Val())
  107. if err != nil {
  108. return err
  109. }
  110. f.NumThreads = v
  111. case "max_threads":
  112. if !d.NextArg() {
  113. return d.ArgErr()
  114. }
  115. if d.Val() == "auto" {
  116. f.MaxThreads = -1
  117. continue
  118. }
  119. v, err := strconv.ParseUint(d.Val(), 10, 32)
  120. if err != nil {
  121. return err
  122. }
  123. f.MaxThreads = int(v)
  124. case "php_ini":
  125. if !d.NextArg() {
  126. return iniError
  127. }
  128. key := d.Val()
  129. if !d.NextArg() {
  130. return iniError
  131. }
  132. if f.PhpIni == nil {
  133. f.PhpIni = make(map[string]string)
  134. }
  135. f.PhpIni[key] = d.Val()
  136. if d.NextArg() {
  137. return iniError
  138. }
  139. case "worker":
  140. wc := workerConfig{}
  141. if d.NextArg() {
  142. wc.FileName = d.Val()
  143. }
  144. if d.NextArg() {
  145. v, err := strconv.Atoi(d.Val())
  146. if err != nil {
  147. return err
  148. }
  149. wc.Num = v
  150. }
  151. for d.NextBlock(1) {
  152. v := d.Val()
  153. switch v {
  154. case "file":
  155. if !d.NextArg() {
  156. return d.ArgErr()
  157. }
  158. wc.FileName = d.Val()
  159. case "num":
  160. if !d.NextArg() {
  161. return d.ArgErr()
  162. }
  163. v, err := strconv.Atoi(d.Val())
  164. if err != nil {
  165. return err
  166. }
  167. wc.Num = v
  168. case "env":
  169. args := d.RemainingArgs()
  170. if len(args) != 2 {
  171. return d.ArgErr()
  172. }
  173. if wc.Env == nil {
  174. wc.Env = make(map[string]string)
  175. }
  176. wc.Env[args[0]] = args[1]
  177. case "watch":
  178. if !d.NextArg() {
  179. // the default if the watch directory is left empty:
  180. wc.Watch = append(wc.Watch, "./**/*.{php,yaml,yml,twig,env}")
  181. } else {
  182. wc.Watch = append(wc.Watch, d.Val())
  183. }
  184. }
  185. if wc.FileName == "" {
  186. return errors.New(`the "file" argument must be specified`)
  187. }
  188. if frankenphp.EmbeddedAppPath != "" && filepath.IsLocal(wc.FileName) {
  189. wc.FileName = filepath.Join(frankenphp.EmbeddedAppPath, wc.FileName)
  190. }
  191. }
  192. f.Workers = append(f.Workers, wc)
  193. }
  194. }
  195. }
  196. return nil
  197. }
  198. func parseGlobalOption(d *caddyfile.Dispenser, _ interface{}) (interface{}, error) {
  199. app := &FrankenPHPApp{}
  200. if err := app.UnmarshalCaddyfile(d); err != nil {
  201. return nil, err
  202. }
  203. // tell Caddyfile adapter that this is the JSON for an app
  204. return httpcaddyfile.App{
  205. Name: "frankenphp",
  206. Value: caddyconfig.JSON(app, nil),
  207. }, nil
  208. }
  209. type FrankenPHPModule struct {
  210. // Root sets the root folder to the site. Default: `root` directive, or the path of the public directory of the embed app it exists.
  211. Root string `json:"root,omitempty"`
  212. // SplitPath sets the substrings for splitting the URI into two parts. The first matching substring will be used to split the "path info" from the path. The first piece is suffixed with the matching substring and will be assumed as the actual resource (CGI script) name. The second piece will be set to PATH_INFO for the CGI script to use. Default: `.php`.
  213. SplitPath []string `json:"split_path,omitempty"`
  214. // ResolveRootSymlink enables resolving the `root` directory to its actual value by evaluating a symbolic link, if one exists.
  215. ResolveRootSymlink *bool `json:"resolve_root_symlink,omitempty"`
  216. // Env sets an extra environment variable to the given value. Can be specified more than once for multiple environment variables.
  217. Env map[string]string `json:"env,omitempty"`
  218. resolvedDocumentRoot string
  219. preparedEnv frankenphp.PreparedEnv
  220. preparedEnvNeedsReplacement bool
  221. logger *zap.Logger
  222. }
  223. // CaddyModule returns the Caddy module information.
  224. func (FrankenPHPModule) CaddyModule() caddy.ModuleInfo {
  225. return caddy.ModuleInfo{
  226. ID: "http.handlers.php",
  227. New: func() caddy.Module { return new(FrankenPHPModule) },
  228. }
  229. }
  230. // Provision sets up the module.
  231. func (f *FrankenPHPModule) Provision(ctx caddy.Context) error {
  232. f.logger = ctx.Logger(f)
  233. if f.Root == "" {
  234. if frankenphp.EmbeddedAppPath == "" {
  235. f.Root = "{http.vars.root}"
  236. } else {
  237. rrs := false
  238. f.Root = filepath.Join(frankenphp.EmbeddedAppPath, defaultDocumentRoot)
  239. f.ResolveRootSymlink = &rrs
  240. }
  241. } else {
  242. if frankenphp.EmbeddedAppPath != "" && filepath.IsLocal(f.Root) {
  243. f.Root = filepath.Join(frankenphp.EmbeddedAppPath, f.Root)
  244. }
  245. }
  246. if len(f.SplitPath) == 0 {
  247. f.SplitPath = []string{".php"}
  248. }
  249. if f.ResolveRootSymlink == nil {
  250. rrs := true
  251. f.ResolveRootSymlink = &rrs
  252. }
  253. if !needReplacement(f.Root) {
  254. root, err := fastabs.FastAbs(f.Root)
  255. if err != nil {
  256. return fmt.Errorf("unable to make the root path absolute: %w", err)
  257. }
  258. f.resolvedDocumentRoot = root
  259. if *f.ResolveRootSymlink {
  260. root, err := filepath.EvalSymlinks(root)
  261. if err != nil {
  262. return fmt.Errorf("unable to resolve root symlink: %w", err)
  263. }
  264. f.resolvedDocumentRoot = root
  265. }
  266. }
  267. if f.preparedEnv == nil {
  268. f.preparedEnv = frankenphp.PrepareEnv(f.Env)
  269. for _, e := range f.preparedEnv {
  270. if needReplacement(e) {
  271. f.preparedEnvNeedsReplacement = true
  272. break
  273. }
  274. }
  275. }
  276. return nil
  277. }
  278. // needReplacement checks if a string contains placeholders.
  279. func needReplacement(s string) bool {
  280. return strings.Contains(s, "{") || strings.Contains(s, "}")
  281. }
  282. // ServeHTTP implements caddyhttp.MiddlewareHandler.
  283. // TODO: Expose TLS versions as env vars, as Apache's mod_ssl: https://github.com/caddyserver/caddy/blob/master/modules/caddyhttp/reverseproxy/fastcgi/fastcgi.go#L298
  284. func (f FrankenPHPModule) ServeHTTP(w http.ResponseWriter, r *http.Request, _ caddyhttp.Handler) error {
  285. origReq := r.Context().Value(caddyhttp.OriginalRequestCtxKey).(http.Request)
  286. repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
  287. var documentRootOption frankenphp.RequestOption
  288. if f.resolvedDocumentRoot == "" {
  289. documentRootOption = frankenphp.WithRequestDocumentRoot(repl.ReplaceKnown(f.Root, ""), *f.ResolveRootSymlink)
  290. } else {
  291. documentRootOption = frankenphp.WithRequestResolvedDocumentRoot(f.resolvedDocumentRoot)
  292. }
  293. env := f.preparedEnv
  294. if f.preparedEnvNeedsReplacement {
  295. env = make(frankenphp.PreparedEnv, len(f.Env))
  296. for k, v := range f.preparedEnv {
  297. env[k] = repl.ReplaceKnown(v, "")
  298. }
  299. }
  300. fr, err := frankenphp.NewRequestWithContext(
  301. r,
  302. documentRootOption,
  303. frankenphp.WithRequestSplitPath(f.SplitPath),
  304. frankenphp.WithRequestPreparedEnv(env),
  305. frankenphp.WithOriginalRequest(&origReq),
  306. )
  307. if err != nil {
  308. return caddyhttp.Error(http.StatusInternalServerError, err)
  309. }
  310. if err = frankenphp.ServeHTTP(w, fr); err != nil {
  311. return caddyhttp.Error(http.StatusInternalServerError, err)
  312. }
  313. return nil
  314. }
  315. // UnmarshalCaddyfile implements caddyfile.Unmarshaler.
  316. func (f *FrankenPHPModule) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
  317. for d.Next() {
  318. for d.NextBlock(0) {
  319. switch d.Val() {
  320. case "root":
  321. if !d.NextArg() {
  322. return d.ArgErr()
  323. }
  324. f.Root = d.Val()
  325. case "split":
  326. f.SplitPath = d.RemainingArgs()
  327. if len(f.SplitPath) == 0 {
  328. return d.ArgErr()
  329. }
  330. case "env":
  331. args := d.RemainingArgs()
  332. if len(args) != 2 {
  333. return d.ArgErr()
  334. }
  335. if f.Env == nil {
  336. f.Env = make(map[string]string)
  337. f.preparedEnv = make(frankenphp.PreparedEnv)
  338. }
  339. f.Env[args[0]] = args[1]
  340. f.preparedEnv[args[0]+"\x00"] = args[1]
  341. case "resolve_root_symlink":
  342. if !d.NextArg() {
  343. continue
  344. }
  345. v, err := strconv.ParseBool(d.Val())
  346. if err != nil {
  347. return err
  348. }
  349. if d.NextArg() {
  350. return d.ArgErr()
  351. }
  352. f.ResolveRootSymlink = &v
  353. }
  354. }
  355. }
  356. return nil
  357. }
  358. // parseCaddyfile unmarshals tokens from h into a new Middleware.
  359. func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
  360. m := FrankenPHPModule{}
  361. err := m.UnmarshalCaddyfile(h.Dispenser)
  362. return m, err
  363. }
  364. // parsePhpServer parses the php_server directive, which has a similar syntax
  365. // to the php_fastcgi directive. A line such as this:
  366. //
  367. // php_server
  368. //
  369. // is equivalent to a route consisting of:
  370. //
  371. // # Add trailing slash for directory requests
  372. // @canonicalPath {
  373. // file {path}/index.php
  374. // not path */
  375. // }
  376. // redir @canonicalPath {path}/ 308
  377. //
  378. // # If the requested file does not exist, try index files
  379. // @indexFiles file {
  380. // try_files {path} {path}/index.php index.php
  381. // split_path .php
  382. // }
  383. // rewrite @indexFiles {http.matchers.file.relative}
  384. //
  385. // # FrankenPHP!
  386. // @phpFiles path *.php
  387. // php @phpFiles
  388. // file_server
  389. //
  390. // parsePhpServer is freely inspired from the php_fastgci directive of the Caddy server (Apache License 2.0, Matthew Holt and The Caddy Authors)
  391. func parsePhpServer(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) {
  392. if !h.Next() {
  393. return nil, h.ArgErr()
  394. }
  395. // set up FrankenPHP
  396. phpsrv := FrankenPHPModule{}
  397. // set up file server
  398. fsrv := fileserver.FileServer{}
  399. disableFsrv := false
  400. // set up the set of file extensions allowed to execute PHP code
  401. extensions := []string{".php"}
  402. // set the default index file for the try_files rewrites
  403. indexFile := "index.php"
  404. // set up for explicitly overriding try_files
  405. var tryFiles []string
  406. // if the user specified a matcher token, use that
  407. // matcher in a route that wraps both of our routes;
  408. // either way, strip the matcher token and pass
  409. // the remaining tokens to the unmarshaler so that
  410. // we can gain the rest of the directive syntax
  411. userMatcherSet, err := h.ExtractMatcherSet()
  412. if err != nil {
  413. return nil, err
  414. }
  415. // make a new dispenser from the remaining tokens so that we
  416. // can reset the dispenser back to this point for the
  417. // php unmarshaler to read from it as well
  418. dispenser := h.NewFromNextSegment()
  419. // read the subdirectives that we allow as overrides to
  420. // the php_server shortcut
  421. // NOTE: we delete the tokens as we go so that the php
  422. // unmarshal doesn't see these subdirectives which it cannot handle
  423. for dispenser.Next() {
  424. for dispenser.NextBlock(0) {
  425. // ignore any sub-subdirectives that might
  426. // have the same name somewhere within
  427. // the php passthrough tokens
  428. if dispenser.Nesting() != 1 {
  429. continue
  430. }
  431. // parse the php_server subdirectives
  432. switch dispenser.Val() {
  433. case "root":
  434. if !dispenser.NextArg() {
  435. return nil, dispenser.ArgErr()
  436. }
  437. phpsrv.Root = dispenser.Val()
  438. fsrv.Root = phpsrv.Root
  439. dispenser.DeleteN(2)
  440. case "split":
  441. extensions = dispenser.RemainingArgs()
  442. dispenser.DeleteN(len(extensions) + 1)
  443. if len(extensions) == 0 {
  444. return nil, dispenser.ArgErr()
  445. }
  446. case "index":
  447. args := dispenser.RemainingArgs()
  448. dispenser.DeleteN(len(args) + 1)
  449. if len(args) != 1 {
  450. return nil, dispenser.ArgErr()
  451. }
  452. indexFile = args[0]
  453. case "try_files":
  454. args := dispenser.RemainingArgs()
  455. dispenser.DeleteN(len(args) + 1)
  456. if len(args) < 1 {
  457. return nil, dispenser.ArgErr()
  458. }
  459. tryFiles = args
  460. case "file_server":
  461. args := dispenser.RemainingArgs()
  462. dispenser.DeleteN(len(args) + 1)
  463. if len(args) < 1 || args[0] != "off" {
  464. return nil, dispenser.ArgErr()
  465. }
  466. disableFsrv = true
  467. }
  468. }
  469. }
  470. // reset the dispenser after we're done so that the frankenphp
  471. // unmarshaler can read it from the start
  472. dispenser.Reset()
  473. if frankenphp.EmbeddedAppPath != "" {
  474. if phpsrv.Root == "" {
  475. phpsrv.Root = filepath.Join(frankenphp.EmbeddedAppPath, defaultDocumentRoot)
  476. fsrv.Root = phpsrv.Root
  477. rrs := false
  478. phpsrv.ResolveRootSymlink = &rrs
  479. } else if filepath.IsLocal(fsrv.Root) {
  480. phpsrv.Root = filepath.Join(frankenphp.EmbeddedAppPath, phpsrv.Root)
  481. fsrv.Root = phpsrv.Root
  482. }
  483. }
  484. // set up a route list that we'll append to
  485. routes := caddyhttp.RouteList{}
  486. // set the list of allowed path segments on which to split
  487. phpsrv.SplitPath = extensions
  488. // if the index is turned off, we skip the redirect and try_files
  489. if indexFile != "off" {
  490. dirRedir := false
  491. dirIndex := "{http.request.uri.path}/" + indexFile
  492. tryPolicy := "first_exist_fallback"
  493. // if tryFiles wasn't overridden, use a reasonable default
  494. if len(tryFiles) == 0 {
  495. if disableFsrv {
  496. tryFiles = []string{dirIndex, indexFile}
  497. } else {
  498. tryFiles = []string{"{http.request.uri.path}", dirIndex, indexFile}
  499. }
  500. dirRedir = true
  501. } else {
  502. if !strings.HasSuffix(tryFiles[len(tryFiles)-1], ".php") {
  503. // use first_exist strategy if the last file is not a PHP file
  504. tryPolicy = ""
  505. }
  506. for _, tf := range tryFiles {
  507. if tf == dirIndex {
  508. dirRedir = true
  509. break
  510. }
  511. }
  512. }
  513. // route to redirect to canonical path if index PHP file
  514. if dirRedir {
  515. redirMatcherSet := caddy.ModuleMap{
  516. "file": h.JSON(fileserver.MatchFile{
  517. TryFiles: []string{dirIndex},
  518. }),
  519. "not": h.JSON(caddyhttp.MatchNot{
  520. MatcherSetsRaw: []caddy.ModuleMap{
  521. {
  522. "path": h.JSON(caddyhttp.MatchPath{"*/"}),
  523. },
  524. },
  525. }),
  526. }
  527. redirHandler := caddyhttp.StaticResponse{
  528. StatusCode: caddyhttp.WeakString(strconv.Itoa(http.StatusPermanentRedirect)),
  529. Headers: http.Header{"Location": []string{"{http.request.orig_uri.path}/"}},
  530. }
  531. redirRoute := caddyhttp.Route{
  532. MatcherSetsRaw: []caddy.ModuleMap{redirMatcherSet},
  533. HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(redirHandler, "handler", "static_response", nil)},
  534. }
  535. routes = append(routes, redirRoute)
  536. }
  537. // route to rewrite to PHP index file
  538. rewriteMatcherSet := caddy.ModuleMap{
  539. "file": h.JSON(fileserver.MatchFile{
  540. TryFiles: tryFiles,
  541. TryPolicy: tryPolicy,
  542. SplitPath: extensions,
  543. }),
  544. }
  545. rewriteHandler := rewrite.Rewrite{
  546. URI: "{http.matchers.file.relative}",
  547. }
  548. rewriteRoute := caddyhttp.Route{
  549. MatcherSetsRaw: []caddy.ModuleMap{rewriteMatcherSet},
  550. HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(rewriteHandler, "handler", "rewrite", nil)},
  551. }
  552. routes = append(routes, rewriteRoute)
  553. }
  554. // route to actually pass requests to PHP files;
  555. // match only requests that are for PHP files
  556. var pathList []string
  557. for _, ext := range extensions {
  558. pathList = append(pathList, "*"+ext)
  559. }
  560. phpMatcherSet := caddy.ModuleMap{
  561. "path": h.JSON(pathList),
  562. }
  563. // the rest of the config is specified by the user
  564. // using the php directive syntax
  565. dispenser.Next() // consume the directive name
  566. err = phpsrv.UnmarshalCaddyfile(dispenser)
  567. if err != nil {
  568. return nil, err
  569. }
  570. // create the PHP route which is
  571. // conditional on matching PHP files
  572. phpRoute := caddyhttp.Route{
  573. MatcherSetsRaw: []caddy.ModuleMap{phpMatcherSet},
  574. HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(phpsrv, "handler", "php", nil)},
  575. }
  576. routes = append(routes, phpRoute)
  577. // create the file server route
  578. if !disableFsrv {
  579. fileRoute := caddyhttp.Route{
  580. MatcherSetsRaw: []caddy.ModuleMap{},
  581. HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(fsrv, "handler", "file_server", nil)},
  582. }
  583. routes = append(routes, fileRoute)
  584. }
  585. subroute := caddyhttp.Subroute{
  586. Routes: routes,
  587. }
  588. // the user's matcher is a prerequisite for ours, so
  589. // wrap ours in a subroute and return that
  590. if userMatcherSet != nil {
  591. return []httpcaddyfile.ConfigValue{
  592. {
  593. Class: "route",
  594. Value: caddyhttp.Route{
  595. MatcherSetsRaw: []caddy.ModuleMap{userMatcherSet},
  596. HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(subroute, "handler", "subroute", nil)},
  597. },
  598. },
  599. }, nil
  600. }
  601. // otherwise, return the literal subroute instead of
  602. // individual routes, to ensure they stay together and
  603. // are treated as a single unit, without necessarily
  604. // creating an actual subroute in the output
  605. return []httpcaddyfile.ConfigValue{
  606. {
  607. Class: "route",
  608. Value: subroute,
  609. },
  610. }, nil
  611. }
  612. // Interface guards
  613. var (
  614. _ caddy.App = (*FrankenPHPApp)(nil)
  615. _ caddy.Provisioner = (*FrankenPHPModule)(nil)
  616. _ caddyhttp.MiddlewareHandler = (*FrankenPHPModule)(nil)
  617. _ caddyfile.Unmarshaler = (*FrankenPHPModule)(nil)
  618. )