nginx 安装和配置
安装
本文采用 centos 下的 yum 安装 nginx
yum install nginx
配置
- 启动:
/usr/sbin/nginx
- 重启:
/usr/sbin/nginx -s reload
- 停止:
/usr/sbin/nginx -s stop
- 测试配置文件:
/usr/sbin/nginx -t
nginx 配置文件常见结构从外到内依次是 [http] [server] [location] 等等,缺省的继承关系是从外到内,也就是说内层块会自动获取外层块的值作为缺省值。
Server
server {
listen 80; # 指定端口
server_name host1; # 指定ip或域名
root html; # 指定虚拟主机的网页和目录
index index.html index.htm; # 默认首页地址
}
server {
listen 80;
server_name host2;
root /data/www/html;
index index.html index.htm;
}
Tips:但是当 server 超过2个时,建议将不同对虚拟主机的配置放在另一个文件中,然后通过在主配置文件 nginx.conf 加上 include 指令包含进来,更便于管理。
include vhosts/*.conf
Location
每个 url 请求都会对应一个服务,nginx 进行处理转发或者是本地的一个文件路径,或者是其他服务器的一个服务路径。而这个路径的匹配是通过 location 来进行的。我们可以将 server 当做对应一个的域名进行配置,而 location 则实在一个域名下对更精确的路径进行配置。
以上面的例子,可以将 root 和 index 指令放到一个 location 中,name只有匹配到这个 location 时才会访问 root 后面的内容。
location / {
root /data/www/host2;
index index.html index.htm;
}
location 匹配规则
~ 波浪线表示执行一个正则匹配,区分大小写
~* 表示执行一个正则匹配,不区分大小写
^~ ^~表示普通字符匹配,如果该选项匹配,只匹配该选项,不匹配别的选项,一般用来匹配目录
= 进行普通字符精确匹配
匹配例子:
location = / {
# 只匹配"/".
[ configuration A ]
}
location / {
# 匹配任何请求,因为所有请求都是以"/"开始
# 但是更长字符匹配或者正则表达式匹配会优先匹配
[ configuration B ]
}
location ^~ /images/ {
# 匹配任何以 /images/ 开始的请求,并停止匹配 其它location
[ configuration C ]
}
location ~* \.(gif|jpg|jpeg)$ {
# 匹配以 gif, jpg, or jpeg结尾的请求.
# 但是所有 /images/ 目录的请求将由 [Configuration C]处理.
[ configuration D ]
}
请求:
/ -> 符合configuration A
/documents/document.html -> 符合configuration B
/images/1.gif -> 符合configuration C
/documents/1.jpg ->符合 configuration D
静态文件映射
alias
alias 后跟的指定目录是准确的,并且末尾必须加 / 。
location /c/ {
alias /a/;
index index.html;
}
如果访问站点 http://location/c 访问的就是 /a/ 目录下的站点信息(index 指定默认首页)。
root
root 后跟的指定目录是上级目录,并且该上级目录下要含有和 location 后指定的名称的同名目录才行。
location /c/ {
root /a/;
}
这时访问站点http://location/c访问的就是/a/c目录下的站点信息。
如果你需要将这个目录展开,在这个location的末尾加上「autoindex on; 」就可以了
转发
比如我要将所有的请求转移到真正提供服务的一台机器的 8001 端口
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 90;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Credentials 'true';
add_header Access-Control-Allow-Headers 'content-type, authorization, if-none-match, x-requested-with, Content-Range, Content-Length';
}
转发并过滤资源文件
server {
listen 8199;
root /var/www/php;
location /wordpress {
root /var/www/php;
fastcgi_pass 127.0.0.1:8999;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
root /var/www/php;
}
}
自定义返回内容
location / {
default_type text/plain;
return 403;
}
负载均衡
upstream myserver; {
ip_hash;
server 172.16.1.1:8001;
server 172.16.1.2:8002;
server 172.16.1.3;
server 172.16.1.4;
}
location / {
proxy_pass http://myserver;
}