Docker 安装

  1. docker pull openresty/openresty

运行

  • -v 挂载宿主机目录,便于本地修改配置文件;
    1. docker run -p 8888:80 -v $PWD/conf.d:/etc/nginx/conf.d openresty/openresty:latest

    OpenResty最佳实践

OpenResty-Best-Practices.pdf

几个小例子

  • internal; 只允许内部调用;
  • default_type text/html; , response 的类型,如果不规定这个,wangye请求 lua 编辑的接口时会出现下载一个空白页;
  • content_by_lua_block{} , 嵌入 lua 代码块;
  • content_by_lua , 使用 lua 解释器执行后面的字符串;
  • ngx.say(res.body) , 应该是(猜的)OpenResty 的一个 api ,返回响应的内容。

    1. server {
    2. listen 80;
    3. server_name localhost;
    4. #charset koi8-r;
    5. #access_log /var/log/nginx/host.access.log main;
    6. location / {
    7. root /etc/dist;
    8. index index.html index.htm;
    9. }
    10. location = /sum {
    11. # 只允许内部调用
    12. internal;
    13. # 这里做了一个求和运算只是一个例子,可以在这里完成一些数据库、
    14. # 缓存服务器的操作,达到基础模块和业务逻辑分离目的
    15. content_by_lua_block {
    16. local args = ngx.req.get_uri_args()
    17. ngx.say(tonumber(args.a) + tonumber(args.b))
    18. }
    19. }
    20. location /block {
    21. default_type text/html;
    22. content_by_lua_block {
    23. local res = ngx.location.capture(
    24. "/sum", {args={a=3, b=8}}
    25. )
    26. ngx.say("status:", res.status, " response:", res.body)
    27. }
    28. }
    29. location /a {
    30. default_type 'text/plain';
    31. content_by_lua 'ngx.say("hello,lua")';
    32. }
    33. location /test {
    34. content_by_lua_block {
    35. local res = ngx.location.capture(
    36. '/print_param',
    37. {
    38. method = ngx.HTTP_POST,
    39. args = ngx.encode_args({a = 1, b = '2&'}),
    40. body = ngx.encode_args({c = 3, d = '4&'})
    41. }
    42. )
    43. ngx.say(res.body)
    44. }
    45. }
    46. location /hello {
    47. content_by_lua_block {
    48. local arg = ngx.req.get_uri_args()
    49. for k,v in pairs(arg) do
    50. ngx.say("[GET ] key:", k, " v:", v)
    51. end
    52. ngx.req.read_body() -- 解析 body 参数之前一定要先读取 body
    53. local arg = ngx.req.get_post_args()
    54. for k,v in pairs(arg) do
    55. ngx.say("[POST] key:", k, " v:", v)
    56. end
    57. }
    58. }
    59. #error_page 404 /404.html;
    60. # redirect server error pages to the static page /50x.html
    61. #
    62. error_page 500 502 503 504 /50x.html;
    63. location = /50x.html {
    64. root /usr/share/nginx/html;
    65. }
    66. # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    67. #
    68. #location ~ \.php$ {
    69. # proxy_pass http://127.0.0.1;
    70. #}
    71. # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    72. #
    73. #location ~ \.php$ {
    74. # root html;
    75. # fastcgi_pass 127.0.0.1:9000;
    76. # fastcgi_index index.php;
    77. # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
    78. # include fastcgi_params;
    79. #}
    80. # deny access to .htaccess files, if Apache's document root
    81. # concurs with nginx's one
    82. #
    83. #location ~ /\.ht {
    84. # deny all;
    85. #}
    86. }