Nginx动静分离与地址重写

动静分离

代理服务器

upstream static {
server 192.168.188.9:80 weight=1 max_fails=1 fail_timeout=60s;
}
upstream phpserver {
server 192.168.188.11:80 weight=1 max_fails=1 fail_timeout=60s;
}
server {
listen 80;
server_name localhost;
#动态资源加载
location ~ \.(php|jsp)$ {
proxy_pass http://phpserver;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#静态资源加载
location ~ .*\.(html|gif|jpg|png|bmp|swf|css|js)$ {
proxy_pass http://static;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

静态服务器

vim /etc/nginx/conf.d/static.conf
server {
listen 80;
server_name localhost;
location ~ \.(html|jpg|png|js|css|gif|bmp|jpeg) {
root /usr/share/nginx/html;
index index.html index.html;
}
}

动态服务器

server {
listen 80;
server_name localhost;
location ~ \.php$ {
root /home/nginx/html; #指定网站目录
fastcgi_pass 127.0.0.1:9000; #指定访问地址
fastcgi_index index.php; #指定默认文件
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params; #包含nginx常量定义
}
}

Nginx Rewrite

Rewrite 语法

server {
rewrite regex replacement [flag]; 
}

rewrite 常用正则表达式

字符描述
.匹配除换行符以外的任意字符
匹配前面的字符零次或一次
+匹配前面的字符一次或多次
*匹配前面的字符0次或多次
\d匹配一个数字字符。等价于[0-9]
\将后面接着的字符标记为一个特殊字符或一个原义字符或一个向后引用
^匹配字符串的开始
$匹配字符串的结尾
{n}匹配前面的字符n次
{n.}匹配前面的字符n次或更多次
[c]匹配单个字符c
[a-z]匹配a-z小写字母的任意一个

例子

1.hapa.cc/11-22-33/index.html ==> hapa.cc/11/22/33/index.html

rewrite ^/([0-9]+)-([0-9]+)-([0-9]+)(.*)$ /$1/$2/$3$4
 permanent;

2.hapa.cc/index.html ==> hapa.cc/index.php/index.html

rewrite ^/(.*)$ /index.php/$1 last;

发表评论