分类 Nginx 下的文章

Nginx开启fastcgi_cache缓存加速

user  www www;

worker_processes auto;

error_log  /home/wwwlogs/nginx_error.log  crit;

pid        /usr/local/nginx/logs/nginx.pid;

#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;

events
    {
        use epoll;
        worker_connections 65535;
        multi_accept on;
    }
    
http
    {
        include       mime.types;
        default_type  application/octet-stream;

        server_names_hash_bucket_size 128;
        client_header_buffer_size 32k;
        large_client_header_buffers 4 32k;
        client_max_body_size 50m;

        sendfile   on;
        tcp_nopush on;
        keepalive_timeout 60;
        tcp_nodelay on;
        
        gzip on;
        gzip_min_length  1k;
        gzip_buffers     4 16k;
        gzip_http_version 1.1;
        gzip_comp_level 2;
        gzip_types     text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/xml+rss;
        gzip_vary on;
        gzip_proxied   expired no-cache no-store private auth;
        gzip_disable   "MSIE [1-6]\.";

        #limit_conn_zone $binary_remote_addr zone=perip:10m;
        ##If enable limit_conn_zone,add "limit_conn perip 10;" to server section.

        server_tokens off;
        access_log off;

        fastcgi_connect_timeout 300;
        fastcgi_send_timeout 300;
        fastcgi_read_timeout 300;
        fastcgi_buffer_size 64k;
        fastcgi_buffers 4 64k;
        fastcgi_busy_buffers_size 128k;
        fastcgi_temp_file_write_size 256k;
        
        #cache设置
        fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
        fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=fastcgi_cache:32m inactive=10m max_size=50g;
        fastcgi_cache_key "$scheme$request_method$host$request_uri";
        fastcgi_cache_methods GET HEAD;
        fastcgi_cache fastcgi_cache; 
        fastcgi_cache_valid 200 302 1h; 
        fastcgi_cache_valid 301 1d; 
        fastcgi_cache_valid any 10m;
        fastcgi_cache_use_stale error timeout invalid_header http_500;
        #忽略一切nocache申明,避免不缓存伪静态等
        fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
        fastcgi_ignore_client_abort on;
        #发送头信息到客户端 - 一般是浏览器
        add_header X-Cache-CFC "$upstream_cache_status - $upstream_response_time";

server
    {
        listen 80 default_server;
        #listen [::]:80 default_server ipv6only=on;
        server_name www.2dan.cc;
        index index.html index.htm index.php;
        root  /home/wwwroot/default;

        #error_page   404   /404.html;
        include enable-php.conf;

        location /nginx_status
        {
            stub_status on;
            access_log   off;
        }
        set $skip_cache 0;
        #post访问不缓存
        if ($request_method = POST) {
            set $skip_cache 1;
        }   
        #动态查询不缓存
        if ($query_string != "") {
            set $skip_cache 1;
        }   
        #后台等特定页面不缓存
        if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") {
            set $skip_cache 1;
        }   
        #对登录用户、评论过的用户不展示缓存
        if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
            set $skip_cache 1;
        }
        location ~ [^/]\.php(/|$) {
            try_files $uri =404;
            fastcgi_pass  unix:/tmp/php-cgi.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
            #新增的缓存规则
            fastcgi_cache_bypass $skip_cache;
            fastcgi_no_cache $skip_cache;
        }
        access_log  /home/wwwlogs/access.log;
    }
}

bash: nginx: command not found

nginx 安装目录 /usr/local/nginx/sbin/nginx

在用户目录下 touch .bash_profile ,添加PATH:

PATH=$PATH:/usr/local/nginx/sbin
export PATH

刷新 source .bash_profile

此时 which nginx 可以输出正确的路径。

免费SSL安全证书Let's Encrypt安装使用及Nginx配置

letsencrypt.png
Let's Encrypt CA 项目由非赢利组织 Internet Security Research Group (ISRG) 运营,由Mozilla、思科、Akamai、IdenTrust、EFF 和密歇根大学等组织发起,向网站自动签发和管理免费SSL证书,以加速互联网从 HTTP 向 HTTPS 过渡。

Let's Encrypt 官方网站:https://letsencrypt.org/
Let's Encrypt 项目主页:https://github.com/letsencrypt/letsencrypt

1、安装Let's Encrypt脚本依赖环境

# CentOS 6
yum install centos-release-SCL && yum update
yum install python27
scl enable python27 bash
yum install python27-python-devel python27-python-setuptools python27-python-tools python27-python-virtualenv
yum install augeas-libs dialog gcc libffi-devel openssl-devel python-devel
yum install python-argparse

# CentOS 7
yum install -y git python27
yum install -y augeas-libs dialog gcc libffi-devel openssl-devel python-devel
yum install python-argparse

2、获取Let's Encrypt并生成SSL证书

yum install git-core
git clone https://github.com/letsencrypt/letsencrypt.git
cd letsencrypt
./letsencrypt-auto certonly --email [email protected] -d www.2dan.cc --webroot -w /home/html --agree-tos

