nginx 常用的配置


安装请移步这里点击我

1. nginx目录嵌套

1
2
3
4
5
6
http {
.......
include /etc/nginx/conf.d/*.conf;
include sites/*.conf;
}

2. gzip on

加到http模块中, 开启gzip, 注意gzip_types配置得是压缩的资源类型

1
2
3
4
5
6
7
8
9
10
11
12
13
http {
.....
gzip on;
gzip_min_length 1k;
gzip_comp_level 5;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css application/javascript text/javascript application/x-javascript text/xml application/xml application/xml+rss application/json image/x-icon image/png image/jpg image/jpeg application/font-woff;
gzip_vary on;
}

3. 多处理器

1
2
3
4
5
6
7
8
worker_processes 4;
events {
worker_connections 2048;
use epoll;
multi_accept on;
}
worker_rlimit_nofile 100000;

4. 静态文件缓存

1
2
3
4
5
6
7
location ~* \.(?:css|js)$ {
expires 12h;
access_log off;
add_header Cache-Control "public";
proxy_pass http://127.0.0.1:5000;
proxy_redirect off;
}

5. 代理

1
2
3
4
5
6
7
8
9
10
location /
{
proxy_pass http://127.0.0.1:8000;
proxy_pass_header Server;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_set_header Host $http_host;
proxy_redirect off;
}

可以设置超时时间

1
2
3
proxy_connect_timeout 500s;
proxy_read_timeout 500s;
proxy_send_timeout 500s;

6. 静态目录 or 文件

1
2
3
4
5
6
7
8
9
10
location /movies/ {
alias /Volumes/Media/Movies/;
allow all;
}
location = /abc.txt {
alias /data/www/static/abc.txt;
expires 30d;
access_log off;
}

7. 静态站

1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 192.168.1.1:80;
server_name www.abc.com;
client_max_body_size 1M;
access_log logs/blog_access.log;
error_log logs/blog_error.log;
root /data/static_site_dir;
index index.html;
}

8. 服务转发

将收到的服务url/参数等, 原封不动转给另一个服务

1
2
3
4
5
6
7
8
server {
listen 80;
server_name www.xxxx.com;
location ~ ^/(.*)$ {
proxy_pass http://192.168.1.1:80/another/service/$1$is_args$args;
proxy_read_timeout 90;
}
}

9. return

语法:

1
2
return http_code;
return http_code "content";

例如:

1
2
3
4
5
6
7
8
9
10
11
location /api/test/ {
return 403;
}
location /stat/ {
return 204;
}
location /ping/ {
return 200;
}

10. 重定向到 www

1
2
3
4
server {
server_name abc.com;
rewrite ^(.*) http://www.abc.com$1 permanent;
}

11. 允许或者拒绝

访问ip控制

1
2
3
4
location /test/ {
allow 192.168.1.1;
deny all;
}

12. 负载均衡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
http {
upstream test {
server 192.168.1.1:5000;
server 192.168.1.2:5000;
}
}
server {
location / {
proxy_pass test;
}
}

13. 配置文件检查

1
2
3
4
5
6
检查配置文件正确性
service nginx configtest
重新加载配置
service nginx reload
daodaoliang wechat
点击上面图片后用微信扫描,你就能认识一个有趣的灵魂了呀。
Fork me on GitHub