You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

327 lines
14 KiB

  1. #!/bin/sh
  2. # This is a template copy it by: ./README.sh | xclip -selection c
  3. # to https://openwrt.org/docs/guide-user/services/webserver/nginx#configuration
  4. NGINX_UTIL="/usr/bin/nginx-util"
  5. EXAMPLE_COM="example.com"
  6. MSG="
  7. /* Created by the following bash script that includes the source of some files:
  8. * https://github.com/openwrt/packages/net/nginx/files/README.sh
  9. */"
  10. eval $("${NGINX_UTIL}" get_env)
  11. code() { printf "<file nginx %s>\n%s</file>" "$1" "$(cat "$(basename $1)")"; }
  12. ifConfEcho() { sed -nE "s/^\s*$1=\s*(\S*)\s*\\\\$/\n$2 \"\1\";/p" ../Makefile;}
  13. cat <<EOF
  14. ===== Configuration =====${MSG}
  15. The official Documentation contains a
  16. [[https://docs.nginx.com/nginx/admin-guide/|Admin Guide]].
  17. Here we will look at some often used configuration parts and how we handle them
  18. at OpenWrt.
  19. At different places there are references to the official
  20. [[https://docs.nginx.com/nginx/technical-specs/|Technical Specs]]
  21. for further reading.
  22. **tl;dr:** The main configuration is a minimal configuration enabling the
  23. ''${CONF_DIR}'' directory:
  24. * There is a ''${LAN_NAME}.conf'' containing a default server for the LAN, \
  25. which includes all ''*.locations''.
  26. * We can disable parts of the configuration by renaming them.
  27. * If we want to install other servers that are also reachable from the LAN, \
  28. we can include the ''${LAN_LISTEN}'' file (or ''${LAN_SSL_LISTEN}'' for \
  29. HTTPS servers).
  30. * If Nginx is installed with SSL support, we have a server \
  31. in ''_redirect2ssl.conf'' that redirects inexistent URLs to HTTPS, too.
  32. * We can create a self-signed certificate and add corresponding directives \
  33. to e.g. ''${EXAMPLE_COM}.conf'' by invoking \
  34. <code>$(basename ${NGINX_UTIL}) ${ADD_SSL_FCT} ${EXAMPLE_COM}</code>
  35. ==== Basic ====${MSG}
  36. We modify the configuration by creating different configuration files in the
  37. ''${CONF_DIR}'' directory.
  38. The configuration files use the file extensions ''.locations'' and
  39. ''.conf'' (plus ''.crt'' and ''.key'' for Nginx with SSL).
  40. We can disable single configuration parts by giving them another extension,
  41. e.g., by adding ''.disabled''.
  42. For the new configuration to take effect, we must reload it by:
  43. <code>service nginx reload</code>
  44. For OpenWrt we use a special initial configuration, which is explained below in
  45. the section [[#openwrt_s_defaults|OpenWrt’s Defaults]].
  46. So, we can make a site available at a specific URL in the **LAN** by creating a
  47. ''.locations'' file in the directory ''${CONF_DIR}''.
  48. Such a file consists just of some
  49. [[https://nginx.org/en/docs/http/ngx_http_core_module.html#location|
  50. location blocks]].
  51. Under the latter link, you can find also the official documentation for all
  52. available directives of the HTTP core of Nginx.
  53. Look for //location// in the Context list.
  54. The following example provides a simple template, see at the end for
  55. different [[#locations_for_apps|Locations for Apps]] and look for
  56. [[https://github.com/search?utf8=%E2%9C%93&q=repo%3Aopenwrt%2Fpackages
  57. +extension%3Alocations&type=Code&ref=advsearch&l=&l=|
  58. other packages using a .locations file]], too:
  59. <code nginx ${CONF_DIR}example.locations>
  60. location /ex/am/ple {
  61. access_log off; # default: not logging accesses.
  62. # access_log /proc/self/fd/1 openwrt; # use logd (init forwards stdout).
  63. # error_log stderr; # default: logging to logd (init forwards stderr).
  64. error_log /dev/null; # disable error logging after config file is read.
  65. # (state path of a file for access_log/error_log to the file instead.)
  66. index index.html;
  67. }
  68. # location /eg/static { … }
  69. </code>
  70. All location blocks in all ''.locations'' files must use different URLs,
  71. since they are all included in the ''${LAN_NAME}.conf'' that is part of the
  72. [[#openwrt_s_defaults|OpenWrt’s Defaults]].
  73. We reserve the ''location /'' for making LuCI available under the root URL,
  74. e.g. [[http://192.168.1.1/|192.168.1.1/]].
  75. All other sites shouldn’t use the root ''location /'' without suffix.
  76. We can make other sites available on the root URL of other domain names, e.g.
  77. on www.example.com/.
  78. In order to do that, we create a ''.conf'' file for every domain name:
  79. see the next section [[#new_server_parts|New Server Parts]].
  80. For Nginx with SSL we can also activate SSL there, as described below in the
  81. section [[#ssl_server_parts|SSL Server Parts]].
  82. We use such server parts also for publishing sites to the internet (WAN)
  83. instead of making them available just in the LAN.
  84. Via ''.conf'' files we can also add directives to the //http// part of the
  85. configuration. The difference to editing the main ''${NGINX_CONF}''
  86. file instead is the following: If the package’s ''nginx.conf'' file is updated
  87. it will only be installed if the old file has not been changed.
  88. ==== New Server Parts ====${MSG}
  89. For making the router reachable from the WAN at a registered domain name,
  90. it is not enough to give the name server the internet IP address of the router
  91. (maybe updated automatically by a
  92. [[docs:guide-user:services:ddns:client|DDNS Client]]).
  93. We also need to set up virtual hosting for this domain name by creating an
  94. appropriate server part in a ''${CONF_DIR}*.conf'' file.
  95. All such files are included at the start of Nginx by the default main
  96. configuration of OpenWrt ''${NGINX_CONF}'' as depicted in
  97. [[#openwrt_s_defaults|OpenWrt’s Defaults]].
  98. In the server part, we state the domain as
  99. [[https://nginx.org/en/docs/http/ngx_http_core_module.html#server_name|
  100. server_name]].
  101. The link points to the same document as for the location blocks in the
  102. [[#basic|Basic Configuration]]: the official documentation for all available
  103. directives of the HTTP core of Nginx.
  104. This time look for //server// in the Context list, too.
  105. The server part should also contain similar location blocks as before.
  106. We can re-include a ''.locations'' file that is included in the server part for
  107. the LAN by default.
  108. Then the site is reachable under the same path at both domains, e.g., by
  109. http://192.168.1.1/ex/am/ple as well as by http://example.com/ex/am/ple.
  110. The [[#openwrt_s_defaults|OpenWrt’s Defaults]] include a ''${LAN_NAME}.conf''
  111. file containing a server part that listens on the LAN address(es) and acts as
  112. //default_server//.
  113. For making the domain name accessible in the LAN, too, the corresponding
  114. server part must listen **explicitly** on the local IP address(es), cf. the
  115. official documentation on
  116. [[https://nginx.org/en/docs/http/request_processing.html|request_processing]].
  117. We can include the file ''${LAN_LISTEN}'' that contains the listen
  118. directives for all LAN addresses on the HTTP port 80 and is automatically
  119. updated.
  120. The following example is a simple template, see
  121. [[https://github.com/search?q=repo%3Aopenwrt%2Fpackages
  122. +include+${LAN_LISTEN}+extension%3Aconf&type=Code|
  123. such server parts of other packages]], too:
  124. <code nginx ${CONF_DIR}${EXAMPLE_COM}.conf>
  125. server {
  126. listen 80;
  127. listen [::]:80;
  128. include '${LAN_LISTEN}';
  129. server_name ${EXAMPLE_COM};
  130. # location / { … } # root location for this server.
  131. include '${CONF_DIR}${EXAMPLE_COM}.locations';
  132. }
  133. </code>
  134. ==== SSL Server Parts ====${MSG}
  135. We can enable HTTPS for a domain if Nginx is installed with SSL support.
  136. We need a SSL certificate as well as its key and add them by the directives
  137. //ssl_certificate// respective //ssl_certificate_key// to the server part of the
  138. domain.
  139. The rest of the configuration is similar as described in the previous section
  140. [[#new_server_parts|New Server Parts]],
  141. we only have to adjust the listen directives by adding the //ssl// parameter,
  142. see the official documentation for
  143. [[https://nginx.org/en/docs/http/configuring_https_servers.html|
  144. configuring HTTPS servers]], too.
  145. For making the domain available also in the LAN, we can include the file
  146. ''${LAN_SSL_LISTEN}'' that contains the listen directives with ssl
  147. parameter for all LAN addresses on the HTTPS port 443 and is automatically
  148. updated.
  149. The official documentation of the SSL module contains an
  150. [[https://nginx.org/en/docs/http/ngx_http_ssl_module.html#example|
  151. example]],
  152. which includes some optimizations.
  153. The following template is extended similarly, see also
  154. [[https://github.com/search?q=repo%3Aopenwrt%2Fpackages
  155. +include+${LAN_SSL_LISTEN}+extension%3Aconf&type=Code|
  156. other packages providing SSL server parts]]:
  157. <code nginx ${CONF_DIR}${EXAMPLE_COM}>
  158. server {
  159. listen 443 ssl;
  160. listen [::]:443 ssl;
  161. include '${LAN_SSL_LISTEN}';
  162. server_name ${EXAMPLE_COM};
  163. ssl_certificate '${CONF_DIR}${EXAMPLE_COM}.crt';
  164. ssl_certificate_key '${CONF_DIR}${EXAMPLE_COM}.key';
  165. ssl_session_cache ${SSL_SESSION_CACHE_ARG};
  166. ssl_session_timeout ${SSL_SESSION_TIMEOUT_ARG};
  167. # location / { … } # root location for this server.
  168. include '${CONF_DIR}${EXAMPLE_COM}.locations';
  169. }
  170. </code>
  171. For creating a certificate (and its key) we can use Let’s Encrypt by installing
  172. [[https://github.com/Neilpang/acme.sh|ACME Shell Script]]:
  173. <code>opkg update && opkg install acme # and for LuCI: luci-app-acme</code>
  174. For the LAN server in the ''${LAN_NAME}.conf'' file, the init script
  175. ''/etc/init.d/nginx'' script installs automatically a self-signed certificate.
  176. We can use this mechanism also for other sites by issuing, e.g.:
  177. <code>$(basename ${NGINX_UTIL}) ${ADD_SSL_FCT} ${EXAMPLE_COM}</code>
  178. - It adds SSL directives to the server part of \
  179. ''${CONF_DIR}${EXAMPLE_COM}.conf'' like in the example above.
  180. - Then, it checks if there is a certificate and key for the given domain name\
  181. that is valid for at least 13 months or tries to create a self-signed one.
  182. - When cron is activated, it installs a cron job for renewing the self-signed\
  183. certificate every year if needed, too. We can activate cron by: \
  184. <code>service cron enable && service cron start</code>
  185. Beside the ''${LAN_NAME}.conf'' file, the
  186. [[#openwrt_s_defaults|OpenWrt’s Defaults]] include also the
  187. ''_redirect2ssl.conf'' file containing a server part that redirects all HTTP
  188. request for inexistent URIs to HTTPS.
  189. ==== OpenWrt’s Defaults ====${MSG}
  190. The default main configuration file is:
  191. $(code ${NGINX_CONF})
  192. We can pretend the main configuration contains also the following presets,
  193. since Nginx is configured with them:
  194. <code nginx>$(ifConfEcho --pid-path pid)\
  195. $(ifConfEcho --lock-path lock_file)\
  196. $(ifConfEcho --error-log-path error_log)\
  197. $(false && ifConfEcho --http-log-path access_log)\
  198. $(ifConfEcho --http-proxy-temp-path proxy_temp_path)\
  199. $(ifConfEcho --http-client-body-temp-path client_body_temp_path)\
  200. $(ifConfEcho --http-fastcgi-temp-path fastcgi_temp_path)\
  201. </code>
  202. So, the access log is turned off by default and we can look at the error log
  203. by ''logread'', as Nginx’s init file forwards stderr and stdout to the
  204. [[docs:guide-user:base-system:log.essentials|logd]].
  205. We can set the //error_log// and //access_log// to files where the log
  206. messages are forwarded to instead (after the configuration is read).
  207. And for redirecting the access log of a //server// or //location// to the logd,
  208. too, we insert the following directive in the corresponding block:
  209. <code nginx>
  210. access_log /proc/self/fd/1 openwrt;
  211. </code>
  212. At the end, the main configuration pulls in all ''.conf'' files from the
  213. directory ''${CONF_DIR}'' into the http block, especially the following
  214. server part for the LAN:
  215. $(code ${CONF_DIR}${LAN_NAME}.conf)
  216. It pulls in all ''.locations'' files from the directory ''${CONF_DIR}''.
  217. We can install the location parts of different sites there (see above in the
  218. [[#basic|Basic Configuration]]) and re-include them in server parts of other
  219. ''${CONF_DIR}*.conf'' files.
  220. This is needed especially for making them available to the WAN as described
  221. above in the section [[#new_server_parts|New Server Parts]].
  222. All ''.locations'' become available on the LAN through the file
  223. ''$(basename ${LAN_LISTEN}).default'', which contains one of the following
  224. directives for every local IP address:
  225. <code nginx>
  226. listen IPv4:80 default_server;
  227. listen [IPv6]:80 default_server;
  228. </code>
  229. The ''${LAN_LISTEN}'' file contains the same directives without the
  230. parameter ''default_server''.
  231. We can include this file in other server parts that should be reachable in the
  232. LAN through their //server_name//.
  233. Both files ''${LAN_LISTEN}{,.default}'' are (re-)created if Nginx starts
  234. through its init for OpenWrt or the LAN interface changes.
  235. === Additional Defaults for OpenWrt if Nginx is installed with SSL support ===
  236. When Nginx is installed with SSL support, there will be automatically managed
  237. files ''$(basename ${LAN_SSL_LISTEN}).default'' and
  238. ''$(basename ${LAN_SSL_LISTEN})'' in the directory
  239. ''$(dirname ${LAN_SSL_LISTEN})/'' containing the following directives for all
  240. IPv4 and IPv6 addresses of the LAN:
  241. <code nginx>
  242. listen IP:443 ssl; # with respectively without: default_server
  243. </code>
  244. Both files as well as the ''${LAN_LISTEN}{,.default}'' files are (re-)created
  245. if Nginx starts through its init for OpenWrt or the LAN interface changes.
  246. For Nginx with SSL there is also the following server part that redirects
  247. requests for an inexistent ''server_name'' from HTTP to HTTPS (using an invalid
  248. name, more in the official documentation on
  249. [[https://nginx.org/en/docs/http/request_processing.html|request_processing]]):
  250. $(code ${CONF_DIR}_redirect2ssl.conf)
  251. Nginx’s init file for OpenWrt installs automatically a self-signed certificate
  252. for the LAN server part if needed and possible:
  253. - Everytime Nginx starts, we check if the LAN is set up for SSL.
  254. - We add //ssl*// directives (like in the example of the previous section \
  255. [[#ssl_server_parts|SSL Server Parts]]) to the configuration file \
  256. ''${CONF_DIR}${LAN_NAME}.conf'' if needed and if it looks “normal”, i.e., \
  257. it has a ''server_name ${LAN_NAME};'' part.
  258. - If there is no corresponding certificate that is valid for more than 13 \
  259. months at ''${CONF_DIR}${LAN_NAME}.{crt,key}'', we create a self-signed one.
  260. - We activate SSL by including the ssl listen directives from \
  261. ''${LAN_SSL_LISTEN}.default'' and it becomes available by the default \
  262. redirect from ''listen *:80;'' in ''${CONF_DIR}_redirect2ssl.conf''
  263. - If cron is available, i.e., its status is not ''inactive'', we use it \
  264. to check the certificate for validity once a year and renew it if there \
  265. are only about 13 months of the more than 3 years life time left.
  266. The points 2, 3 and 5 can be used for other domains, too:
  267. As described in the section [[#new_server_parts|New Server Parts]] above, we
  268. create a server part in ''${CONF_DIR}www.example.com.conf'' with
  269. a corresponding ''server_name www.example.com;'' directive and call
  270. <code>$(basename ${NGINX_UTIL}) ${ADD_SSL_FCT} www.example.com</code>
  271. EOF