Getting started with nginx configuration

Thanks to fellow Hacker School
er Leah Steinberg
for inspiring this post!

Having intermittently struggled with apache2
configuration files for the majority of my adult life, I find nginx
an absolute joy to set up. I’m completely sincere about that. But, for those who are just getting into Web development, nginx
is just about as much of a struggle as Apache used to be—in fact, probably more so, because there’s less abundant learning material out there on the Internet.

So, here’s an attempt to make that situation just the slightest bit better.

If you don’t already have nginx
installed, I encourage you to follow these directions
for building OpenResty
, an enhanced version of nginx
that enables building entire Web apps within the nginx
process using the beautiful programming language Lua
.

But, from here on, I’m going to assume that you already have a stock version of nginx
installed. Verify that if you run

$ nginx -v

you get some kind of reasonable response, like

nginx version: nginx/1.2.3

Success!

Now, make a file called hi.conf
:

hi.conf

error_log stderr;

pid nginx.pid;

http {

access_log off;

server {

listen 4945;

location / {

return 200;

}

}

}

events {}

I’ve chosen the number 4945 so as to hopefully not conflict with any services that may already be running on your machine for one reason or another. Now, let’s launch nginx
using this configuration file and test it:

$ nginx -p `pwd`/ -c hi.conf
nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (13: Permission denied)
$ telnet localhost 4945
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET / HTTP/1.0

HTTP/1.1 200 OK
Server: nginx/1.2.3
Date: Mon, 07 Apr 2014 01:50:28 GMT
Content-Type: text/plain
Content-Length: 0
Connection: close

Connection closed by foreign host.
$ kill -QUIT `cat nginx.pid`

You’ll have to actually enter the line GET / HTTP/1.0
. HTTP is a protocol intended for humans to be able to read and write, and you may as well take advantage of it! Of course, you could also navigate to http://localhost:4945/
in a browser, but then all you see is a blank page, which is not quite as satisfying (to me, at least) as a 200 OK
on the terminal.

What’s that? You want to actually serve data, and not just a blank page?

hi2.conf

error_log stderr;

pid nginx.pid;

http {

access_log off;

root .;

server {

listen 4945;

location / {

try_files /index.html =404;

}

}

}

events {}

Then just drop an index.html
into the same folder as hi2.conf
and run

$ nginx -p `pwd`/ -c hi2.conf

Now you should be able to load http://localhost:4945/
and see what you wrote in index.html
. Exciting!

责编内容来自:Technical Journal (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合技术 » Getting started with nginx configuration

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录