> ### ***安裝***
yum install pcre pcre-devel
cd /usr/local/src/
wget http://nginx.org/download/nginx-1.6.3.tar.gz
tar zxvf nginx-1.6.3.tar.gz
cd nginx-1.6.3
./configure --prefix=/usr/local/nginx
make
make install
> 注意:由于nginx要在rewrite時要解析正則表達式,PCRE是正則解析庫
>### **nginx管理**
```
systemctl start nginx.service????#啟動nginx
systemctl stop nginx.service????#結束nginx
systemctl restart nginx.service???#重啟nginx
```
> ### ***nginx目錄***
```
cd /usr/local/nginx
---conf #配置文件
---html #網頁文件
---logs #日志文件
---sbin #主要二進制程序
```
>### ***配置pathinfo格式訪問***
```
location ~ \.php(.*)$ {
root html;
fastgi_pass 127.0.0.1:9000;
fastcgi_index index.php
fastcgi_param SCRIPT_FILENAME $DOCUMENT_ROOT$fastcgi_script_name;
fastcgi_param PATH_INFO $1;
}
```
>### ***隱藏入口文件index.php***
```
Sever {
listen 80;
server_name 域名;
access_log logs/域名.log main;
location / {
root html/網站目錄;
index index.php index.html;
if ( !-e $request_filename) {
rewrite (.*) /index.php/$1;
}
}
}
```
>### ***利用try_fieles隱藏入口文件index.php***
```
Sever {
listen 80;
server_name 域名;
access_log logs/域名.log main;
location / {
root html/網站目錄;
index index.php index.html;
try_files $uri /index.php?$rui
}
}
```
> ### **反射代理**
用nginx做反向代理用proxy_pass
以反向代理為例,nginx不自己處理圖片的相關請求,而是把圖片請求轉發給apache來處理.
執行流程:客戶端->nginx->proxy_pass->apache(再原路返回)
具體配置:
```
location ~ \.(jpg|jpeg|png|gif)$ {
proxy_pass HTTP://IP:port;
}
```
反向代理容易把用戶真正的IP丟失,而是獲得的是代理服務器的IP,要想獲得真正用戶的IP,需要在代理服務器通過設置頭信息字段,把用戶IP傳到后臺服務器.
配置如下:
```
location ~ \.(jpg|jpeg|png|gif)$ {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://ip:port;
}
```
再到apache的日志格式里加上**X-Forwarded-For**,如下:
```
LogFormat "%{X-Forwarded-For}i %1 %u %t \"$r\" %>s %b" common
```
> ### ***負載均衡***
在nginx中做集群與負載均衡步驟都是一樣的,Upstream{}模塊 把多臺服務器加入到一個組中.
然后memcached_pass, fastcgi_pass, proxy_press ====>組
具體配置
1配置upstream(上游)
```
upstream imageserver {
server 192.168.1.205:8080 weight=1 max_fails=2 fail_timeout=30s;
server 192.168.1.206:8081 weight=1 max_fails=2 fail_timeout=30s;
}
```
2下游調用
```
location ~ \.(jpg|jpeg|png|gif)$ {
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://imageserver;
}
```
默認的負載均衡算法:
是設置計數器,輪流請求N臺服務器.
可以安裝第3方模塊,來利用不同參數把請求均衡到不同服務器去.
如基于cookie值區別用戶做負載均衡(nginx sticky模塊).
或基于URI利用一致性哈希算法做均衡(NginxHttpUpstreamConsistenHash模塊).
或基于IP做負載均衡等.
nginx配置網站域名,需要在本地的hosts文件將對應的域名添加進去,例如:
192.168.1.101 www.demo.io