标签归档:Nginx

CentOS安装Nginx

Official Red Hat/CentOS packages

To add NGINX yum repository, create a file named /etc/yum.repos.d/nginx.repo and paste one of the configurations below:

CentOS:

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

RHEL:

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/rhel/$releasever/$basearch/
gpgcheck=0
enabled=1

Due to differences between how CentOS, RHEL, and Scientific Linux populate the $releasever variable, it is necessary to manually replace $releasever with either 5 (for 5.x) or 6 (for 6.x), depending upon your OS version.

use

yum info nginx

to show the information about Nginx

[root@localhost ~]# yum info nginx
Loaded plugins: fastestmirror
nginx | 2.9 kB 00:00:00 
nginx/7/x86_64/primary_db | 14 kB 00:00:22 
Loading mirror speeds from cached hostfile
 * base: mirrors.linode.com
 * extras: mirrors.linode.com
 * updates: mirrors.linode.com
Available Packages
Name : nginx
Arch : x86_64
Epoch : 1
Version : 1.10.1
Release : 1.el7.ngx
Size : 640 k
Repo : nginx/7/x86_64
Summary : High performance web server
URL : http://nginx.org/
License : 2-clause BSD-like license
Description : nginx [engine x] is an HTTP and reverse proxy server, as well as
 : a mail proxy server.

Then

yum install nginx

参考:https://www.nginx.com/resources/wiki/start/topics/tutorials/install/

站点服务器迁移,从Apache2到Nginx

在工作过程中逐渐体会到了Nginx在静态页面处理上的优势,决定将Server由之前的Apache转向Nginx。相对于Apache,Nginx使用更低的内存就能够实现更高的并发,这对于我使用的低配置服务器自然是非常合适的。

迁移过程十分简单,无非就是停止Apache服务,安装Nginx,将站点加入Nginx的Server中即可,网上相关资料很多,这里就不赘述了。(当然还有php-fpm的配置)

迁移后的结果还是十分满意的,下面配上压测的结果

20160127191809

上图是改成Nginx后的压测结果,RPS已经打到了58/s,要知道之前使用Apache服务器的时候,执行ab -c 1000 -n 100直接就宕机了。压测过程中的负载也极低,在0.01以下。

20160127192333

这个数据在之前使用Apache时可能超过20,这样的高值往往意味着服务器宕机。

总之,对于服务器配置不高,主要处理静态内容或者是追求高并发低负载这些要求的话,使用Nginx将是非常明智的选择。

个人的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;
}