月度归档:2015年12月

个人的Nginx配置参考

Nginx服务器具有强大的性能,在处理静态文件上具有先天的优势。同时,Nginx可以通过配置使得其更适合自己的网站。

在使用了半年后,总结一下自己的Nginx配置信息,也给自己以后使用留下一些参考。

以下是我的Nginx配置目录的树状图:

└─ Nignx
     ├──── conf.d
     │      └── htpasswd
     ├──── sites-available
     ├──── sites-enabled
     │      ├── zivers.com
     │      ├──    https.zivers.com
     │      ├──    wiki.zivers.com
     │      ├── mail.zivers.com
     │      └── direct_ip
     ├──── global
     │      ├── restrictions.conf
     │      ├──    wordpress.conf
     │      └──    wordpress-wp-super-cache.conf      
     └──── nginx.conf

以下为具体的配置:

Nginx

nginx.conf

user www-data www-data;
worker_processes 1;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;


    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    fastcgi_connect_timeout 300s;
    fastcgi_send_timeout 300s;
    fastcgi_read_timeout 300s;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 8 128k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_intercept_errors on;

    gzip on;
    gzip_disable "msie6";

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    client_max_body_size 13m;
    index index.php index.html index.htm;
    upstream php {
        server unix:/var/run/php5-fpm.sock; 
    }

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

WordPress

sites-enabled/https.zivers.com

server {
    # listens both on IPv4 and IPv6 on 443 and enables HTTPS and HTTP/2 support.
    # HTTP/2 is available in nginx 1.9.5 and above.
    # listen *:443 ssl http2;
    # listen [::]:443 ssl http2;
    listen 443 ssl;

    # indicate locations of SSL key files.
    ssl_certificate /etc/letsencrypt/live/zivers.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/zivers.com/privkey.pem;
    # ssl_dhparam /srv/www/master/ssl/dhparam.pem;

    # indicate the server name
    server_name zivers.com www.zivers.com;

    # Enable HSTS. This forces SSL on clients that respect it, most modern browsers. The includeSubDomains flag is optional.
    # add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";

    # Set caches, protocols, and accepted ciphers. This config will merit an A+ SSL Labs score as of Sept 2015.
    # ssl_session_cache shared:SSL:20m;
    # ssl_session_timeout 10m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5';

    return 301 https://www.zivers.com$request_uri;

}

sites-enabled/zivers.com

server {
    listen 80;
    server_name zivers.com;
    rewrite ^/(.*)$ https://www.zivers.com/$1 permanent;
}
server {
    listen 80;

    root /var/www/zivers.com;
    index index.php;
    server_name www.zivers.com;

    error_log  /var/log/nginx/zivers_error.log error;
    access_log /var/log/nginx/zivers_access.log;


    include global/restrictions.conf;
    include global/wordpress.conf;    

}

global/wordpress.conf

# WordPress single site rules.
# Designed to be included in any server {} block.

# This order might seem weird - this is attempted to match last if rules below fail.
# http://wiki.nginx.org/HttpCoreModule
# location / {
#    try_files $uri $uri/ /index.php?$args;
# }

# Add trailing slash to */wp-admin requests.
rewrite /wp-admin$ $scheme://$host$uri/ permanent;

# Directives to send expires headers and turn off 404 error logging.
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;
}

# Uncomment one of the lines below for the appropriate caching plugin (if used).
include global/wordpress-wp-super-cache.conf;
#include global/wordpress-w3-total-cache.conf;

# Pass all .php files onto a php-fpm/php-fcgi server.
location ~ [^/]\.php(/|$) {
    fastcgi_split_path_info ^(.+?\.php)(/.*)$;
    if (!-f $document_root$fastcgi_script_name) {
        return 404;
    }
    # This is a robust solution for path info security issue and works with "cgi.fix_pathinfo = 1" in /etc/php.ini (default)

    include fastcgi_params;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#    fastcgi_intercept_errors on;
    fastcgi_pass php;
}

global/restrictions.conf

