注册 登录  
 加关注
查看详情
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

天马行空

宠辱不惊,闲看庭前花开花落;去留无意,漫观天外云展云舒……

 
 
 

日志

 
 
 
 

Nginx入门  

2011-12-26 10:16:50|  分类: LINUX |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

以下内容为翻译内容,原文地址:http://blog.martinfjordvald.com/2010/07/nginx-primer/

Update: There is now a follow up to this post which deals with the differences between Nginx and Apache, it is recommended reading if you come from Apache:

此文档讲解了nginxApache的一些不同,如果你是apache用户,建议读此文档


Nginx is a fairly simple HTTP server, though there are a few gotchas people need to be aware of before they start using this 8th wonder. The most important is that Nginx is a reverse proxy first and HTTP server second, it does not necessarily have a concept of file, this will change the way we handle our configuration a bit.

Nginx是一个非常简单的http服务器,现在已经有一些人已经认识到Nginx是世界第八奇迹并开始使用它了。最关键的是Nginxreverse proxy(反向代理)优先,以http serverhttp服务器)为其次,文件的概念对于Nginx来说不是必要的,这个特点将影响我们对Nginx的服务的配置。

The first thing you need to know is that the Nginx configuration file is an inheriting-hierarchy, directives specified in a higher block will filter down to lower blocks as a default value, from this follows that we want to specify things in the top most hierarchy whenever possible. Since directives in top blocks filter down as default values it is still possible to override them in most cases.

首先你要知道Nginx配置文件是分层继承结构,在上层的定义将会变为下层的默认值(默认情况)由此我们可以上层指定相关配置,由于上层定义会变为下层同属性的默认值,大多数情况下我们可以在下层指定特定值来覆盖上层的定义

There are 3 hierarchies which are usually referred to as blocks. The HTTP-block, the server-block and the location block of which the hierarchy goes like this: http -> server -> location.

Nginx配置文件内容分为3层继承结构,我们通常称之为块。他们分别是HTTP块,server快,location块。继承关系为HTTP->server->location

Furthermore there are two special locations, an event block and the root which the event block and the http block reside in. Both of these contain only a minor amount of directives. The majority of your time will be spent in the other three blocks.

除上述3块配置外,Nginx还有两个特殊的配置块,分别为event块和root块,其中event块和http块配置文件中是并列的关系,这两块配置仅仅包含了很少一部分配置指令。你大部分的时间将要花费在其余的三块上。

The blocks have a semantic meaning of sorts. The server block is what in Apache would be considered a virtual host. The location block usually referrers to the URI.

Block(块)是按照语义排序的,server block对应apachevirtual host(拟主机),location block 对应apache URI(统一资源描述符)

When using the official wiki the context keyword specifies in which block a directive may be used, as mentioned earlier it is usually recommended to specify the directive in the top most block.

当在某个块中用标准wiki的上下文关键字来表明一个指令是否生效时,就像前面提到的那样,通常建议把这个指令配置在最高层

Virtual Hosts

To begin with the most interesting directives are server_name and root. The former instruct Nginx to use this server block when the HOST header matches the value and the latter defines what to use as root when looking for files.

虚拟主机:

让我们以我们最感兴趣的的指令server_name root 来开始。前者指示Nginx用这个server块当域名头匹配配置的server_name时,(假设本机为服务器,客户端访问时有个http请求报文,此报文中有host域,当Nginx收到http报文请求时会用host域和我们配置的server_name进行匹配,如果匹配成功则此虚拟主机开始工作) 后者指定文件的根目录

This forms the basic of our virtual hosts, an example would be:

这个表格说明了基本的虚拟主机配置

server {   
listen          80; #注释:监听80端口   
server_name     domain.com *.domain.com; # 域名为 domain.com   
rewrite ^       http://www.domain.com$request_uri? permanent;# ? 
}  
server {   
listen          80;   
server_name     www.domain.com;    
index           index.html; #主页   
root            /home/domain.com # 根目录 
}

Here we have two virtual hosts. The first one is hit when domain.com or any subdomain of domain.com except for www is sent as the HOST header by the browser. The reason for this is that Nginx will always choose the most specific match, and if visting www.domain.com then this will match the second block precisely.

这里又两个虚拟主机,当收到域名为domain.com或者任何一个子域名为domain.com的任意请求时(www除外),第一个虚拟主机命中,原因是Nginx总是选择最精确匹配,如果我们访问www.domain.com是第二个虚拟主 机被匹配

This also means you can create a default virtual host to catch all domains without a proper match. Thankfully this is as simple as adding the default_server flag to the listen directive. This causes all request without a HOST header or without another vhost matching the HOST header to be sent to this vhost instead. Examples are requests accessing the IP directly or if someone points a random domain at your IP. The server_name _; which you will see mentioned in a lot of guides means nothing and does nothing. It’s just a bogus invalid HOST header that can be used to make sure nothing ever matches it. You should be able to simply not define a server_name.

这也意味着你可以创建一个默认的虚拟主机捕获所有的和本地配置没有适当匹配的域名,非常感谢,这里有一个非常简单的添加默认虚拟主机标识的方法来进行监听,这些情况发生在所有的请求报文中不包含域名头或者其他虚拟host无法匹配请求的host头而被送到本虚拟主机。比如请求是用IP直接访问或者有人分配一个随机域名给你的IP。在很多指南中都曾提到server_name 为_ 意味着什么也不是而且什么也不做。这只是一个虚假的无效的HOST头为了确保没有任何匹配,你可以不定义server_name

