nginx

Table of Contents

http://nginx.org/

1 站点跳转

从dirlt.com跳转到dirtysalt.info

http {
    server_name dirlt.com;
    rewrite ^ $scheme://dirtysalt.info$request_uri? permanent;
}

这样访问dirlt.com时候,返回HTTP Permanent Redirect

➜~  curl -v -S dirlt.com
-* Rebuilt URL to: dirlt.com/
-*   Trying 139.162.32.139...
-* Connected to dirlt.com (127.0.0.1) port 80 (#0)
> GET / HTTP/1.1
> Host: dirlt.com
> User-Agent: curl/7.43.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.4.6 (Ubuntu)
< Date: Sat, 26 Mar 2016 02:25:22 GMT
< Content-Type: text/html
< Content-Length: 193
< Connection: keep-alive
< Location: http://dirtysalt.info/
<
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.4.6 (Ubuntu)</center>
</body>
</html>

2 支持软链接

http {
    disable_symlinks off;
}

3 正向代理

用nginx做一个http proxy. `resolver*`这个字段是必要的。

server {
    resolver 8.8.8.8;
    resolver_timeout 5s;

    listen 0.0.0.0:64441;

    location / {
        proxy_pass $scheme://$http_host$request_uri;
        proxy_set_header Host $http_host;
        proxy_connect_timeout 5;
    }
}

然后来测试一下

In [10]: import requests

In [11]: r = requests.get('http://www.baidu.com', **{'proxies': {'http': 'http://127.0.0.1:64441'}})

In [12]: r
Out[12]: <Response [200]>

4 请求缓存

可以针对某个路径下面的请求进行缓存。不过我还没有搞清楚缓存规则是怎么样的,默认应该是对query做key.

proxy_cache_path /root/ngx-cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=1d;
server {
  listen 80;
  server_name dirlt.com;
  location / {
      proxy_pass http://127.0.0.1:9000;
  }
  location /download/ {
      proxy_cache my_cache;
      proxy_pass http://127.0.0.1:9000;
  }
}

UPDATE: 这篇 文章 给了一些看上去不错的配置和解释

#设置Web缓存区名称为cache_one,内存缓存空间大小为200MB,1天没有被访问的内容自动清除,硬盘缓存空间大小为30GB。 proxy_cache_path /data0/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;

#如果后端的服务器返回502、504、执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移。 proxy_next_upstream http_502 http_504 error timeout invalid_header;

#对不同的HTTP状态码设置不同的缓存时间 proxy_cache_valid 200 304 12h; #以域名、URI、参数组合成Web缓存的Key值,Nginx根据Key值哈希,存储缓存内容到二级缓存目录内 proxy_cache_key $host$uri$is_args$args;

所以我们可以设置proxy_cache_key字段来选择cache_key.

comments powered by Disqus