# Global restrictions configuration file.
# Designed to be included in any server {} block.</p>
location = /favicon.ico {
    log_not_found off;
    access_log off;
}

location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}

# Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
# Keep logging the requests to parse later (or to pass to firewall utilities such as fail2ban)
location ~ /\. {
    deny all;
}

# Deny access to any files with a .php extension in the uploads directory
# Works in sub-directory installs and also in multisite network
# Keep logging the requests to parse later (or to pass to firewall utilities such as fail2ban)
location ~* /(?:uploads|files)/.*\.php$ {
    deny all;
}

global/wordpress-wp-super-cache.conf

# WP Super Cache rules.
# Designed to be included from a 'wordpress-ms-...' configuration file.

set $cache_uri $request_uri;

# POST requests and urls with a query string should always go to PHP
if ($request_method = POST) {
        set $cache_uri 'null cache';
}

if ($query_string != "") {
        set $cache_uri 'null cache';
}   

# Don't cache uris containing the following segments
if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
        set $cache_uri 'null cache';
}   

# Don't use the cache for logged in users or recent commenters
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in") {
        set $cache_uri 'null cache';
}

# START MOBILE
# Mobile browsers section to server them non-cached version. COMMENTED by default as most modern wordpress themes including twenty-eleven are responsive. Uncomment config lines in this section if you want to use a plugin like WP-Touch
# if ($http_x_wap_profile) {
#        set $cache_uri 'null cache';
#}

#if ($http_profile) {
#        set $cache_uri 'null cache';
#}

#if ($http_user_agent ~* (2.0\ MMP|240x320|400X240|AvantGo|BlackBerry|Blazer|Cellphone|Danger|DoCoMo|Elaine/3.0|EudoraWeb|Googlebot-Mobile|hiptop|IEMobile|KYOCERA/WX310K|LG/U990|MIDP-2.|MMEF20|MOT-V|NetFront|Newt|Nintendo\ Wii|Nitro|Nokia|Opera\ Mini|Palm|PlayStation\ Portable|portalmmm|Proxinet|ProxiNet|SHARP-TQ-GX10|SHG-i900|Small|SonyEricsson|Symbian\ OS|SymbianOS|TS21i-10|UP.Browser|UP.Link|webOS|Windows\ CE|WinWAP|YahooSeeker/M1A1-R2D2|iPhone|iPod|Android|BlackBerry9530|LG-TU915\ Obigo|LGE\ VX|webOS|Nokia5800)) {
 #       set $cache_uri 'null cache';
#}

#if ($http_user_agent ~* (w3c\ |w3c-|acs-|alav|alca|amoi|audi|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-|dang|doco|eric|hipt|htc_|inno|ipaq|ipod|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-|lg/u|maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|palm|pana|pant|phil|play|port|prox|qwap|sage|sams|sany|sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo|teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|wap-|wapa|wapi|wapp|wapr|webc|winw|winw|xda\ |xda-)) {
  #      set $cache_uri 'null cache';
#}
#END MOBILE

# Use cached or actual file if they exists, otherwise pass request to WordPress
location / {
        try_files /wp-content/cache/supercache/$http_host/$cache_uri/index.html $uri $uri/ /index.php?$args ;
}

Direct IP Block

sites-enabled/direct_ip

server {
    listen 80 default_server;
    server_name _;
    return 444;
}

Others

sites-enabled/mail.zivers.com

server {
    listen 80 ;

    root /var/www/mail.zivers.com/;
    index index.html index.htm index.php;

    server_name mail.zivers.com;

    error_log  /var/log/nginx/mail_error.log error;
    access_log /var/log/nginx/mail_access.log;

    location / {
        try_files $uri $uri/ =404;
    }
    location /phpmyadmin {
        try_files $uri $uri/ =404;
    }

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
                return 404;
        }
        include fastcgi_params;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        #fastcgi_intercept_errors on;
        fastcgi_pass php;
    }

}

site-enabled/wiki.zivers.com

