|
#自动补全"/"
if (-d $request_filename)
{
rewrite ^/(.*)([^/])$ http://$host/$1$2/ last;
}
#实现网页动静态分离
location /
{
root /data0/htdocs/tomcat;
index index.html index.htm;
if (!-f $request_filename)
{
rewrite ^/([a-zA-Z]+).html /$1.jsp last;
proxy_pass http://tomcat;
break;
}
}
#对网站的图片、Flash、JavaScript、CSS、静态HTML、进行web缓存
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css|html|shtml)$
{
#如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到 upstream负载均衡池中的另一台服务器,实现故障转移。
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_cache cache_one;
#对不同的HTTP状态码设置不同的缓存时间
proxy_cache_valid 200 10m;
proxy_cache_valid 304 1m;
proxy_cache_valid 301 302 1h;
proxy_cache_valid any 1m;
#以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存 内容到二级缓存目录内
proxy_cache_key $host$uri$is_args$args;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://tomcat;
}
#用于清除缓存,假设一个URL为http://tomcat.hxqm.com/docs/appdev/index.html,通过访问http://tomcat.hxqm.com/purge/docs/appdev/index.html就可以清除该URL的缓存。
location ~ /purge(/.*)
{
allow 127.0.0.1;
allow 192.168.81.0/24;
deny all;
proxy_cache_purge cache_one $host$1$is_args$args;
}
#扩展名以.php、.jsp、.cgi结尾的动态应用程序不缓存。
location ~ .*\.(php|jsp|cgi)?$
{
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://tomcat;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 1h;
}
location /svn {
root /home/lg/www/;
index index.html;
}
location = /favicon.ico {
try_files $uri $uri/favicon.ico /home/lg/www/favicon.ico =404;
}
location /share {
root /home/lg/Downloads;
}
# Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store(Mac).
location ~ /\. {
deny all;
}
location ^~ /packages {
root /home/lg/Downloads/1software;
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
allowall;
}
location ^~ /Music {
root /home/lg/;
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
allowall;
}
location ^~ /Videos {
root /home/lg/;
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
allowall;
}
location ^~ /html5 {
root /home/lg/workspace/nodejs/;
index index.html index.htm;
}
location ^~ /NginxStatus {
stub_statuson;
access_logon;
#auth_basic'NginxStatus';
#auth_basic_user_fileconf.d/htpasswd
}
location = /50x.html {
root /usr/share/nginx/html;
}
location = /404.html {
root /usr/share/nginx/html;
}
location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
access_log off;
log_not_found off;
expires max;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 24h;
log_not_found off;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
#静态文件,nginx自己处理
location ~ ^/(images|javascript|js|css|flash|media|static)/ {
root /var/www/virtual/htdocs;
#过期30天,静态文件不怎么更新,过期可以设大一点,如果频繁更新,则可以设置得小一点。
expires 30d;
}#设定查看Nginx状态的地址
location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file conf/htpasswd;
}
Nginx的Rewrite规则编写实例
1.当访问的文件和目录不存在时,重定向到某个php文件
if( !-e $request_filename )
{
rewrite ^/(.*)$ index.php last;
}
2.目录对换 /123456/xxxx ====> /xxxx?id=123456
rewrite ^/(\d+)/(.+)/ /$2?id=$1 last;
3.如果客户端使用的是IE浏览器,则重定向到/ie目录下
if( $http_user_agent ~ MSIE)
{
rewrite ^(.*)$ /ie/$1 break;
}
4.禁止访问多个目录
location ~ ^/(cron|templates)/
{
deny all;
break;
}
5.禁止访问以/data开头的文件
location ~ ^/data
{
deny all;
}
6.禁止访问以.sh,.flv,.mp3为文件后缀名的文件
location ~ .*\.(sh|flv|mp3)$
{
return 403;
}
7.设置某些类型文件的浏览器缓存时间
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)$
{
expires 1h;
}
8.给favicon.ico和robots.txt设置过期时间;
这里为favicon.ico为99天,robots.txt为7天并不记录404错误日志
location ~(favicon.ico) {
log_not_found off;
expires 99d;
break;
}
location ~(robots.txt) {
log_not_found off;
expires 7d;
break;
}
9.设定某个文件的过期时间;这里为600秒,并不记录访问日志
location ^~ /html/scripts/loadhead_1.js {
access_log off;
root /opt/lampp/htdocs/web;
expires 600;
break;
}
10.文件反盗链并设置过期时间
这里的return 412 为自定义的http状态码,默认为403,方便找出正确的盗链的请求
“rewrite ^/ http://img.tiyee.net/leech.gif;”显示一张防盗链图片
“access_log off;”不记录访问日志,减轻压力
“expires 3d”所有文件3天的浏览器缓存
location ~* ^.+\.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ {
valid_referers none blocked *.c1gstudio.com *.c1gstudio.net localhost 208.97.167.194;
if ($invalid_referer) {
rewrite ^/ http://img.tiyee.net/leech.gif;
return 412;
break;
}
access_log off;
root /opt/lampp/htdocs/web;
expires 3d;
break;
}
11.只充许固定ip访问网站,并加上密码
root /opt/htdocs/www;
allow 208.97.167.194;
allow 222.33.1.2;
allow 231.152.49.4;
deny all;
auth_basic “C1G_ADMIN”;
auth_basic_user_file htpasswd;
12将多级目录下的文件转成一个文件,增强seo效果
/job-123-456-789.html 指向/job/123/456/789.html
rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /job/$1/$2/jobshow_$3.html last;
13.将根目录下某个文件夹指向2级目录
如/shanghaijob/ 指向 /area/shanghai/
如果你将last改成permanent,那么浏览器地址栏显是/location/shanghai/
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
上面例子有个问题是访问/shanghai 时将不会匹配
rewrite ^/([0-9a-z]+)job$ /area/$1/ last;
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
这样/shanghai 也可以访问了,但页面中的相对链接无法使用,
如./list_1.html真实地址是/area/shanghia/list_1.html会变成/list_1.html,导至无法访问。
那我加上自动跳转也是不行咯
(-d $request_filename)它有个条件是必需为真实目录,而我的rewrite不是的,所以没有效果
if (-d $request_filename){
rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
知道原因后就好办了,让我手动跳转吧
rewrite ^/([0-9a-z]+)job$ /$1job/ permanent;
rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;
14.文件和目录不存在的时候重定向:
if (!-e $request_filename) {
proxy_pass http://127.0.0.1;
}
Nginx和Apache的Rewrite规则实例对比
1.一般简单的Nginx和Apache规则的区别不大,基本能够完全兼容,例如:
Apache: RewriteRule ^/abc/$ /web/abc.php [L]
Nginx: rewrite ^/abc/$ /web/abc.php last ;
我们可以看出来只要把Apache的RewriteRule改为Nginx的rewrite,Apache的[L]改为last 即可。
如果将Apache的规则改为Nginx规则后,用命令Nginx -t 检查发现错误,则我们可以尝试给条件加上引号,例如:
rewrite “^/([0-9]{5}).html$” /x.php?id=$1 last;
2.Apache和Nginx的Rewrite规则在URL跳转时有细微区别:
Apache: RewriteRule ^/html/([a-zA-Z]+)/.*$ /$1/ [R=301,L]
Nginx: rewrite ^/html/([a-zA-Z]+)/.*$ http://$host/$1/ premanent ;
我们可以看到在Nginx的跳转中,我们需要加上http://$host,这是在Nginx中强烈要求的。
3.下面是一些Apache和Nginx规则的对应关系
a.Apache的RewriteCond对应Nginx的if
b.Apache的RewriteRule对应Nginx的rewrite
c.Apache的[R]对应Nginx的redirect
d.Apache的[P]对应Nginx的last
e.Apache的[R,L]对应Nginx的redirect
f.Apache的[P,L]对应Nginx的last
g.Apache的[PT,L]对应Nginx的last
例如:允许指定的域名访问本站,其他的域名一律转向www.tiyee.net
Apache:
RewriteCond %{HTTP_HOST} !^(.*?)\.aaa\.com$ [NC]
RewriteCond %{HTTP_HOST} !^localhost$
RewriteCond %{HTTP_HOST} !^192\.168\.0\.(.*?)$
RewriteRule ^/(.*)$ http://www.tiyee.net [R,L]
Nginx:
if( $host ~* ^(.*)\.aaa\.com$ )
{
set $allowHost ‘1’;
}
if( $host ~* ^localhost )
{
set $allowHost ‘1’;
}
if( $host ~* ^192\.168\.1\.(.*?)$ )
{
set $allowHost ‘1’;
}
if( $allowHost !~ ‘1’ )
{
rewrite ^/(.*)$ http://www.tiyee.net redirect ;
}
《附录:nginx全局变量》
经常需要配置Nginx ,其中有许多以 $ 开头的变量,经常需要查阅nginx 所支持的变量。Nginx支持的http变量实现在 ngx_http_variables.c 的 ngx_http_core_variables存储实现
ngx_http_core_variables
static ngx_http_variable_t ngx_http_core_variables[] = {
{ ngx_string("http_host"), NULL, ngx_http_variable_header,
offsetof(ngx_http_request_t, headers_in.host), 0, 0 },
{ ngx_string("http_user_agent"), NULL, ngx_http_variable_header,
offsetof(ngx_http_request_t, headers_in.user_agent), 0, 0 },
{ ngx_string("http_referer"), NULL, ngx_http_variable_header,
offsetof(ngx_http_request_t, headers_in.referer), 0, 0 },
#if (NGX_HTTP_GZIP)
{ ngx_string("http_via"), NULL, ngx_http_variable_header,
offsetof(ngx_http_request_t, headers_in.via), 0, 0 },
#endif
#if (NGX_HTTP_PROXY || NGX_HTTP_REALIP)
{ ngx_string("http_x_forwarded_for"), NULL, ngx_http_variable_header,
offsetof(ngx_http_request_t, headers_in.x_forwarded_for), 0, 0 },
#endif
{ ngx_string("http_cookie"), NULL, ngx_http_variable_headers,
offsetof(ngx_http_request_t, headers_in.cookies), 0, 0 },
{ ngx_string("content_length"), NULL, ngx_http_variable_header,
offsetof(ngx_http_request_t, headers_in.content_length), 0, 0 },
{ ngx_string("content_type"), NULL, ngx_http_variable_header,
offsetof(ngx_http_request_t, headers_in.content_type), 0, 0 },
{ ngx_string("host"), NULL, ngx_http_variable_host, 0, 0, 0 },
{ ngx_string("binary_remote_addr"), NULL,
ngx_http_variable_binary_remote_addr, 0, 0, 0 },
{ ngx_string("remote_addr"), NULL, ngx_http_variable_remote_addr, 0, 0, 0 },
{ ngx_string("remote_port"), NULL, ngx_http_variable_remote_port, 0, 0, 0 },
{ ngx_string("server_addr"), NULL, ngx_http_variable_server_addr, 0, 0, 0 },
{ ngx_string("server_port"), NULL, ngx_http_variable_server_port, 0, 0, 0 },
{ ngx_string("server_protocol"), NULL, ngx_http_variable_request,
offsetof(ngx_http_request_t, http_protocol), 0, 0 },
{ ngx_string("scheme"), NULL, ngx_http_variable_scheme, 0, 0, 0 },
{ ngx_string("request_uri"), NULL, ngx_http_variable_request,
offsetof(ngx_http_request_t, unparsed_uri), 0, 0 },
{ ngx_string("uri"), NULL, ngx_http_variable_request,
offsetof(ngx_http_request_t, uri),
NGX_HTTP_VAR_NOCACHEABLE, 0 },
{ ngx_string("document_uri"), NULL, ngx_http_variable_request,
offsetof(ngx_http_request_t, uri),
NGX_HTTP_VAR_NOCACHEABLE, 0 },
{ ngx_string("request"), NULL, ngx_http_variable_request_line, 0, 0, 0 },
{ ngx_string("document_root"), NULL,
ngx_http_variable_document_root, 0, NGX_HTTP_VAR_NOCACHEABLE, 0 },
{ ngx_string("realpath_root"), NULL,
ngx_http_variable_realpath_root, 0, NGX_HTTP_VAR_NOCACHEABLE, 0 },
{ ngx_string("query_string"), NULL, ngx_http_variable_request,
offsetof(ngx_http_request_t, args),
NGX_HTTP_VAR_NOCACHEABLE, 0 },
{ ngx_string("args"),
ngx_http_variable_request_set,
ngx_http_variable_request,
offsetof(ngx_http_request_t, args),
NGX_HTTP_VAR_CHANGEABLE|NGX_HTTP_VAR_NOCACHEABLE, 0 },
{ ngx_string("is_args"), NULL, ngx_http_variable_is_args,
0, NGX_HTTP_VAR_NOCACHEABLE, 0 },
{ ngx_string("request_filename"), NULL,
ngx_http_variable_request_filename, 0,
NGX_HTTP_VAR_NOCACHEABLE, 0 },
{ ngx_string("server_name"), NULL, ngx_http_variable_server_name, 0, 0, 0 },
{ ngx_string("request_method"), NULL,
ngx_http_variable_request_method, 0,
NGX_HTTP_VAR_NOCACHEABLE, 0 },
{ ngx_string("remote_user"), NULL, ngx_http_variable_remote_user, 0, 0, 0 },
{ ngx_string("body_bytes_sent"), NULL, ngx_http_variable_body_bytes_sent,
0, 0, 0 },
{ ngx_string("request_completion"), NULL,
ngx_http_variable_request_completion,
0, 0, 0 },
{ ngx_string("request_body"), NULL,
ngx_http_variable_request_body,
0, 0, 0 },
{ ngx_string("request_body_file"), NULL,
ngx_http_variable_request_body_file,
0, 0, 0 },
{ ngx_string("sent_http_content_type"), NULL,
ngx_http_variable_sent_content_type, 0, 0, 0 },
{ ngx_string("sent_http_content_length"), NULL,
ngx_http_variable_sent_content_length, 0, 0, 0 },
{ ngx_string("sent_http_location"), NULL,
ngx_http_variable_sent_location, 0, 0, 0 },
{ ngx_string("sent_http_last_modified"), NULL,
ngx_http_variable_sent_last_modified, 0, 0, 0 },
{ ngx_string("sent_http_connection"), NULL,
ngx_http_variable_sent_connection, 0, 0, 0 },
{ ngx_string("sent_http_keep_alive"), NULL,
ngx_http_variable_sent_keep_alive, 0, 0, 0 },
{ ngx_string("sent_http_transfer_encoding"), NULL,
ngx_http_variable_sent_transfer_encoding, 0, 0, 0 },
{ ngx_string("sent_http_cache_control"), NULL, ngx_http_variable_headers,
offsetof(ngx_http_request_t, headers_out.cache_control), 0, 0 },
{ ngx_string("limit_rate"), ngx_http_variable_request_set_size,
ngx_http_variable_request_get_size,
offsetof(ngx_http_request_t, limit_rate),
NGX_HTTP_VAR_CHANGEABLE|NGX_HTTP_VAR_NOCACHEABLE, 0 },
{ ngx_string("nginx_version"), NULL, ngx_http_variable_nginx_version,
0, 0, 0 },
{ ngx_string("hostname"), NULL, ngx_http_variable_hostname,
0, 0, 0 },
{ ngx_string("pid"), NULL, ngx_http_variable_pid,
0, 0, 0 },
{ ngx_null_string, NULL, NULL, 0, 0, 0 }
};
把这些变量提取下,总结如下:
- arg_PARAMETER #这个变量包含GET请求中,如果有变量PARAMETER时的值。
- args #这个变量等于请求行中(GET请求)的参数,例如foo=123&bar=blahblah;
- binary_remote_addr #二进制的客户地址。
- body_bytes_sent #响应时送出的body字节数数量。即使连接中断,这个数据也是精确的。
- content_length #请求头中的Content-length字段。
- content_type #请求头中的Content-Type字段。
- cookie_COOKIE #cookie COOKIE变量的值
- document_root #当前请求在root指令中指定的值。
- document_uri #与
- uri相同。
- host #请求主机头字段,否则为服务器名称。
- hostname #Set to the machine’s hostname as returned by gethostname
- http_HEADER
- is_args #如果有
- args参数,这个变量等于”?”,否则等于”",空值。
- http_user_agent #客户端agent信息
- http_cookie #客户端cookie信息
- limit_rate #这个变量可以限制连接速率。
- query_string #与
- args相同。
- request_body_file #客户端请求主体信息的临时文件名。
- request_method #客户端请求的动作,通常为GET或POST。
- remote_addr #客户端的IP地址。
- remote_port #客户端的端口。
- remote_user #已经经过Auth Basic Module验证的用户名。
- request_completion #如果请求结束,设置为OK. 当请求未结束或如果该请求不是请求链串的最后一个时,为空(Empty)。
- request_method #GET或POST
- request_filename #当前请求的文件路径,由root或alias指令与URI请求生成。
- request_uri #包含请求参数的原始URI,不包含主机名,如:”/foo/bar.php?arg=baz”。不能修改。
- scheme #HTTP方法(如http,https)。
- server_protocol #请求使用的协议,通常是HTTP/1.0或HTTP/1.1。
- server_addr #服务器地址,在完成一次系统调用后可以确定这个值。
- server_name #服务器名称。
- server_port #请求到达服务器的端口号。
本人实际应用:
#Nginx所有用户和组,window下不指定
user root;
#工作的进程数量(通常等于CPU数量或者2倍于CPU)
worker_processes 4;
#错误日志存放路径
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#指定pid 存放文件
pid logs/nginx.pid
events {
#使用网络IO模型linux建议epoll,freeBSD建议采用kqueue,window下不指定。
use epoll;
worker_connections 2048;
}
http {
include mime.types;
default_type application/octet-stream;
#定义日志格式
#log_format main '$remote_addr-$remote_user [$time_local],"$request"'
'$status $body_bytes_sent "$http_regerer"'
'"$http_user_agent""$http_x_forwarded_for"';
#access_log logs/access.log main;
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m.
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
#keepalive_time 0;
keepalive_time 65;
#是否压缩
include gzip.conf;
#proxy_temp_path和proxy_cache_path必须指定同一路径
proxy_temp_path /usr/local/www/proxy_temp_dir;
proxy_cache_path /usr/local/www/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30;
#服务器集群为star
upstream star{
server 10.126.252.65:8081 weight=10 max_fails=2 fail_timeout=30s;
server 10.126.252.65:8082 weight=1 max_fails=2 fail_timeout=30s;
}
#服务器集群为wyf
upstream wyf{
server 10.126.252.65:8083 weight=1 max_fails=2 fail_timeout=30s;
}
server{
listen 80;
server_name star;
access_log logs/star.log;
server_name_in_redirect on;
location /text1{
include proxy.conf;
proxy_pass http://star;
}
location /text2{
include proxy.conf;
proxy_pass http://star;
#root html;
#index index.html index.htm index.jsp;
}
#动态页面
location ~.*\.(jsp|jspx|do|action)?${
include proxy.conf;
proxy_pass http://star;
}
#静态页面
location ~.*\.(html|htm)?${
#指定tomcat1发布路径
root /home/ecsp/soft/ace/Nginx/tomcat1/webapps;
include proxy.conf;
#这里的if如果root找不到路径,制定到tomcat中查找。
#if(!-f $request_filename){
#proxy_pass http://star;
#break;
#}
#失效3小时
expires 3h;
}
#图片格式分离
location ~.*\.(gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)?${
#指定tomcat1发布路径
root /home/ecsp/soft/ace/Nginx/tomcat1/webapps;
include proxy.conf;
#if(!-f $request_filename){
#proxy_pass http://star;
#break;
#}
#失效30天
expires 30d;
}
#js|css分离
location ~.*\.(js|css)?${
#指定tomcat1发布路径
root /home/ecsp/soft/ace/Nginx/tomcat1/webapps;
include proxy.conf;
#if(!-f $request_filename){
#proxy_pass http://star;
#break;
#}
expires 3h;
}
#错误页面
error_page 500 502 503 504 404 /50x.html;
location =50x.html{
root html;
}
}
#这个server还没有实现,先放在这里。(能不能放2个server,以后研究)
#第二个server
server{
listen 80;
server_name wyf;
access_log logs/wyf.log;
server_name_in_redirect on;
#这里的location /test3可以写到第一个server中。
location /text3{
include proxy.conf;
proxy_pass http://wyf;
}
} |
|