如果多个域名可以加多个-d 域名

- 阅读剩余部分 -

利用Nginx的accesskey和secure_link模块实现防盗链

之前文章Nginx搭建flv mp4流媒体服务器中介绍了通过referer判断实现简单的防盗链,弊端是来源容易被伪造。今天介绍一下更高级的防盗链策略。

软件版本:
nginx-1.22.1
nginx-accesskey-2.0.3

增加编译参数 --with-http_secure_link_module --add-module=/root/nginx-accesskey-2.0.3 并重新编译 nginx

./configure --prefix=/usr/local/nginx --add-module=../nginx_mod_h264_streaming-2.2.7 --with-pcre=../pcre-8.41 --with-zlib=../zlib-1.2.11 --user=www --group=www --with-http_flv_module --with-http_stub_status_module --with-threads --with-http_ssl_module --with-http_secure_link_module --add-module=/root/nginx-accesskey-2.0.3 --with-openssl-opt='enable-tls1_3 enable-weak-ssl-ciphers' --with-http_v2_module --with-http_mp4_module --with-cc-opt='-O3'
make && make install

完整的配置文件示例:

user www www;

worker_processes auto;

error_log  /usr/local/nginx/logs/error.log  crit;

pid /usr/local/nginx/logs/nginx.pid;

events {
    use epoll;
    worker_connections 65535;
}

http {
    include mime.types;
    default_type application/octet-stream;
    
    server_names_hash_bucket_size 128;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
    client_max_body_size 150m;
    tcp_nopush on;
    tcp_nodelay on;
    
    sendfile on;
    
    keepalive_timeout 65;
    limit_conn_zone $binary_remote_addr zone=perip:10m; #容器共使用10M的内存来应对IP传输开销
    
    gzip on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types       text/plain application/x-javascript text/css application/xml;
    gzip_vary on;
    gzip_proxied        expired no-cache no-store private auth;
    gzip_disable        "MSIE [1-6]\.";
    
    server {
        listen 80;
        listen 443 ssl http2 fastopen=3 reuseport;
        server_name 2dan.cc; 
        root /home/html;
        limit_conn perip 3; #限制每个IP同一时间只能发起3个连接
        limit_rate_after 10m; #在视频文件下载10M以后开始限速
        limit_rate 100k; #速度限制为100K
        charset utf-8;
        
        ssl on;
        ssl_certificate      2dan.cc_bundle.crt;
        ssl_certificate_key  2dan.cc.key;
        ssl_session_timeout  5m;
        ssl_protocols  TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
        ssl_ciphers TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:TLS13-AES-128-GCM-SHA256:TLS13-AES-128-CCM-8-SHA256:TLS13-AES-128-CCM-SHA256:EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+ECDSA+AES128:EECDH+aRSA+AES128:RSA+AES128:EECDH+ECDSA+AES256:EECDH+aRSA+AES256:RSA+AES256:EECDH+ECDSA+3DES:EECDH+aRSA+3DES:RSA+3DES:!MD5;
        ssl_prefer_server_ciphers on;
        error_page 497 https://$host$uri; #http重定向到https 

        location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        }
        
        location ~ \.(mp4|m3u8)$ {
                 mp4;
                 valid_referers none blocked *.2dan.cc; #防盗链授权
            if ($invalid_referer) {
                  return 403;
            }
            if (!-e $request_filename) {rewrite ^/(.*)/(.*)/(.*)/(.*) /$4?key=$1&st=$2&e=$3 last;}
            accesskey on;
            accesskey_hashmethod md5;
            accesskey_arg "key";
            accesskey_signature "mypass$REMOTE_ADDR";
            secure_link $arg_st,$arg_e;
            secure_link_md5 mypass$arg_e;
            if ( $secure_link = "" ) {
                return 402;
            }
            if ( $secure_link = "0" ) {
                return 405;
            }
        }
        access_log off;
    }
}

结合PHP实现自动跳转到真实链接地址

- 阅读剩余部分 -

Rewrite重写时的优先级问题

现象:
把apache换成了nginx后,发现网站的播放页面明明生成了静态html文件,可是访问的确是伪静态文件(静态和伪静态路径一样)。

解决方法:

1、apache
在.htacess 文件中第二行增加:

RewriteCond %{REQUEST_FILENAME} !-f

其它常用的参数:

-d 是否是一个目录

-f 是否是一个文件

-s 是否是一个正常的有大小的文件

-l 是否是一个快捷方式

-x 是否是一个具有执行权限的文件

-F 检查TestString是还是是一个合法的文件

-U 检查TestString是否是一个合法的URL

2、nginx

if (!-f $request_filename){
rewrite ^/(.*)/(.*)/(.*)-(.*)$ /index.php?s=/vod-play-id-$2-sid-$3-pid-$4-listname-$1;
}

判断文件存在则优先访问文件,不存在则访问rewrite路径