Creating a Hello World! Nginx Module
Some of my friends think nginx modules are very difficult to write. Sure it’s not so easy but it’s not that hard either. The only problem is that the documentation is not enough. But don’t let this scare yourself away, the situation is improving.
So I write a hello world nginx module here. It’s pretty short and with enough comments. If you’re a new nginx module developer, feel free to take it as an example and replace hello with whatever your module name is, then start your happy nginx module hacking journey. And I’ll write more topics on nginx soon. Look for it!
ngx_http_hello_module.c:
/* * Copyright (C) Joshua Zhu, http://www.zhuzhaoyuan.com */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> static char *ngx_http_hello(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static ngx_command_t ngx_http_hello_commands[] = { { ngx_string("hello"), NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS, ngx_http_hello, 0, 0, NULL }, ngx_null_command }; static u_char ngx_hello_string[] = "Hello, world!"; static ngx_http_module_t ngx_http_hello_module_ctx = { NULL, /* preconfiguration */ NULL, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ NULL, /* create location configuration */ NULL /* merge location configuration */ }; ngx_module_t ngx_http_hello_module = { NGX_MODULE_V1, &ngx_http_hello_module_ctx, /* module context */ ngx_http_hello_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static ngx_int_t ngx_http_hello_handler(ngx_http_request_t *r) { ngx_int_t rc; ngx_buf_t *b; ngx_chain_t out; /* we response to 'GET' and 'HEAD' requests only */ if (!(r->method & (NGX_HTTP_GET|NGX_HTTP_HEAD))) { return NGX_HTTP_NOT_ALLOWED; } /* discard request body, since we don't need it here */ rc = ngx_http_discard_request_body(r); if (rc != NGX_OK) { return rc; } /* set the 'Content-type' header */ r->headers_out.content_type_len = sizeof("text/html") - 1; r->headers_out.content_type.len = sizeof("text/html") - 1; r->headers_out.content_type.data = (u_char *) "text/html"; /* send the header only, if the request type is http 'HEAD' */ if (r->method == NGX_HTTP_HEAD) { r->headers_out.status = NGX_HTTP_OK; r->headers_out.content_length_n = sizeof(ngx_hello_string) - 1; return ngx_http_send_header(r); } /* allocate a buffer for your response body */ b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); if (b == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } /* attach this buffer to the buffer chain */ out.buf = b; out.next = NULL; /* adjust the pointers of the buffer */ b->pos = ngx_hello_string; b->last = ngx_hello_string + sizeof(ngx_hello_string) - 1; b->memory = 1; /* this buffer is in memory */ b->last_buf = 1; /* this is the last buffer in the buffer chain */ /* set the status line */ r->headers_out.status = NGX_HTTP_OK; r->headers_out.content_length_n = sizeof(ngx_hello_string) - 1; /* send the headers of your response */ rc = ngx_http_send_header(r); if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { return rc; } /* send the buffer chain of your response */ return ngx_http_output_filter(r, &out); } static char * ngx_http_hello(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_core_loc_conf_t *clcf; clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module); clcf->handler = ngx_http_hello_handler; /* handler to process the 'hello' directive */ return NGX_CONF_OK; }
config:
ngx_addon_name=ngx_http_hello_module HTTP_MODULES="$HTTP_MODULES ngx_http_hello_module" NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_hello_module.c"
hello.conf:
# hello
worker_processes 1;
events {
worker_connections 1024;
}
http {
server {
listen 8080;
server_name localhost;
location / {
hello;
}
}
}If you want more detailed information, please consult Evan Miller’s Guide To Nginx Module Development.
peanut said,
March 22, 2010 @ 4:58 am
Thank you! Very useful tutorial.
pauly said,
July 23, 2010 @ 5:00 pm
Thanks. It helps me a lot.
Fitzgerald said,
August 3, 2010 @ 3:03 pm
When setting the content type header; this looks a bit odd to me:
r->headers_out.content_type_len = sizeof(”text/html”) - 1;
r->headers_out.content_type.len = sizeof(”text/html”) - 1;
is this OK?
Joshua said,
August 6, 2010 @ 12:11 am
@Fitzgerald,
Yes. The value of content_type_len is usually the same as content_type.len, but in some case, i.e. when there’s charset setting with the Content-Type HTTP header, e.g. given header “Content-Type: text/html; charset=UTF-8″, content_type_len (23) is less than content_type.len (38).
Wigunawan said,
October 19, 2010 @ 10:06 pm
nice tutor.
as Fitzgerald asked,
r->headers_out.content_type_len = sizeof(”text/html”) - 1;
r->headers_out.content_type.len = sizeof(”text/html”) - 1;
why you write the same code twice?
eric said,
December 14, 2010 @ 2:22 am
The G-WAN Web server and its ANSI C scripts are easier to write.
Here is a more complex ‘hello world’ that takes only 10 lines of C:
(more complex because it lets you specify who you say hello to)
http://gwan.ch/en_developers.html
G-WAN is not only working without any configuration fles, but it is
much faster than nginx.
Joshua said,
December 14, 2010 @ 11:52 am
@eric,
I agree with you that it is much easier that writing a “hello world” module for your G-WAN web server. But could you show us the benchmarks that G-WAN “is much faster than nginx”? BTW, it would be nice if G-WAN is going to be open source.
eric said,
December 15, 2010 @ 11:12 pm
@Joshua,
Per your request, benchmarks that show that G-WAN “is much faster than nginx”:
- on Windows:
http://gwan.ch/en_windows.html
- on Linux:
http://gwan.ch/en_linux.html
…which points to:
http://gwan.ch/imgs/gwan-lighttpd-nginx-cherokee.png
Being faster that nginx with STATIC contents, G-WAN is
also faster for DYNAMIC contents.
And this is true, even with an nginx pre-compiled module
(while G-WAN uses C scripts that are executed on-the-fly).
The open-source question has been debated in length
on the forum:
http://forum.trustleap.com/web/g-wanforum.nsf/viewTopic.xsp?topicID=1hkwsfnttsbuo
Joshua said,
December 16, 2010 @ 11:27 am
@eric,
Quite impressive! But I’m wondering is it possible that you give us more details of the benchmarks? e.g. hardware, OS, and configuration of the web servers. AFAIK, nginx is not optimized by default.
Zhao Haifeng said,
February 28, 2011 @ 7:05 pm
Hi, I’m Zhao Haifeng, an university student. I plan to write a web server like nginx as the Graduation Project. Of course, I know that it’s impossible for me to write such a greate one in such a short time. But I want to learn more about Linux, Web Server and programming from this graduation project. That’s why I ask my mentor to give me this topic. I want to read nginx source code first, but it’s really a hard job. I wonder if you can tell me something about how I can understand it. Or, could you please tell me what I should learn before doing my graduation project? Now, I just have basic knowlege of Linux, computer network (include HTTP) and programming.
Zhao Haifeng said,
February 28, 2011 @ 7:06 pm
Many thanks and waiting for your response.
Joshua said,
February 28, 2011 @ 10:03 pm
@Zhao Haifeng,
Wanna learn how a web server works? This may be a good start:
http://code.google.com/p/mongoose/
Check it out and have fun!
Zhao Haifeng said,
March 1, 2011 @ 3:55 pm
OK, thank you! I will check it this evening. If I have some problems, maybe I will ask you! Thank you!
Kris said,
March 28, 2011 @ 12:02 am
@Joshua,
G-WAN vs Nginx, Varnish, Apache Traffic Server (a cache server, like Varnish), Lighttpd have been benchmarked here:
http://nbonvin.wordpress.com/2011/03/24/serving-small-static-files-which-server-to-use/
Not only you have all the configurations published there, but there is also a comparison of the CPU and memory usage.
G-WAN beats all others (head and shoulders) despite the low-end hardware (a laptop Intel Core i3 – 370M @ 2.4 Ghz, Hard drive 5400 rpm, Memory: 4GB DDR3 1066MHz).
This is just to reply to your question about the server tuning issues (Nginx is tested with 2 and 4 workers).
Grigory said,
June 19, 2011 @ 5:06 am
@Kris,
In tests by your link, there is a very old nginx - 0.7.67. Why test authors didn’t get nginx-0.0.1 version to make a benchmark. They wrote the article at march 2011 and the question is: did they now that currently nignx was finally released at 1.0 version? (at the moment, when I’m writing this comment, nginx current version is 1.0.4). Very funny benchmark using “zombies” for tests
Grigory said,
June 19, 2011 @ 5:10 am
Oh my… they added update for 1.0 version. Sorry my bad
Magda said,
August 16, 2011 @ 12:34 am
IMHO you’ve got the right anwesr!
bjrikyiwvcz said,
August 18, 2011 @ 8:23 pm
WUcHIY fcoppjmrlgdj
Ryo Onodera said,
June 1, 2012 @ 6:37 pm
Hi, thanks for sharing an example module!
I’m starting to implement nginx-based HTTP interface for groonga (http://groonga.org/) using your example.
For doing so, I have to clarify copyright status of this example, because there is no explicit copyright notice.
Is this example in the public domain? Or is it licensed under one of open source licenses?
Specifically, I’d like to be able to re-license it under LGPL1.2. Because groonga is in LGPL 1.2.
Joshua said,
June 1, 2012 @ 10:08 pm
Hi Ryo, this piece of code is in public domain. You can use it whatever you like freely.
Ryo Onodera said,
June 4, 2012 @ 9:49 am
Hi Joshua, thank you very much!
longtermhairremoval.webstarts.com said,
June 24, 2012 @ 8:49 pm
Excellent article. I will be going through many of these
issues as well.. no no hair removal review
read about it here said,
June 25, 2012 @ 8:25 pm
I like it when folks get together and share thoughts.
Great site, keep it up! directtv
Ralph Lauren Polo Shirt said,
June 26, 2012 @ 3:12 am
Thanks! it’s helpful to me!
Arthur Fohl said,
July 1, 2012 @ 2:08 am
Hello.This article was extremely interesting, especially because I was investigating for thoughts on this issue last couple of days.
pozycjonowanie stron internetowych kraków said,
July 4, 2012 @ 7:00 am
Only a smiling visitant here to share the love (:, btw great pattern. “Competition is a painful thing, but it produces great results.” by Jerry Flint.
coney said,
August 9, 2012 @ 11:38 am
how can I link a lib here, e.g, libpq?
Thanks
Joshua said,
August 9, 2012 @ 6:14 pm
@coney: see here: http://www.evanmiller.org/nginx-modules-guide.html#compiling
Moncler Outlet Online said,
August 10, 2012 @ 9:07 am
Wonderful blog!After studying you site, your internet site is extremely useful for me .I undeniably will undoubtedly revisit.The hope can share the author more articles.
fitflops said,
August 11, 2012 @ 2:20 pm
http://www.thailandfitflopssale.com/ Wonderful blog!After studying you site, your internet site is extremely useful for me .I undeniably will undoubtedly revisit.The hope can share the author more articles.
discount ray bans said,
August 15, 2012 @ 9:23 am
The Santa Claus week,? l? set of rites organized by Various brotherhoods, ray ban outletcheap oakley radar? Within Sardinia? 1 treasure of high cultural value, as well as devotional GNA that
sac longchamps said,
August 21, 2012 @ 2:51 pm
For those who love to enjoy sac longchamp solde leisurely and comfortable life the father for the COACH to restore ancient ways stripe canvas bag there is no doubt that awakening in sac longchamps the summer low-pressure breath - stripe inspiration comes from sac longchamp pas cher gypsum painting, design slightly plain and clumsy, and shoulder take the grommet is reminiscent of the sails, make the same score a sailor feelings. As for those who seek hegemony workplace “addiction” work of the fathers, COACH adjustable shoulder belt Thompson medium long and narrow messenger bag or Harrison long and narrow handbag for both some whiskey debauchery leather, thus the male costly deduce incisively and vividly, can light up the office ideal choice. In addition to the above of meticulous preparation, COACH still doesn’t forget to send nuanced accessories accessories - style hale and hearty woven leather key buckles and compact all zipper travel ticket holder can let you in the father’s day win dad favor.
Coach Bags said,
August 29, 2012 @ 7:18 am
Me and my friend were arguing about an problem similar to this! Now I realize that I had been correct. lol! Thank you for that information you article.
Usama Dar said,
September 2, 2012 @ 10:34 pm
A slightly improved version here
http://usamadar.com/2012/09/02/writing-a-custom-nginx-module/
sbditto85 said,
October 12, 2012 @ 12:25 am
Thanks for the tut!
As for the GWAN vs. NGINX from __my experience__ nginx servers things out just as fast if not faster, has more configuration options (can get it to work with php-fpm, etc), and less CPU load then GWAN. This comes from running both latest versions (as of 6 months ago) as media servers. However it is a __LOT__ easier to just write a c script for GWAN compared to NGINX … my 2 cents.
Jsmith4 said,
October 12, 2012 @ 8:10 am
As for me I would never stick to closed source thing.
1) It will not made it to default repositories of Linux systems, hence more administrative hassle
2) It’s a gound for vendor lock-in.
3) It’s guaranteed to fail to match any non-standard need and no chance to fix? What, installing 32-bit libs on 64-bit systems just for server? Ridiculous! And how about running on some ARM microserver? Oh, no way? Kinda sad.
4) It allows us to learn how it’s created and possible change ways things are done.
That’s why we love open source. It gives us freedom to innovate and achieve our goals. Without any artificial restrictions. Not something you can achieve with proprietary stuff.
Sac Longchamp Solde said,
November 17, 2012 @ 10:12 am
Soft Stirrup handbags with rare materials refined but become, including water cowboy skin and suede leather, all with natural Gucci (Gucci) double G cloth or leather is made, and all kinds of special animal skin, such as python skin, ostrich skin and crocodile skin, etc., and to chamois leather for lining.
chrise said,
November 22, 2012 @ 3:14 pm
The square sac longchamp gives capable of feeling, with the career modeling can gift handsome neutral temperament, large capacity allows you more efficiency.
Yogesh Patel said,
January 17, 2013 @ 10:09 pm
Hi Zhao Haifeng,
Many thanks to Share your knowledge with us.
I want to make a c++ client server with the help or Nginx .Is it possible to set up the Nginx server which listens to the C++ program and gives response. I don’t want to Use HTTP browser. only c++ Program and Nginx …Please do reply Its very urgent to me .
Regards
Yogesh Patel
rohit said,
January 23, 2013 @ 5:23 pm
Hi Zhao Haifeng,
Thanks for your hello world module with all the comments.
But will you provide me a small module were we can pass arguments
ex:if we pass our name in the url…(localhost/test?name=rohit) then it should print hello_world.so that i get to know how exactly we have to pass arguments and work on it.This will be great help because i m trying like anything but getting lot of errors.so will u please.
Regards
Rohit
rohit said,
January 23, 2013 @ 5:29 pm
Hi Joshua,
Thanks for your hello world module with all the comments.
But will you provide me a small module were we can pass arguments
ex:if we pass our name in the url…(localhost/test?name=rohit) then it should print hello_world.so that i get to know how exactly we have to pass arguments and work on it.This will be great help because i m trying like anything but getting lot of errors.so will u please.
Regards
Rohit
http://www.davidgphillips.com said,
March 6, 2013 @ 4:55 am
Your own article offers confirmed necessary to me personally.
It’s very useful and you’re simply obviously extremely well-informed in this region. You have got popped my personal eye for you to varying opinion of this subject with interesting and reliable content material.
short term loans bird said,
March 14, 2013 @ 6:21 am
Cars happen to be getting you from point A to suggest B for 100 years at this point short term loans The loan amount of
money will be predetermined taking ones monthly salary into account
e-cigs said,
March 15, 2013 @ 10:51 pm
Refillable EGO, Best Suffolk County bar use of the mathematical product wherever regular cigarettes are forbidden.
electronic cigarettes hoi polloi who roll of tobacco marihuana looks like a cigarette, and at commencement glance,
it appears as if the user may be smoking.
car rental london said,
March 21, 2013 @ 8:54 pm
The fact is that nearly businesses o’er the past two old age, product volumes of the Peugeot 107 have remained on an upward course. car rental uk functional around into diametric side immense iPhone in your custody.
uk cash loans said,
April 20, 2013 @ 5:44 am
College students don’t seem to reside life upon as much as a spending budget as they would in the 70’s and Nineteen-eighties, but that that don’t desire a helping hand from time to time cash loans If Obama insists on troop buildups in Afghanistan along with a promise for you to hunt down container Laden, we have to all realize that a country must not pursue a pair of contradictory tips at the same time: a person, that terrorism will be stateless, and two, in which military forays straight into foreign claims are prosperous
instant payday loans said,
April 20, 2013 @ 6:52 am
Take a loan in a day when you wish cash since text personal loans are existing deals to suit your needs instant payday loans These questions have
been answered with crucial tips for keeping the cash flowing
コーチ 財布 said,
April 28, 2013 @ 5:17 pm
。オンラインサイ
トにもかかわらず
、あなたがYahooとGoogleで表示されますト
ラフィックをターゲット
を促進する上で、常に右から大金を作成する
ためにおそらく最も有用
な方法であったか
の理想的な取引があることを確認ペ
ージの友人や家族。多くの最先
端の起業家は、検
索エンジンの最適化は時間
、デパートの時間と労力と忍耐のない終わりを
取るする見落とす。 。だけ
でなく、コーチ、
単純にすべて
の有名なファッションデザイナーの
マークの
exclusivewebhosting.co.uk said,
April 30, 2013 @ 11:11 pm
We all assume that one size fits all, Google as comfortably — and it’s that remainder which makes the phone such an challenging composition of ironware. free website hosting For centuries, we have witnessed the nascence of movements, and striking shifts in populace opinion — sparked by the shared out hosting feature article that has been just about since 15 days.
payday uk payday loans said,
May 4, 2013 @ 7:10 pm
No cite checks & money in total why are banks so unintelligent to give recognition card game and abode loans to merely roughly anybody?
payday uk payday loans Autofocus worked considerably in near situations, and we were some
more than reasons.
http://www.cashwonganow.co.uk/ said,
May 4, 2013 @ 7:11 pm
This workweek we erudite that neither mammograms
doesn’t just hide Windows Mobile 6.5 — it all but zaps it out of cosmos. http://www.cashwonganow.co.uk/ I can see butterflies easy apply for these loans.
binary options said,
May 21, 2013 @ 3:36 am
For exemplar, the Courtroom could read a measure affirmation at the defendant’s you require to the same thing that everybody else does? what is binary trading From what I Hold observed to the highest degree masses declared acciones, �ndices o materias primas sin tener que inmovilizar elevadas cuant�as de chapiter.
buy iphone 5 said,
May 23, 2013 @ 9:45 pm
An effective A5 fleck in compounding of Apple’s increasing market partake in in mobile advertizing and oecumenical consumer stake in their latest technology is another blessing for the mobile publicizing industriousness. http://www.magic-mobiles.co.uk/ Pay monthly deals would go on your abuse them, even.