server {
    listen 80;
    server_name wiki.zivers.com;

    root  /srv/www/gollum;

    error_log  /var/log/nginx/wiki_error.log error;
    access_log /var/log/nginx/wiki_access.log;

    location / {
        auth_basic "Restricted";
        auth_basic_user_file   conf.d/htpasswd;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://localhost:4567;
    }

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    error_page 500 502 503 504 /500.html;
    client_max_body_size 1M;
    keepalive_timeout 10;
}

LNMP环境快速部署

最近连续部署了几次LNMP环境,这里总结一下,以便下次能够快速部署。

在本文中,将配置基本的LNMP环境并附加了sysv-rc-conf,Redis等工具。

Ubuntu配置:

启用root账号:

~$ sudo passwd root
~$ su root

配置环境配置:sudo

sudo apt-get update
sudo apt-get install sysv-rc-conf

安装Nginx:

sudo apt-get install nginx
sudo sysv-rc-conf nginx on

删除sites-enabled下的default配置,新建配置localhost

cd /etc/nginx/sites-enabled
sudo rm default
cd /etc/nginx/sites-available
sudo vim localhost

localhost配置

server {
        listen 80 default_server;
        root /srv/www;

        index index.php index.html;

        server_name _;

        location / {
               try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                include fastcgi_params;
        }
}

完成Nginx的配置:

sudo mkdir /srv/www
sudo touch /srv/www/info.php
sudo echo "<?php phpinfo(); ?>" >> /srv/www/info.php
cd /etc/nginx/sites-enabled/
sudo ln -s ../sites-available/localhost localhost
service nginx restart

安装php:

sudo apt-get install php5 php5-common php5-fpm php5-mcrypt php5-curl php5-cli php5-mysql php5-gd php5-intl php5-xsl
sysv-rc-conf php5-fpm on

修改php.ini的配置:

sudo vim /etc/php5/fpm/php.ini
memory_limit = 256M

重启php5-fpm生效。

测试php和Nginx配置是否正确:

在浏览器中访问:

http://localhost/info.php

安装MySQL:

sudo apt-get install mysql-server
sudo sysv-rc-conf mysql on

配置MySQL

sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf

# bind-address 127.0.0.1

以root用户进入MySQL的Shell,创建新用户并授权:

mysql -u root -p

> create user 'db_user'@'%' identified by 'db_password';
> grant all on *.* to 'db_user'@'%';
> flush privileges

安装phpMyAdmin

sudo apt-get install phpmyadmin

在安装过程中需要选择服务器,有apache和lighttpd两个选项,因为我们是Nginx,所以这里直接Tab到<ok>,回车继续。然后输入数据库密码,等待安装结束。

安装完成后建立连接:

sudo ln -s /usr/share/phpmyadmin /srv/www

此时,通过以下地址即可访问phpMyAdmin:

http://localhost/phpmyadmin

LNMP配置完成。

* 安装Redis

这里需要安装Redis和Redis的php扩展:

sudo apt-get install redis-server
sudo apt-get install php5-redis

 

使用sysv-rc-conf工具管理Ubuntu启动服务

Ubuntu继承了Unix/Linux标准的启动级别(Run Level)概念,将其分为7级。虽然这样能够更加精确的控制启动项的级别,但是在运维过程中,需要调整某项服务的启动行为就变得十分繁琐。以下内容取自Wikipedia:

运行级别(Runlevel)指的是Unix或者Linux等类Unix操作系统下不同的运行模式。运行级别通常分为7等,分别是从0到6,但如果必要的话也可以更多。

例如在大多数linux操作系统下一共有如下6个典型的运行级别:

0 停机
1 单用户,Does not configure network interfaces, start daemons, or allow non-root logins
2 多用户,无网络连接 Does not configure network interfaces or start daemons
3 多用户,启动网络连接 Starts the system normally.
4 用户自定义
5 多用户带图形界面
6 重启
在Debian Linux中2-5这四个运行级别都集中在级别2上。这个级别也是系统预设的正常运行级别。

在Ubuntu中,几个启动级别分别存储于/etc目录下的7个rc*.d文件中

