天天看點

Web架構深度優化實戰(LNMP與LAMP)啟用有效期控制root html;

1、隐藏nginx版本号

隐藏前:

$ curl -I localhost

HTTP/1.1 200 OK

Server: nginx/1.6.3

Date: Fri, 16 Oct 2015 15:31:44 GMT

Content-Type: text/html

Content-Length: 18

Last-Modified: Wed, 07 Oct 2015 07:00:17 GMT

Connection: keep-alive

ETag: "5614c301-12"

Accept-Ranges: bytes

http {

server_tokens off; #在http标簽内最前面加入"server_tokens off;"後儲存退出

include mime.types;

/application/nginx/sbin/nginx -s reload #平滑重新開機nginx服務

隐藏後:

Server: nginx

Date: Fri, 16 Oct 2015 15:44:53 GMT

2、隐藏apache版本号

Date: Fri, 16 Oct 2015 15:57:01 GMT

Server: Apache/2.4.16 (Unix) PHP/5.6.12

X-Powered-By: PHP/5.6.12

Content-Type: text/html; charset=gb2312

2.1、打開httpd-default.conf子產品

修改httpd.conf配置檔案的476行,打開httpd-default.conf子產品

$ vi /application/apache/conf/httpd.conf

476 # Include conf/extra/httpd-default.conf

修改為:476 Include conf/extra/httpd-default.conf #取消前面的#注釋

2.2、修改httpd-default.conf檔案

$ vi /application/apache/conf/extra/httpd-default.conf

在64行之後插入"ServerTokens Prod"

64 #

65 ServerTokens Prod #64行之後插入"ServerTokens Prod"

66 ServerSignature Off

$ /application/apache/bin/apachectl graceful #平滑重新開機apache服務

Date: Fri, 16 Oct 2015 15:58:43 GMT

Server: Apache

3、更改掉nginx的預設使用者及使用者組nobody

$ useradd nginx -s /sbin/nologin -M #添加普通使用者nginx,并且禁止它登入系統

更改預設使用者的方法有兩種:

第一種為:

$ grep "user" nginx.conf

user nginx nginx;

第二種為:

$ ./configure --user=nginx --group=nginx --prefix=/application/nginx-1.6.3 --with-http_stub_status_module --with-http_ssl_module

$ ps -ef|grep nginx

root 25404 1 0 Oct16 ? 00:00:00 nginx: master process /application/nginx/sbin/nginx

nginx 26092 25404 0 Oct16 ? 00:00:00 nginx: worker process

4、優化-根據硬體調整nginx子程序數

$ grep "worker_processes" nginx.conf

worker_processes 1; #worker_processes參數的設定可以等于cpu的個數或核數,程序數多一些,起始提供服務時就不會臨時啟動新程序提供服務,減少了系統開銷,提升了服務速度。

檢視linux伺服器的CPU核數:

$ grep "physical id" /proc/cpuinfo

physical id : 0

$ vi nginx.conf

worker_processes 4; #由預設的1調整為4

$ /application/nginx/sbin/nginx -s reload

$ ps -ef|grep nginx|grep -v grep

nginx 26185 25404 0 00:53 ? 00:00:00 nginx: worker process

nginx 26186 25404 0 00:53 ? 00:00:00 nginx: worker process

nginx 26187 25404 0 00:53 ? 00:00:00 nginx: worker process

nginx 26188 25404 0 00:53 ? 00:00:00 nginx: worker process

5、根據cpu核數優化cpu資源配置設定給不同的nginx程序

輸入top後按1,檢視cpu核數

$ grep "worker_cpu_affinity" nginx.conf

worker_cpu_affinity 0001 0010 0100 1000;

#worker_cpu_affinity就是配置nginx程序CPU親和力的參數,即把不同的程序分給不同的CPU處理。這裡0001 0010 0100 1000是掩碼,分别代表1、2、3、4核CPU,由于worker_processes程序數為4,是以上述配置會把每個程序配置設定一核CPU處理,預設情況下程序不會綁定任何CPU,參數位置為main段。

6、優化nginx事件處理模型-連接配接數-打開檔案配置實戰

6.1、nginx事件處理模型

grep events nginx.conf -A 2

在events {

worker_connections 1024;

use epoll; #加入事件處理模型epoll

multi_accept on; #在nginx獲得有關新連接配接的通知後,嘗試接受()盡可能多的連接配接

}

6.2、調整單個程序允許的用戶端最大連接配接數

events {

worker_connections 10240; #修改單個程序允許的用戶端最大連接配接數10240-20480

use epoll;

multi_accept on;

6.3、配置每個程序的最大檔案打開數

worker_rlimit_nofile 65535;

7、優化伺服器名字的hash表大小

如果定義了大量名字,或者定義了非常長的名字,那就需要在http配置子產品中調整server_names_hash_max_size,預設512kb,一般是cpu L1的4-5倍,server_names_hash_bucket_size的預設值可能是32,或者是64,或者是其他值,取決于CPU的緩存行的長度。如果這個值是32,那麼定義“too.long.server.name.nginx.org”作為虛拟機主機名就會失敗,顯示如下錯誤資訊:

could not build the server_names_hash,

you should increase server_names_hash_bucket_size;32

出現這種情況,那就需要設定值擴大:

http{

server_names_hash_max_size 512;

server_names_hash_bucket_size 128;

8、開啟高效檔案傳輸模式

sendfile on;

tcp_nopush on;

#設定連接配接逾時時間,php服務建議短連結,JAVA服務建議長連接配接

keepalive_timeout 60;

tcp_nodelay on;

client_header_timeout 15;

client_body_timeout 15;

send_timeout 15;

#上傳檔案大小控制:

client_max_body_size 10m;

9、fastcgi調優(配合php引擎動态服務)

fastcgi_cache_path /tmp/fcgi_cache levels=2:2 keys_zone=fcgi_cache:512m inactive=1d max_size=40g;

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 128k;

fastcgi_cache fcgi_cache;

fastcgi_cache_valid 200 302 1h;

fastcgi_cache_valid 301 1d;

fastcgi_cache_valid any 1m;

fastcgi_cache_min_uses 1;

10、配置nginx gzip壓縮功能

要壓縮的内容:所有程式(大于1K的純文字檔案:js,css,html,xml,shtml)

不要壓縮的内容:圖檔,視訊,flash

gzip on;

gzip_min_length 1k;

gzip_buffers 4 32k;

gzip_http_version 1.1;

gzip_comp_level 9;

gzip_types text/plain application/x-javascript text/css application/xml;

gzip_vary on;

以上内容放在http标簽裡

火狐浏覽器安裝firebug,yslow兩個元件用來測試nginx的gzip是否配置成功

apache壓縮功能實戰:

a.開啟子產品:

LoadModule deflate_module modules/mod_deflate.so

LoadModule headers_module modules/mod_headers.so

b.httpd.conf中增加

<ifmodule deflate_module>

  DeflateCompressionLevel 9

  AddOutputFilterByType DEFLATE text/html text/plain text/xml \

application/json application/xml   AddOutputFilter DEFLATE js css   AddOutputFilter INCLUDES .shtml .htm .xml .php .html </ifmodule> c.重新開機伺服器

11、配置nginx expires緩存功能

location ~ .*\.(png|js|css|jpg|gif|xml|svg|ico|html)$ { #由nginx處理靜态頁面

root html/ROOT;

expires 30d; #使用expires緩存子產品,緩存到用戶端30天

配置apache expires緩存功能:

Apache要設定檔案緩存時間,要依靠一個叫mod_expires的子產品,但是,我們的機器上,原本是沒有安裝這個子產品的,幸運的是,apache安裝這個子產品很簡單,首先找到源代碼。

比如我們的是2.2.22的版本

cd httpd_2.2.22/modules/metadata

sudo /usr/local/apache2/bin/apxs -c -i -a mod_expires.c

這樣就完成了mod_expores子產品的安裝,下面需要修改一下配置檔案

sudo vim httpd.conf

在裡面加入如下語句

#啟用expires_module子產品

LoadModule expires_module modules/mod_expires.so

<ifModule mod_expires.c>

ExpiresActive On

#現在隻控制swf檔案的緩存期為3天

ExpiresByType application/x-shockwave-flash "access plus 3 days"

</ifModule>

然後重新開機apache

sudo ./apachectl restart

mod_expirse這個子產品,可以配置如下參數:

ExpiresActive on|off #這個選項表示是否啟用有效期控制

ExpiresDefault <code><seconds> #用于設定預設的時間

ExpiresByType type/encoding <code><seconds> #用于對某一種類型的檔案進行控制

有以下幾種寫法(都表示有效期為1個月):

ExpiresDefault "access plus 1 month"

ExpiresDefault M2592000

設定方法:

1.在apache配置檔案httpd.conf中找到

#LoadModule expires_module modules/mod_expires.so 去掉#即可

2.添加配置資訊:

ExpiresActive on #緩存十天

ExpiresBytype text/css "access plus 10 days

ExpiresByType application/x-javascript "access plus 10 days "

ExpiresByType image/jpeg "access plus 10 days "

Expiresbytype image/gif "access plus 10 days "

其他設定類似:

LoadModule expires_module modules/mod_expires.so # 啟用expires_module子產品

ExpiresActive On # 啟用有效期控制

ExpiresByType image/gif A2592000 # GIF有效期為1個月

ExpiresByType text/html M604800 # HTML文檔的有效期是最後修改時刻後的一星期

#以下的含義類似

ExpiresByType text/css "now plus 2 months"

ExpiresByType text/js "now plus 2 days"

ExpiresByType image/jpeg "access plus 2 months"

ExpiresByType image/bmp "access plus 2 months"

ExpiresByType image/x-icon "access plus 2 months"

ExpiresByType image/png "access plus 2 months"

3.重新開機apache即可。

12、nginx防爬蟲實戰及user_agent原理實戰

#全局配置

limit_req_zone $anti_spider zone=anti_spider:10m rate=15r/m;

#某個server中

limit_req zone=anti_spider burst=30 nodelay;

if ($http_user_agent ~* "xxspider|xxbot") {

set $anti_spider $http_user_agent;

超過設定的限定頻率,就會給spider一個503。

上述配置詳細解釋請自行google下,具體的spider/bot名稱請自定義。

nginx中禁止屏蔽網絡爬蟲:

代碼如下:

server {

listen 80;

server_name www.xxx.com;

#charset koi8-r;

#access_log logs/host.access.log main;

#location / {

{

return 403;

13、nginx日志相關優化與安全

Nginx日志切割腳本:

#!/bin/sh

#nginx_logs-cut,2015-09-28,linuxzkq

logs_path=/application/nginx/logs

/bin/mv ${logs_path}/access.log ${logspath}/access$(date +%F -d -1day).log

/application/nginx/sbin/nginx -s reload

不記錄不需要的通路日志:

對于健康檢查或某些圖檔,js,css的日志,一般不需要記錄。

location ~ .*.(png|jpg|gif|ico)$ { #由nginx處理靜态頁面

access_log off;

apache忽略圖檔通路日志的記錄:

<FilesMatch ".(bmp|gif|jpg|swf)">

SetEnv IMAG 1

</FilesMatch>

CustomLog /var/wwwlogs/b.test.com.log combined env=!IMAG

由于負載均衡的健康檢查會造成apache的通路日志被大量寫入,使得通路量無法統計,使用下面的方法可以讓apache不再記錄負載均衡的健康檢查日志。

配置(checkstatus.html):

SetEnvIfRequest_URI "^/checkstatus.html" dontlog

ErrorLog logs/error_log

LogLevel warn

CustomLog"logs/access_log" combined env=!dontlog

Nginx通路日志的權限設定

chown -R www.www /app/logs

chmod -R 700 /app/logs

Nginx與apache目錄及檔案權限設定

為了保證apache與nginx的網站不遭受×××***上傳及修改檔案

1、所有站點目錄的使用者群組都不應該為root;

2、所有目錄權限是755;

3、所有檔案權限是644.

注意:網站服務的使用者不能用root!!!!!

14、nginx站點目錄及檔案URL通路控制

根據擴充名限制程式和檔案通路:

location ~ ^/images/..(php|php5)$

deny all;

location ~ ^/static/..(php|php5|sh|pl|py)$

location ~ ^/static/(attachment|avatar)/..(php|php5|sh|bat)$

Nginx限制來源ip通路指定網站目錄:

location ~ ^/oldboy/{

deny 192.168.1.1;

allow 202.111.12.211;

allow 10.1.1.0/16;

allow 192.168.1.0/24;

Nginx限制使用網站IP通路網站:

法一、#禁止IP通路

server {

listen 80 default_server;

servername ;

法二、也可以把這些流量收集起來,導入到自己的網站,隻要做以下跳轉設定就可以:

listen 80 default_server;

rewrite ^(.*) http://www.mydomain.com permanent;

15、http狀态碼講解及錯誤頁面優化

http狀态碼講解

生産環境常見的HTTP狀态碼清單(List of HTTP status codes)為:

說明:求精不求多,有舍才有得 不一樣的思維不一樣的精彩。

200 - OK,伺服器成功傳回網頁

Standard response for successful HTTP requests.

301 - Moved Permanently(永久跳轉),請求的網頁已永久跳轉到新位置。

This and all future requests should be directed to the given.

403 - Forbidden(禁止通路),伺服器拒絕請求

forbidden request (matches a deny filter) => HTTP 403

The request was a legal request, but the server is refusing to respond to it.

404 - Not Found,伺服器找不到請求的頁面。

The requested resource could not be found but may be available again in the future.

500 - Internal Server Error(内部伺服器錯誤),一般是配置錯誤

internal error in haproxy => HTTP 500

A generic error message, given when no more specific message is suitable.

502 - Bad Gateway(壞的網關),一般是網關伺服器請求後端服務時,後端服務沒有按照http協定正确傳回結果。

the server returned an invalid or incomplete response => HTTP 502

The server was acting as a gateway or proxy and received an invalid response from the upstream server.

503 - Service Unavailable(服務目前不可用),可能因為超載或停機維護。

no server was available to handle the request => HTTP 503

The server is currently unavailable (because it is overloaded or down for maintenance).

504 - Gateway Timeout(網關逾時),一般是網關伺服器請求後端服務時,後端服務沒有在特定的時間内完成服務。

the server failed to reply in time => HTTP 504

The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.

16、tmp目錄使用記憶體檔案系統作為nginx的proxy_cache

介紹

/dev/shm/是一個使用tmpfs檔案系統的裝置,其實就是一個特殊的檔案系統。redhat中預設大小為實體記憶體的一半,使用時不用mkfs格式化。

tmpfs是一種基于記憶體的檔案系統,它和虛拟磁盤ramdisk比較類似,但不完全相同,和ramdisk一樣,tmpfs可以使用RAM,但它也可以使用swap分區來存儲。而且傳統的ramdisk是個塊裝置,要用mkfs來格式化它,才能真正地使用它;而tmpfs是一個檔案系統,并不是塊裝置,隻是安裝它,就可以使用了。tmpfs是最好的基于RAM的檔案系統。

tmpfs是Linux/Unix系統上的一種基于記憶體的虛拟檔案系統。tmpfs可以使用您的記憶體或swap分區來存儲檔案(即它的存儲空間在virtual memory 中, VM由real memory和swap組成)。由此可見,tmpfs主要存儲暫存的檔案。它有如下2個優勢 :

動态檔案系統的大小。

tmpfs 使用VM建的檔案系統,速度當然快。

重新開機後資料丢失。

當删除tmpfs中的檔案時,tmpfs會動态減少檔案系統并釋放VM資源,LINUX中可以把一些程式的臨時檔案放置在tmpfs中,利用tmpfs比硬碟速度快的特點提升系統性能。實際應用中,為應用的特定需求設定此檔案系統,可以提升應用讀寫性能,如将squid 緩存目錄放在/tmp, php session 檔案放在/tmp, socket檔案放在/tmp, 或者使用/tmp作為其它應用的緩存裝置

臨時修改/dev/shm大小:

#mount -o size=1500M -o nr_inodes=1000000 -o noatime,nodiratime -o remount /dev/shm

mount -t tmpfs -o size=20m tmpfs /tmp 臨時挂載使用

開機啟用的配置:

可以在/etc/fstab 中定義其大小

tmpfs /dev/shm tmpfs,defaults,size=512m 0 0

tmpfs /tmp tmpfs defaults,size=25M 0 0

修改後執行mount -o remoount /dev/shm 後生效

mkdir /dev/shm/tmp (/dev/shm/ 下建立的目錄與/tmp綁定, 則/tmp 即使用tmpfs檔案系統)

chmod 1777 /dev/shm/tmp

mount --bind /dev/shm/tmp /tmp

17、禁止資源目錄解析php程式

nginx下禁止目錄執行php的方法則簡單許多,允許設定多個目錄

location ~ ^/(attachments|images)/..(php|php5|PHP|PHP5)$

  {

  deny all;

  }

當web目錄不是根目錄,或者有多個目錄的時候可以是

location ~ ^(/discuz/|/bbs/)/(attachments|images)/..(php|php5|PHP|PHP5)$

Apache下禁止目錄執行php的方法:

<Directory /webroot/attachments>

php_flag engine off

</Directory>

lighthttpd下禁止目錄執行php的方法:

$HTTP["url"] =~ "^/(forumdata|templates|upload|images)/" {

fastcgi.server = ()

18、Nginx的proxy

proxy_redirect off;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

client_max_body_size 50m; #Nginx上傳檔案大小限制(動态應用)

client_body_buffer_size 256k;

proxy_connect_timeout 30;

proxy_send_timeout 30;

proxy_read_timeout 60;

proxy_buffer_size 4k;

proxy_buffers 4 32k;

proxy_busy_buffers_size 64k;

proxy_temp_file_write_size 64k;

proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;

proxy_max_temp_file_size 128m;

proxy_store on;

proxy_store_access user:rw group:rw all:r;

#proxy_temp_path /dev/shm/nginx_proxy;

#proxy_temp_path /data2/nginx_cache;

19、Web服務資源防盜鍊實戰

web服務資源防盜鍊解決辦法:

1.圖檔,視訊上打水印,品牌

2.防火牆控制,根據IP控制

3.防盜鍊(根據referer機制)

apache防盜鍊實戰:

Apache 防盜鍊的第一種實作方法,可以用 Rewrite 實作。首先要确認 Apache 的 rewrite module 可用:能夠控制 Apache httpd.conf 檔案的,打開 httpd.conf,確定有這麼一行配置:

  LoadModule rewrite_module modules/mod_rewrite.so

  然後在相應虛拟主機配置的地方,加入下列代碼:

  ServerName www.php100.com

  # 防盜鍊配置 參數

  RewriteEngine On

  RewriteCond %{HTTP_REFERER} !^http://php100.com/.$ [NC]

  RewriteCond %{HTTP_REFERER} !^http://php100.com$ [NC]

  RewriteCond %{HTTP_REFERER} !^http://www.php100.com/.$ [NC]

  RewriteCond %{HTTP_REFERER} !^http://www.php100.com$ [NC]

  RewriteRule .*.(gif|jpg|swf)$ http://www.php100.com/img/nolink.jpg [R,NC]

 1. php100.com/www.php100.com 表示自己的信任站點。gif|jpg|swf 表示要保護檔案的擴充名(以|分開)。nolink.jpg盜鍊後的重定向頁面/圖檔。用以輸出警示資訊,這張圖檔應該盡可能的小。

gif|jpg|swf 表示要保護的防止被盜連的檔案的擴充名(以|分開)

nolink.jpg 為上述擴充名的資源被盜鍊後的重定向頁面/圖檔,用以輸出警示資訊,這張圖檔應該盡可能的小。

有些使用者使用的是虛拟主機,沒有伺服器的控制權,無法修改 httpd.conf 檔案和重新開機伺服器。那麼請确認你的虛拟主機支援 .htaccess,将上面的配置寫入 .htaccess 檔案,放入根目錄或圖檔所在的目錄即可:

  # 防盜鍊配置

Nginx防盜鍊實戰:

如果您使用的是預設站點,也就是說,您的站點可以直接輸入伺服器IP通路的,使用root登入,修改 /usr/local/nginx/conf/nginx.conf 這個配置檔案。

如果您建立了站點,那麼修改/usr/local/nginx/conf/vhost/你的域名.conf 這個配置檔案,找到:

location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$

expires 30d;

把這一段删掉,修改成:

location ~ .(gif|jpg|png|jpeg)$ {

expires 30d;

valid_referers none blocked .hugao8.com www.hugao8.com m.hugao8.com .baidu.com .google.com;

if ($invalid_referer) {

rewrite ^/ http://ww4.sinaimg.cn/bmiddle/051bbed1gw1egjc4xl7srj20cm08aaa6.jpg;

#return 404;

第一行: location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$

其中“gif|jpg|jpeg|png|bmp|swf”設定防盜鍊檔案類型,自行修改,每個字尾用“|”符号分開!

第三行:valid_referers none blocked *.it300.com it300.com;

就是白名單,允許檔案鍊出的域名白名單,自行修改成您的域名!*.it300.com這個指的是子域名,域名與域名之間使用空格隔開!

第五行:rewrite ^/ http://www.it300.com/static/images/404.jpg;

這個圖檔是盜鍊傳回的圖檔,也就是替換盜鍊網站所有盜鍊的圖檔。這個圖檔要放在沒有設定防盜鍊的網站上,因為防盜鍊的作用,這個圖檔如果也放在防盜鍊網站上就會被當作防盜鍊顯示不出來了,盜鍊者的網站所盜鍊圖檔會顯示X符号。

這樣設定差不多就可以起到防盜鍊作用了,上面說了,這樣并不是徹底地實作真正意義上的防盜鍊!

我們來看第三行:valid_referers none blocked *.it300.com it300.com;

valid_referers 裡多了“none blocked”

我們把“none blocked”删掉,改成

valid_referers *.it300.com it300.com;

nginx徹底地實作真正意義上的防盜鍊完整的代碼應該是這樣的:

valid_referers .hugao8.com www.hugao8.com m.hugao8.com .baidu.com .google.com;

rewrite ^/ http://ww4.sinaimg.cn/bmiddle/051bbed1gw1egjc4xl7srj20cm08aaa6.jpg;

這樣您在浏覽器直接輸入圖檔位址就不會再顯示圖檔出來了,也不可能會再右鍵另存什麼的。

這個是給圖檔防盜鍊設定的防盜鍊傳回圖檔,如果我們是檔案需要防盜鍊下載下傳,把第五行:

rewrite ^/ http://www.it300.com/static/images/404.jpg;

改成一個連結,可以是您主站的連結,比如把第五行改成:

rewrite ^/ http://www.it300.com;

這樣,當别人輸入檔案下載下傳位址,由于防盜鍊下載下傳的作用就會跳轉到您設定的這個連結!

最後,配置檔案設定完成别忘記重新開機nginx生效!

20、Nginx僞靜态的配置解決方案實戰

Nginx Web Server:

rewrite ^([^.])/topic-(.+).html$ $1/portal.php?mod=topic&topic=$2 last;

rewrite ^([^.])/article-([0-9]+)-([0-9]+).html$ $1/portal.php?mod=view&aid=$2&page=$3 last;

rewrite ^([^.])/forum-(\w+)-([0-9]+).html$ $1/forum.php?mod=forumdisplay&fid=$2&page=$3 last;

rewrite ^([^.])/thread-([0-9]+)-([0-9]+)-([0-9]+).html$ $1/forum.php?mod=viewthread&tid=$2&extra=page%3D$4&page=$3 last;

rewrite ^([^.])/group-([0-9]+)-([0-9]+).html$ $1/forum.php?mod=group&fid=$2&page=$3 last;

rewrite ^([^.])/space-(username|uid)-(.+).html$ $1/home.php?mod=space&$2=$3 last;

rewrite ^([^.])/blog-([0-9]+)-([0-9]+).html$ $1/home.php?mod=space&uid=$2&do=blog&id=$3 last;

rewrite ^([^.])/(fid|tid)-([0-9]+).html$ $1/index.php?action=$2&value=$3 last;

rewrite ^([^.])/([a-z]+[a-z0-9_])-([a-z0-9_-]+).html$ $1/plugin.php?id=$2:$3 last;

if (! -e $request_filename) {

return 404;

DISCUZ僞靜态及防盜鍊案例:

listen 80;

servername bbs.etiantian.org;

index index.php index.html index.htm;

root /application/data/bbs;

rewrite ^([^.])/thread-([0-9]+)-([0-9]+)-([0-9]+).html$ $1/forum.php?mod=viewthread&tid=$2&extra=page%3

D$4&page=$3 last;

rewrite ^([^.]*)/([a-z]+[a-z0-9])-([a-z0-9_-]+).html$ $1/plugin.php?id=$2:$3 last;

valid_referers bbs.etiantian.org;

#return 403;

rewrite ^/ http://bbs.etiantian.org/daolian.html;

location ~* .(php|php5)$ {

fastcgi_index index.php;

fastcgi_pass 127.0.0.1:9000;

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

fastcgi_param SCRIPT_NAME $fastcgi_script_name;

include fastcgi_params;

21、Nginx優化之針對錯誤頁面進行優雅顯示

error_page 403 /403.html;

error_page 404 /404.html;

error_page 400 http://oldboy.blog.51cto.com;

#error_page 404 /404.html;

#redirect server error pages to the static page /50x.html

#

error_page 500 502 503 504 /50x.html;

location = /50x.html {

root html;

22、Nginx優化之控制單IP并發連接配接與連接配接速率控制防DOS

1、http {

limit_conn_zone $binary_remote_addr zone=addr:10m;

...

location /download/ {

limit_conn addr 1;

limit_conn_zone $binary_remote_addr zone=perip:10m;

limit_conn_zone $server_name zone=perserver:10m;

limit_conn perip 10;

limit_conn perserver 100;

2、http {

limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

location /search/ {

limit_req zone=one burst=5;

23、Nginx優化之磁盤挂載優化以及Linux核心優化

磁盤挂載優化:

LABEL=/nginx /nginx ext3 defaults,nosuid,noexec,nodev 1

完整的Linux核心優化配置:

net.ipv4.ip_forward = 0

net.ipv4.conf.default.rp_filter = 1

net.ipv4.conf.default.accept_source_route = 0

kernel.sysrq = 0

kernel.core_uses_pid = 1

net.ipv4.tcp_syncookies = 1

kernel.msgmnb = 65536

kernel.msgmax = 65536

kernel.shmmax = 68719476736

kernel.shmall = 4294967296

net.ipv4.tcp_max_tw_buckets = 6000

net.ipv4.tcp_sack = 1

net.ipv4.tcp_window_scaling = 1

net.ipv4.tcp_rmem = 4096 87380 4194304

net.ipv4.tcp_wmem = 4096 16384 4194304

net.core.wmem_default = 8388608

net.core.rmem_default = 8388608

net.core.rmem_max = 16777216

net.core.wmem_max = 16777216

net.core.netdev_max_backlog = 262144

net.core.somaxconn = 262144

net.ipv4.tcp_max_orphans = 3276800

net.ipv4.tcp_max_syn_backlog = 262144

net.ipv4.tcp_timestamps = 0

net.ipv4.tcp_synack_retries = 1

net.ipv4.tcp_syn_retries = 1

net.ipv4.tcp_tw_recycle = 1

net.ipv4.tcp_tw_reuse = 1

net.ipv4.tcp_mem = 94500000 915000000 927000000

net.ipv4.tcp_fin_timeout = 1

net.ipv4.tcp_keepalive_time = 30

net.ipv4.ip_local_port_range = 1024 65000

24、Nginx優化-為特殊Web服務增加使用者身份驗證

$ htpasswd -cb /application/nginx/conf/htpasswd oldboy 123456

Adding password for user oldboy

$ chmod 400 /application/nginx/conf/htpasswd

server_name localhost;

charset utf8;

location / {

root /application/data/phpMyAdmin;

auth_basic "oldboy training";

auth_basic_user_file /application/nginx/conf/htpasswd;

location ~ .(php|php5)?$ {

root /application/data/phpMyAdmin;

fastcgi_pass 127.0.0.1:9000;

fastcgi_index index.php;

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

include fastcgi_params;

25、讓Nginx服務以及Nginx站點運作于監牢模式下

架構師提供的解決方案

使用普通使用者啟動Nginx(監牢模式):

1.給nginx服務降級,使用ynca使用者跑服務,站點也是ynca權限,給開發設定普通賬号和ynca同組。

2.開發重新開機nginx,管理站點程式,檢視日志。項目負責制:責任你來負責。

參考資料:http://down.51cto.com/data/844517

[root@LNMP-07 conf]# useradd ynca

[root@LNMP-07 conf]# ll /home

total 8

drwx------ 2 ynca ynca 4096 Oct 27 00:54 ynca

[root@LNMP-07 conf]# mkdir /home/ynca/www

[root@LNMP-07 conf]# /application/nginx/sbin/nginx -h

nginx version: nginx/1.8.0

Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:

-?,-h : this help

-v : show version and exit

-V : show version and configure options then exit

-t : test configuration and exit

-q : suppress non-error messages during configuration testing

-s signal : send signal to a master process: stop, quit, reopen, reload

-p prefix : set prefix path (default: /application/nginx-1.8.0/)

-c filename : set configuration file (default: conf/nginx.conf)

-g directives : set global directives out of configuration file

[root@LNMP-07 conf]# cp nginx.conf /home/ynca/

[root@LNMP-07 conf]# cd /home/ynca/

[root@LNMP-07 ynca]# ll

total 12

-rw-r--r-- 1 root root 5439 Oct 27 01:15 nginx.conf

drwxr-xr-x 2 root root 4096 Oct 27 00:55 www

[root@LNMP-07 ynca]# mkdir conf

[root@LNMP-07 ynca]# mv nginx.conf conf/

drwxr-xr-x 2 root root 4096 Oct 27 01:16 conf

[root@LNMP-07 ynca]# pwd

/home/ynca

[root@LNMP-07 ynca]# mkdir log

drwxr-xr-x 2 root root 4096 Oct 27 01:17 log

[root@LNMP-07 ynca]# chown -R ynca.ynca

drwxr-xr-x 2 ynca ynca 4096 Oct 27 01:16 conf

drwxr-xr-x 2 ynca ynca 4096 Oct 27 01:17 log

drwxr-xr-x 2 ynca ynca 4096 Oct 27 00:55 www

[root@LNMP-07 ynca]# killall nginx

[root@LNMP-07 ynca]# lsof -i:80

[root@LNMP-07 ynca]# /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf

nginx: [emerg] open() "/home/ynca/conf/mime.types" failed (2: No such file or directory) in /home/ynca/conf/nginx.

[root@LNMP-07 ynca]# ln -s /application/nginx/conf/mime.types /home/ynca/conf/mime.types

nginx: [emerg] open() "/home/ynca/conf/fastcgi_params" failed (2: No such file or directory) in /home/ynca/conf/nginx.conf:71

[root@LNMP-07 ynca]# ln -s /application/nginx/conf/fastcgi_params /home/ynca/conf/fastcgi_params

nginx: [emerg] unexpected end of file, expecting "}" in /home/ynca/conf/nginx.conf:75 #配置檔案上面少一個大括号

[root@LNMP-07 ynca]# ps -ef|grep nginx|grep -v grep

root 1548 1 0 01:39 ? 00:00:00 nginx: master process /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf

ynca 1549 1548 0 01:39 ? 00:00:00 nginx: worker process

[root@LNMP-07 conf]# su - ynca

[ynca@LNMP-07 ~]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf

nginx: [alert] could not open error log file: open() "/application/nginx-1.8.0/logs/error.log" failed (13: Permission denied)

2015/10/27 01:51:29 [warn] 1637#0: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /home/ynca/conf/nginx.conf:2

2015/10/27 01:51:29 [emerg] 1637#0: open() "/home/ynca/log/access_log" failed (13: Permission denied)

[ynca@LNMP-07 ~]$ ll

drwxr-xr-x 2 ynca ynca 4096 Oct 27 01:47 conf

drwxr-xr-x 2 ynca ynca 4096 Oct 27 01:39 log

2015/10/27 02:00:32 [warn] 1729#0: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /home/ynca/conf/nginx.conf:2

nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)

[root@LNMP-07 ynca]# cd /application/nginx/logs

[root@LNMP-07 logs]# ls

access.log access_2015-10-12.log

access_2015-09-27.log access_2015-10-16.log

access_2015-09-28.log access_2015-10-17.log

access_2015-09-29.log access_2015-10-19.log

access_2015-09-30.log access_2015-10-21.log

access_2015-10-02.log access_2015-10-23.log

access_2015-10-05.log access_2015-10-26.log

access_2015-10-06.log error.log

access_2015-10-09.log

[root@LNMP-07 logs]# chown -R ynca.ynca error.log

nginx: [warn] the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /home/ynca/conf/nginx.conf:2

nginx: [emerg] open() "/application/nginx-1.8.0/logs/nginx.pid" failed (13: Permission denied)

[root@LNMP-07 ynca]# vi conf/nginx.conf

user ynca ynca;

worker_processes 1;

error_log /home/ynca/log/error_log;

pid /home/ynca/log/nginx.pid;

[ynca@LNMP-07 ~]$ lsof -i:80

[ynca@LNMP-07 ~]$ ps -ef|grep nginx|grep -v grep

ynca 1765 1 0 02:14 ? 00:00:00 nginx: master process /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf

ynca 1766 1765 0 02:14 ? 00:00:00 nginx: worker process

[ynca@LNMP-07 ~]$ grep -Ev "#|^$" conf/nginx.conf

default_type application/octet-stream;

log_format main '$remote_addr - $remote_user [$time_local] "$request" '

'$status $body_bytes_sent "$http_referer" '

'"$http_user_agent" "$http_x_forwarded_for"';

server_tokens off;

[ynca@LNMP-07 www]$ curl -i localhost:8080

Date: Mon, 26 Oct 2015 18:27:25 GMT

Content-Length: 23

Last-Modified: Mon, 26 Oct 2015 18:24:43 GMT

ETag: "562e6feb-17"

監牢模式_linuxzkq

[ynca@LNMP-07 www]$ killall nginx

[ynca@LNMP-07 www]$ ps -ef|grep nginx|grep -v grep

[ynca@LNMP-07 www]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf

[ynca@LNMP-07 www]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf &>/dev/null

ynca 1797 1 0 02:29 ? 00:00:00 nginx: master process /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf

ynca 1798 1797 0 02:29 ? 00:00:00 nginx: worker process

26、php引擎php.ini參數優化實戰

無論是apache還是nginx,php.ini都是适合的;而php-fpm.conf适合nginx+fcgi的配置。

php.ini配置檔案:

[PHP]

engine = On

short_open_tag = Off

asp_tags = Off

precision = 14

output_buffering = 4096

zlib.output_compression = Off

implicit_flush = Off

unserialize_callback_func =

serialize_precision = 17

disable_functions = #關閉危險函數,在等号後面寫上要禁用的危險函數

disable_classes =

zend.enable_gc = On

expose_php = On #關閉php版本資訊,修改為Off。

max_execution_time = 30 #設定每個腳本運作的最長時間

max_input_time = 60 #每個腳本等待輸入資料的最長時間

memory_limit = 128M #設定每個腳本使用的最大記憶體

error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

display_errors = Off #錯誤資訊控制,建議設定為:Off

display_startup_errors = Off

log_errors = On #錯誤日志,建議打開

error_log = /application/logs/php_errors.log #添加錯誤日志路徑

log_errors_max_len = 1024

ignore_repeated_errors = Off

ignore_repeated_source = Off

report_memleaks = On

track_errors = Off

html_errors = On

variables_order = "GPCS"

request_order = "GP"

register_argc_argv = Off

auto_globals_jit = On

post_max_size = 8M

auto_prepend_file =

auto_append_file =

default_mimetype = "text/html"

default_charset = "UTF-8"

doc_root =

user_dir =

extension_dir = "/application/php5.6.12/lib/php/extensions/no-debug-zts-20131226/"

enable_dl = Off

file_uploads = On

upload_max_filesize = 2M #上傳檔案的最大許可大小

max_file_uploads = 20

allow_url_fopen = On #禁止打開遠端位址,建議設定為Off

allow_url_include = Off

default_socket_timeout = 60

cgi.fix_pathinfo = 0 #防止Nginx檔案類型錯誤解析漏洞

session_save_handler = files #php_session資訊存放類型:memcache

session_save_path = "/tmp" #php_session資訊存放位置:tcp://10.0.0.18:11211

[CLI Server]

cli_server.color = On

[Pdo_mysql]

pdo_mysql.cache_size = 2000

pdo_mysql.default_socket=

[Phar]

[mail function]

SMTP = localhost

smtp_port = 25

mail.add_x_header = On

[SQL]

sql.safe_mode = Off # safe_mode = Off #修改為on,啟用安全模式 safe_mode_gid = Off #使用者組安全

[ODBC]

odbc.allow_persistent = On

odbc.check_persistent = On

odbc.max_persistent = -1

odbc.max_links = -1

odbc.defaultlrl = 4096

odbc.defaultbinmode = 1

[Interbase]

ibase.allow_persistent = 1

ibase.max_persistent = -1

ibase.max_links = -1

ibase.timestampformat = "%Y-%m-%d %H:%M:%S"

ibase.dateformat = "%Y-%m-%d"

ibase.timeformat = "%H:%M:%S"

[MySQL]

mysql.allow_local_infile = On

mysql.allow_persistent = On

mysql.cache_size = 2000

mysql.max_persistent = -1

mysql.max_links = -1

mysql.default_port =

mysql.default_socket =

mysql.default_host =

mysql.default_user =

mysql.default_password =

mysql.connect_timeout = 60

mysql.trace_mode = Off

[MySQLi]

mysqli.max_persistent = -1

mysqli.allow_persistent = On

mysqli.max_links = -1

mysqli.cache_size = 2000

mysqli.default_port = 3306

mysqli.default_socket =

mysqli.default_host =

mysqli.default_user =

mysqli.default_pw =

mysqli.reconnect = Off

[mysqlnd]

mysqlnd.collect_statistics = On

mysqlnd.collect_memory_statistics = Off

[PostgreSQL]

pgsql.allow_persistent = On

pgsql.auto_reset_persistent = Off

pgsql.max_persistent = -1

pgsql.max_links = -1

pgsql.ignore_notice = 0

pgsql.log_notice = 0

[Sybase-CT]

sybct.allow_persistent = On

sybct.max_persistent = -1

sybct.max_links = -1

sybct.min_server_severity = 10

sybct.min_client_severity = 10

[bcmath]

bcmath.scale = 0

[Session]

session.save_handler = files

session.use_strict_mode = 0

session.use_cookies = 1

session.use_only_cookies = 1

session.name = PHPSESSID

session.auto_start = 0

session.cookie_lifetime = 0

session.cookie_path = /

session.cookie_domain =

session.cookie_httponly =

session.serialize_handler = php

session.gc_probability = 1

session.gc_divisor = 1000

session.gc_maxlifetime = 1440

session.referer_check =

session.cache_limiter = nocache

session.cache_expire = 180

session.use_trans_sid = 0

session.hash_function = 0

session.hash_bits_per_character = 5

url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry"

[Tidy]

tidy.clean_output = Off

[soap]

soap.wsdl_cache_enabled=1

soap.wsdl_cache_dir="/tmp"

soap.wsdl_cache_ttl=86400

soap.wsdl_cache_limit = 5

[ldap]

ldap.max_links = -1

[opcache]

extension = imagick.so

extension = memcache.so

zend_extension = opcache.so

extension = pdo_mysql.so

[xcache-common]

extension = xcache.so

[xcache.admin]

xcache.admin.enable_auth = On

xcache.admin.user = "mOo"

xcache.admin.pass = "md5 encrypted password"

[xcache]

xcache.shm_scheme = "mmap"

xcache.size = 128M

xcache.count = 2

xcache.slots = 8K

xcache.ttl = 86400

xcache.gc_interval = 3600

xcache.var_size = 4M

xcache.var_count = 1

xcache.var_slots = 8K

xcache.var_ttl = 0

xcache.var_maxttl = 0

xcache.var_gc_interval = 300

xcache.var_namespace_mode = 0

xcache.var_namespace = ""

xcache.readonly_protection = Off

xcache.mmap_path = "/dev/zero"

xcache.coredump_directory = ""

xcache.coredump_type = 0

xcache.disable_on_crash = Off

xcache.experimental = Off

xcache.cacher = On

xcache.stat = On

xcache.optimizer = Off

[xcache.coverager]

xcache.coverager = Off

xcache.coverager_autostart = On

xcache.coveragedump_directory = ""

register_globals = Off #關閉注冊全局變量,建議設定為Off

magic_quotes_gpc = Off #打開此選項,防止SQL注入,修改為:On

FastCGI優化(php-fpm):

CGI全稱是“公共網關接口”(Common Gateway Interface),HTTP伺服器與你的或其它機器上的程式進行“交談”的一種工具,其程式一般運作在網絡伺服器上。 CGI可以用任何一種語言編寫,隻要這種語言具有标準輸入、輸出和環境變量。如php,perl,tcl等。

php-fpm.conf參數優化實戰(基于php-5.3.27優化):

25 ;pid = run/php-fpm.pid #pid = /app/logs/php-fpm.pid

32 ;error_log = log/php-fpm.log #error_log = /app/logs/php-fpm.log

50 ;log_level = notice #log_level = error

108 ;events.mechanism = epoll #events.mechanism = epoll

175 ;listen.owner = nginx #listen.owner = nginx

176 ;listen.group = nginx #listen.group = nginx

235 pm.max_children = 5 #建議修改為:1024

240 pm.start_servers = 2 #建議修改為:16

245 pm.min_spare_servers = 1 #建議修改為:5

250 pm.max_spare_servers = 3 #建議修改為:20

255 ;pm.process_idle_timeout = 10s; #建議修改為:pm.process_idle_timeout = 15s

261 ;pm.max_requests = 500 #建議修改為:pm.max_requests = 2048

441 ;slowlog = log/$pool.log.slow #取消注釋"分号",slowlog = /app/logs/$pool.log.slow

447 ;request_slowlog_timeout = 0 #修改為request_slowlog_timeout = 10

458 ;rlimit_files = 1024 #修改為rlimit_files = 32768

繼續閱讀