1. 程式人生 > >Web架構深度優化實戰(LNMP與LAMP)

Web架構深度優化實戰(LNMP與LAMP)

磁盤 host mkfs格式化 sina zend error_log 路徑 linux中 etc

好久沒寫博客了,正好最近有點時間,在整理之前的文檔時,給翻出來了,索性整理好順邊分享給大家,老鳥勿噴,菜鳥借鑒吧!

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服務
隱藏後:
$ curl -I localhost
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 16 Oct 2015 15:44:53 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
2、隱藏apache版本號
$ curl -I localhost
HTTP/1.1 200 OK
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服務
隱藏後:
$ curl -I localhost
HTTP/1.1 200 OK
Date: Fri, 16 Oct 2015 15:58:43 GMT
Server: Apache
X-Powered-By: PHP/5.6.12
Content-Type: text/html; charset=gb2312
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
user nginx nginx;
worker_processes 4; #由默認的1調整為4
$ /application/nginx/sbin/nginx -s reload
$ ps -ef|grep nginx|grep -v grep
root 25404 1 0 Oct16 ? 00:00:00 nginx: master process /application/nginx/sbin/nginx
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 / {

root html;

    #    index  index.html index.htm;
    #}
    if ($http_user_agent ~* "qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Feedfetcher-Google|Yahoo! Slurp|Yahoo! Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot|ia_archiver|Tomato Bot") 

{
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)$
{
deny all;
}
location ~ ^/static/(attachment|avatar)/..(php|php5|sh|bat)$
{
deny all;
}

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;
deny all;
}

Nginx限制使用網站IP訪問網站:
法一、#禁止IP訪問
server {
listen 80 default_server;
servername ;
return 403;
}
法二、也可以把這些流量收集起來,導入到自己的網站,只要做以下跳轉設置就可以:
server {
listen 80 default_server;
servername ;
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個優勢 :

  1. 動態文件系統的大小。
  2. tmpfs 使用VM建的文件系統,速度當然快。
  3. 重啟後數據丟失。

當刪除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)$
  {
  deny all;
  }

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盜鏈後的重定向頁面/圖片。用以輸出警示信息,這張圖片應該盡可能的小。

  1. gif|jpg|swf 表示要保護的防止被盜連的文件的擴展名(以|分開)
  2. nolink.jpg 為上述擴展名的資源被盜鏈後的重定向頁面/圖片,用以輸出警示信息,這張圖片應該盡可能的小。
    有些用戶使用的是虛擬主機,沒有服務器的控制權,無法修改 httpd.conf 文件和重啟服務器。那麽請確認你的虛擬主機支持 .htaccess,將上面的配置寫入 .htaccess 文件,放入根目錄或圖片所在的目錄即可:

  # 防盜鏈配置
  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]

   通過判斷referer變量的值,判斷圖片或資源的引用是否合法,只有在設定範圍內的 referer,才能訪問指定的資源,從而實現了防盜鏈(Anti-Leech)的目的。需要指出的是:不是所有的用戶代理(瀏覽器)都會設置 referer 變量,而且有的還可以手工修改 referer,也就是說,referer 是可以被偽造的。本文所講的,只是一種簡單的防護手段。當然,應付一般的盜鏈也足夠了。

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徹底地實現真正意義上的防盜鏈完整的代碼應該是這樣的:
location ~ .(gif|jpg|png|jpeg)$ {
expires 30d;
valid_referers
.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;
}
}

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

第五行:rewrite ^/ http://www.it300.com/static/images/404.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偽靜態及防盜鏈案例:
server {
listen 80;
servername bbs.etiantian.org;
index index.php index.html index.htm;
root /application/data/bbs;
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%3
D$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;
}
location ~
.(gif|jpg|png|jpeg)$ {
valid_referers bbs.etiantian.org;
if ($invalid_referer) {
#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;
...
server {
...
location /download/ {
limit_conn addr 1;
}

limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
location /download/ {
limit_conn addr 1;
}

limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;
server {
...
limit_conn perip 10;
limit_conn perserver 100;
}

2、http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
...
server {
...
location /search/ {
limit_req zone=one burst=5;
}

23、Nginx優化之磁盤掛載優化以及Linux內核優化
磁盤掛載優化:
LABEL=/nginx /nginx ext3 defaults,nosuid,noexec,nodev 1
Linux內核優化:
待更新。。。

24、Nginx優化-為特殊Web服務增加用戶身份驗證
$ htpasswd -cb /application/nginx/conf/htpasswd oldboy 123456
Adding password for user oldboy
$ chmod 400 /application/nginx/conf/htpasswd

server {
listen 80;
server_name localhost;
charset utf8;
location / {
root /application/data/phpMyAdmin;
index index.php index.html index.htm;
auth_basic "oldboy training";
auth_basic_user_file /application/nginx/conf/htpasswd;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
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/
[root@LNMP-07 ynca]# ll
total 8
drwxr-xr-x 2 root root 4096 Oct 27 01:16 conf
drwxr-xr-x 2 root root 4096 Oct 27 00:55 www
[root@LNMP-07 ynca]# pwd
/home/ynca
[root@LNMP-07 ynca]# mkdir log
[root@LNMP-07 ynca]# ll
total 12
drwxr-xr-x 2 root root 4096 Oct 27 01:16 conf
drwxr-xr-x 2 root root 4096 Oct 27 01:17 log
drwxr-xr-x 2 root root 4096 Oct 27 00:55 www
[root@LNMP-07 ynca]# chown -R ynca.ynca
[root@LNMP-07 ynca]# ll
total 12
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
[root@LNMP-07 ynca]# /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
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
[root@LNMP-07 ynca]# /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
nginx: [emerg] unexpected end of file, expecting "}" in /home/ynca/conf/nginx.conf:75 #配置文件上面少一個大括號
[root@LNMP-07 ynca]# /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
[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
total 12
drwxr-xr-x 2 ynca ynca 4096 Oct 27 01:47 conf
drwxr-xr-x 2 ynca ynca 4096 Oct 27 01:39 log
drwxr-xr-x 2 ynca ynca 4096 Oct 27 00:55 www
[root@LNMP-07 ynca]# chown -R ynca.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 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
[ynca@LNMP-07 ~]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
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 ~]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
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
[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
user ynca ynca;
worker_processes 1;
error_log /home/ynca/log/error_log;
pid /home/ynca/log/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
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"‘;
sendfile on;
tcp_nopush on;
keepalive_timeout 60;
server_tokens off;
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;

server {
    listen       8080;
    server_name  www.etiantian.com;
    location / {
        root   /home/ynca/www;
        index  index.php index.html index.htm;
    }
    location ~ \.php$ {
        root           /home/ynca/www;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
     access_log    /home/ynca/log/access_log; 
 }

}
[ynca@LNMP-07 www]$ curl -i localhost:8080
HTTP/1.1 200 OK
Server: nginx
Date: Mon, 26 Oct 2015 18:27:25 GMT
Content-Type: text/html
Content-Length: 23
Last-Modified: Mon, 26 Oct 2015 18:24:43 GMT
Connection: keep-alive
ETag: "562e6feb-17"
Accept-Ranges: bytes

監牢模式_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
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
[ynca@LNMP-07 www]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf &>/dev/null
[ynca@LNMP-07 www]$ ps -ef|grep nginx|grep -v grep
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

Web架構深度優化實戰(LNMP與LAMP)