server {  

listen          80 
default_server;   server_name     _;    
index           index.html;   
root            /var/www/default 
}

Locations

If you’re changing over from Apache then this is where you want to pay attention. Nginx typically does not use complicated rewrites – usually we can accomplish the same using a location block.

如果你是从apache转移过来的用户这里有些需要注意的地方。Nginx典型的不用复杂的重写机制,通常我们可以完成相同的事情用一个

location块

The most important things to note are that locations, with the exception of named locations, works on the URI without any query parameters and only one location block will ever be run. This is also why I recommend putting directives in the top most block. A root directive defined in location / will not be available in location /images – unless defined in the server block. I trust you see how defining things in the upper most block will prevent code duplication and headaches.

最重要的事情是注意locations,命名locations是个例外,locations工作在没有任何参数的URI上,而且只有一个location将会被执行。

这也是为什么我建议配置指令在最上层(http层),root指定定义了一个location "/" 将不在有效在location “/images ” 除非定义在server块上。我相信你知道在最尽可能的上层定义来阻止代码混乱和棘手

Another important point about locations is that, as with server_name directive, Nginx will use the most specific location block. There are a few rules for how specific various setups will be, the location directive wiki entry explains this very well, so you should read that first.

另一个重要点是locations,同server_name指令一样,Nginx用了很多特定的location块,这里有一些规则关于如何建立各种各样的locations块,建议阅读链接 location directive wiki entry 。

Let us look at a few examples of how to use a location block. In this example we’ve run a forum on URI /forum/ and have recently moved it to a subdomain. We now need to redirect the old URLs to the new URLs.

让我们看下下面的例子关于如何运用location块,在这个例子中我们运行一个论坛在 URI   /forum/ 上,而且最近又把这个论坛移向了一个子域名,现在我们需要重定向旧的url到新的url 

server {

listen 80 default;  

server_name www.domain.com;  

root /home/domain.com  

# This will match any URI beginning with /forum  

location /forum 

{  

# We capture the URI and redirect it to the subdomain.  

rewrite forum(.*) http://forum.domain.com$1 permanent;  

}

}  


server {  

listen 80;  

server_name forum.domain.com;  

index index.php;  

root /home/domain.com/forum; 

}

The requests for /forum are now successfully transferred to our new subdomain while requests to files not in /forum will be served from our normal /home/domain.com root.

请求到 /forum 现在被我们成功的转换为我们新的子域名,当请求的文件没有在 /forum 中时,我们用我们的基本域名 /home/domain.com 来服务

Handling PHP

PHP – or any backend really ties in well with locations, namely we can define a location block to catch all PHP files.

server {  

listen 80;  

server_name forum.domain.com;  

index index.php;  

root /home/domain.com/forum;  

location ~* \.php$ {  

include fastcgi.conf # I include this in http context, it's just here to show it's required for fastcgi!  

try_files $uri =404;  

fastcgi_pass 127.0.0.1:9000;  

}

}

As said previously, Nginx does not care about files but rather locations and this is why I have a try_files directive inside the php block. This location block matches a URI that ends in .php but it does not care if it’s a file or not. Therefore a request for /forum/avatars/user2.jpg/index.php will be matched and sent to PHP, and if PHP is not configured properly PHP will then execute /forum/avatars/user2.jpg when /forum/avatars/user2.jpg/index.php doesn’t exist. This provides a huge security risk. Do note that this is not a bug in Nginx, it’s the intended behaviour and as such will not be “fixed”.

This can also be fixed on the PHP side by setting cgi.fix_pathinfo=0 in the php.ini file.

The end result, though, is that .php files which exist will be passed via fastcgi to our PHP processes running on port 9000.

The Finishing Touch – SEF URLs

This setup works, but all the craze these days is to have search engine friendly URLs for SEO reasons. Usually this involves quite a few rewrites, but with Nginx we can do it with just one line, provided the backend script is written in a sane way.

server {  

listen 80;  

server_name forum.domain.com;  

index index.php;  

root /home/domain.com/forum;  

location / {  

try_files $uri $uri/ /index.php;  

}  

location ~* \.php$ {  

include fastcgi.conf # I include this in http context, it's just here to show it's required for fastcgi!  

try_files $uri =404;  

fastcgi_pass 127.0.0.1:9000;  

} }

 

Did you notice the change? It’s minimal really. The one try files line means that it will first try accessing the full URI, which means that a static file request will end here. Secondly it will try the full URI plus a slash, thus looking for a directory. Finally, if none of these are found it will send the request to /index.php and perform a new location match, which will of course hit our PHP location and fastcgi_pass the request. PHP will then have the full URI in $_SERVER['PATH_INFO']. Simple, elegant and easy to understand.

Debugging Requests

Nginx is a complicated server at times, thankfully we have an excellent error log available to us to help figure out where things are going wrong. If you check the error log directive in the wiki you will notice that it takes a second argument. This will let you define how much information is output by nginx. A value of info will give you sufficient info to debug most issues.

Further Reading

The official nginx wiki is an invaluable resource, a good way to expand your knowledge about Nginx is to read the directives and variables in the Core module. Also see the full config example to get an idea of a more complex configuration file.

Related posts:

  1. Nginx Primer 2: From Apache to Nginx
  2. “No input file specified” With PHP and Nginx
  3. Nginx Taking Funding: A Deal with the Devil?
  4. File Uploading With PHP & Nginx
  5. Implementing Full-Page caching with Nginx and PHP
  评论这张
 
阅读(700)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018