在Debian Linux中,下列路径对应不同的运行级别。当系统启动时,通过其中的脚本文件来启动相应的服务。

/etc/rc0.d Run level 0
/etc/rc1.d Run level 1
/etc/rc2.d Run level 2
/etc/rc3.d Run level 3
/etc/rc4.d Run level 4
/etc/rc5.d Run level 5
/etc/rc6.d Run level 6

在rc*.d文件中,以K开头的服务代表开机时在此级别不启动,S开头的服务代表开机在此级别启动。如果需要关闭某项服务的开机启动,例如Apache2,则需要将所有七个文件下的服务名从S开头改成K开头,而且需要将后面的数字进行修改。这样修改启动项便十分复杂。

所以,我们使用更方便的 sysv-rc-conf 工具进行管理。

对于需要开机启动的服务,例如Apache2,只需执行sysv-rc-conf apache2 on即可。

若要更加准确的修改启动项,直接运行sysv-rc-conf,将出现一个简单的交互界面,在此可以修改启动级别。

20160130192155

说明:用X标志标识的即为Enable状态,例如上图中的Nginx就在2、3、4、5四个级别上启动。移动光标到对应项目,按空格取消项目启动。按q保存退出。

Redis缓存不起效的一种可能原因解决

今天公司新上了一个网站,但是页面缓存却没有起作用,每次刷新页面在页面中的随机内容都再次随机而不是被缓存下来。显然,原因是Redis挂了。

先看一眼

~# redis-cli
127.0.0.1:6379> keys *
1) "cgi"

进入了Redis的bash,但是查询发现只有一条记录。说明Redis并没有Down,但是确实是出现了问题。

127.0.0.1:6379> set 0 1
(error) MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error. 

随意插入一条key:value记录,报错,错误内容为“not able to persist on disk”,无法更改磁盘内容。

考虑到可能是Redis配置问题,先看下Redis的配置文件

~# vi /etc/redis/6379.conf

找到了以下内容

# The filename where to dump the DB
dbfilename dump.rdb

# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir /var/redis/6379

Redis将缓存数据库存在到了/var/redis/6379/dump.rdb这个文件内。顺势找到这个文件并查看权限

~# cd /var/redis/6379
~# ll
-rw-r--r-- 1 root root   18 Nov 13 03:25 dump.rdb

没有修改权限。看来原因找到了,Redis无法修改缓存数据库,导致内容没有写入。修改权限为777,重启Redis。

root@localhost:/var/redis/6379# chmod 777 dump.rdb 
root@localhost:/var/redis/6379# ll
-rwxrwxrwx 1 root root   18 Nov 13 03:25 dump.rdb*
root@localhost:/var/redis/6379# ps aux|grep redis
root      3392  0.1  0.0  39648  3156 ?        Ssl  Nov13  21:00 /usr/local/bin/redis-server *:6379              
root     29174  0.0  0.0   9392  2096 pts/3    R+   09:25   0:00 grep --color=auto redis
root@localhost:/var/redis/6379# kill -9 3392
root@localhost:/var/redis/6379# /usr/local/bin/redis-server /etc/redis/6379.conf

这里有一段插曲,因为尝试使用service redis restart失败,考虑到可能Redis并没有被写入Service中,所以就查询了以下进程然后重启。再次刷新页面,测试Redis是否工作。

root@localhost:/var/redis/6379# redis-cli
127.0.0.1:6379> set 1 1
OK
127.0.0.1:6379> keys *
  1) "<CONTENTS>"
  ...
  8) "<CONTENTS>"

显示正常,Redis已经可用。

附:

后来去init.d下查找了一下,发现Redis是有service,只不过名字是redis_6379

~# cd /etc/init.d/
~# ll
-rwxr-xr-x  1 root root 1098 Nov  4 09:45 redis_6379*
~# service redis_6379 restart
Please use start or stop as first argument
~# service redis_6379 stop
Stopping ...
Redis stopped
~# service redis_6379 start
Starting Redis server...