nginx配置總結

nginx這裏就不做說明了,都知道nginx中最大的亮點是反向代理和靜態頁面的響應,當然其他的功能也不錯,下面將介紹下nginx的一些功能的使用詳解,
*********************************************************************************************************************************************
目錄:
一, 軟件安裝
二, 虛擬主機
三, 用戶認證
四, HTTPS
五, 反向代理
六, 負載均衡
七, URL重寫

*********************************************************************************************************************************************

在rhel5.x上實現以上功能

*********************************************************************************************************************************************
一,編譯安裝nginx

  1. 下載nginx-1.2.2.tar.gz到/usr/src目錄  當然也可以下載最新版的,1.2.2的版本目前來說還是最新版的 
  2. #安裝相關軟件包 
  3. #yum -y groupinstall "Development Libraries"  "Development Tools" 
  4. #yum -y install pcre-devel 
  5. #useradd -s /sbin/nologin nginx 
  6. #cd /usr/src 
  7. #tar xzvf nginx-1.2.2.tar.gz 
  8. #cd /usr/src/nginx-1.2.2 
  9. #./configure --prefix=/usr/local/nginx --pid-path=/var/run/nginx/nginx.pid \ 
  10. --lock-path=/var/lock/nginx.lock --user=nginx --group=nginx --with-http_ssl_module \ 
  11. --with-http_flv_module --with-http_stub_status_module --with-http_gzip_static_module \ 
  12. --http-client-body-temp-path=/var/tmp/nginx/client/ --http-proxy-temp-path=/var/tmp/nginx/proxy \ 
  13. --http-fastcgi-temp-path=/var/tmp/nginx/fcgi --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \ 
  14. --http-scgi-temp-path=/var/tmp/nginx/scgi --with-pcre 
  15. #make && make install 

給nginx提供SysV服務啓動腳本

  1. #vim /etc/init.d/nginx 內容如下 
  2. #!/bin/sh 
  3. # nginx - this script starts and stops the nginx daemon 
  4. # chkconfig:   - 85 15  
  5. # description:  Nginx is an HTTP(S) server, HTTP(S) reverse \ 
  6. #               proxy and IMAP/POP3 proxy server 
  7. # processname: nginx 
  8. # config:      /usr/local/nginx/conf/nginx.conf 
  9. # config:      /etc/sysconfig/nginx 
  10. # pidfile:     /var/run/nginx.pid 
  11.   
  12. # Source function library. 
  13. . /etc/rc.d/init.d/functions 
  14.   
  15. # Source networking configuration. 
  16. . /etc/sysconfig/network 
  17.   
  18. # Check that networking is up. 
  19. [ "$NETWORKING" = "no" ] && exit 0 
  20.   
  21. nginx="/usr/local/nginx/sbin/nginx" 
  22. prog=$(basename $nginx) 
  23.   
  24. NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf" 
  25.   
  26. [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx 
  27.   
  28. lockfile=/var/lock/subsys/nginx 
  29.   
  30. make_dirs() { 
  31.    # make required directories 
  32.    user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -` 
  33.    options=`$nginx -V 2>&1 | grep 'configure arguments:'` 
  34.    for opt in $options; do 
  35.        if [ `echo $opt | grep '.*-temp-path'` ]; then 
  36.            value=`echo $opt | cut -d "=" -f 2` 
  37.            if [ ! -d "$value" ]; then 
  38.                # echo "creating" $value 
  39.                mkdir -p $value && chown -R $user $value 
  40.            fi 
  41.        fi 
  42.    done 
  43.   
  44. start() { 
  45.     [ -x $nginx ] || exit 5 
  46.     [ -f $NGINX_CONF_FILE ] || exit 6 
  47.     make_dirs 
  48.     echo -n $"Starting $prog: " 
  49.     daemon $nginx -c $NGINX_CONF_FILE 
  50.     retval=$? 
  51.     echo 
  52.     [ $retval -eq 0 ] && touch $lockfile 
  53.     return $retval 
  54.   
  55. stop() { 
  56.     echo -n $"Stopping $prog: " 
  57.     killproc $prog -TERM
  58.     retval=$? 
  59.     echo 
  60.     [ $retval -eq 0 ] && rm -f $lockfile 
  61.     return $retval 
  62.   
  63. restart() { 
  64.     configtest || return $? 
  65.     stop 
  66.     sleep 1 
  67.     start 
  68.   
  69. reload() { 
  70.     configtest || return $? 
  71.     echo -n $"Reloading $prog: " 
  72.     killproc $nginx -HUP 
  73.     RETVAL=$? 
  74.     echo 
  75.   
  76. force_reload() { 
  77.     restart 
  78.   
  79. configtest() { 
  80.   $nginx -t -c $NGINX_CONF_FILE 
  81.   
  82. rh_status() { 
  83.     status $prog 
  84.   
  85. rh_status_q() { 
  86.     rh_status >/dev/null 2>&1 
  87.   
  88. case "$1" in 
  89.     start) 
  90.         rh_status_q && exit 0 
  91.         $1 
  92.         ;; 
  93.     stop) 
  94.         rh_status_q || exit 0 
  95.         $1 
  96.         ;; 
  97.     restart|configtest) 
  98.         $1 
  99.         ;; 
  100.     reload) 
  101.         rh_status_q || exit 7 
  102.         $1 
  103.         ;; 
  104.     force-reload) 
  105.         force_reload 
  106.         ;; 
  107.     status) 
  108.         rh_status 
  109.         ;; 
  110.     condrestart|try-restart) 
  111.         rh_status_q || exit 0 
  112.             ;; 
  113.     *) 
  114.         echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}" 
  115.         exit 2 
  116. esac 
  1. 給腳本執行權限 
  2. #chmod a+x /etc/init.d/nginx 
  3. #chkconfig --add nginx 
  4. #chkconfig nginx on 
  5. #service nginx start 

 

二,配置虛擬主機        

  1. #vim /usr/local/nginx/conf/nginx.conf 
  2. ..... 
  3. server { 
  4.          listen   80;  #監聽的端口 
  5.          server_name www.andy.com;   #訪問此站點的域名 
  6.          index  index.html index.htm; #默認主頁 
  7.          root /www;          #網站根目錄 
  8. }
  9. server {
  10. ........
  11. .......
  12. }
  13. ....... 

  如果說此服務器的虛擬主機很多,顯然上面的配置方法不易於管理,我們可以專門指定一個目錄來放虛擬主機的配置文件,每一個虛擬主機單獨使用一個配置文件,這樣的話管理起來也方便多了,配置如下

  1. #vim /usr/local/nginx/conf/nginx.conf 
  2. ..... 
  3. ..... 
  4. include conf/vhost/*.conf;  
  5.  
  6. #mkdir /usr/local/nginx/conf/vhost 
  7. #vim /usr/local/nginx/conf/vhost/www.conf  
  8. server { 
  9. listen   80;  #監聽的端口 
  10. server_name www.andy.com;   #訪問此站點的域名 
  11. index  index.html index.htm; #默認主頁 
  12. root /www;          #網站根目錄 
  13. }


三,用戶認證

  1. #這裏使用htpasswd工具所生成的用戶名密碼作爲用戶認證的來源  
  2. #htpasswd -cd /usr/local/nginx/conf/.auth andy  
  3. #htpasswd -d /usr/local/nginx/conf/.auth andy_f  
  4. #vim /usr/local/nginx/conf/vhost/www.conf  
  5. server {  
  6.         listen   80;   
  7.         server_name www.andy.com;     
  8.         index  index.html index.htm; 
  9.         root /www;   
  10. location / { 
  11.          auth_basic "test"; 
  12.          auth_basic_user_file /usr/local/nginx/conf/.auth; 
  13.  
  14. #service nginx restart 


四, HTTPS 使用自頒發證書實現 

  1. #建立存放https證書的目錄 
  2. #mkdir -pv /usr/local/nginx/conf/.sslkey 
  3. #生成網站私鑰文件 
  4. #cd /usr/local/nginx/conf/.sslkey 
  5. #openssl genrsa -out https.key 1024 
  6. #生存網站證書文件,需要注意的是在生成的過程中需要輸入一些信息根據自己的需要輸入,但Common Name 項輸入的必須是訪問網站的FQDN 
  7. #openssl req -new -x509 -key https.key -out https.crt 
  8. #爲了安全起見,將存放證書的目錄權限設置爲400 
  9. #chmod -R 400 /usr/local/nginx/conf/.sslkey 
  10.  
  11. #vim /usr/local/nginx/conf/vhost/www.conf 
  12. server {  
  13.         listen   443;   
  14.         server_name www.andy.com;   
  15.         index  index.html index.htm;  
  16.         root /www;   
  17.         ssl                 on; 
  18.         ssl_protocols       SSLv3 TLSv1 TLSv1.1 TLSv1.2; 
  19.         ssl_ciphers         AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5; 
  20.         ssl_certificate     /usr/local/nginx/conf/.sslkey/https.crt; 
  21.         ssl_certificate_key /usr/local/nginx/conf/.sslkey/https.key; 
  22.         ssl_session_cache   shared:SSL:10m; 
  23.         ssl_session_timeout 10m; 
  24. }   
  25.  
  26. #重新啓動nginx服務
  27. #service nginx restart   



五, 反向代理  帶緩存機制的反向代理

  1. #vim /usr/local/nginx/conf/nginx/conf 
  2. .......
  3. .......
  4. http { 
  5. ......
  6.  
  7.   proxy_cache_path /var/www/cache levels=1:2 keys_zone=mycache:20m max_size=2048m inactive=60m
  8.   proxy_temp_path /www/cache/tmp; 
  9. ......
  10. server { 
  11.         listen 80; 
  12.         server_name www.andy.com; 
  13.         location / { 
  14.           proxy_pass http://127.0.0.1/;  
  15.           proxy_cache mycache; 
  16.           proxy_cache_valid 200 302 60m; 
  17.           proxy_cache_valid 404 1m; 
  18.           proxy_set_header Host $host; 
  19.           proxy_set_header X-Real-IP $remote_addr; 
  20.           } 
  21. #重啓nginx服務
  22. #service nginx restart

 

六, 負載均衡
      在nginx中實現負載均衡其實也是使用反向代理的機制,那麼在nginx中默認支持的調度算法有三種,輪詢,加權輪詢,ip_hash, 負載均衡是啥不用解釋了吧,下面來配置下nginx的負載均衡.

  1. #vim /usr/local/nginx/conf/nginx.conf  
  2. user  nginx;  
  3. worker_processes  10;  
  4. error_log  logs/error.log crit;  
  5. pid        logs/nginx.pid;  
  6. events  
  7. {  
  8.   use epoll;  
  9.   worker_connections 51000;  
  10. }  
  11. http {  
  12.     include       mime.types;  
  13.     default_type  application/octet-stream;  
  14.     keepalive_timeout  60;  
  15.     tcp_nodelay on;  
  16. #指定負載均衡的方式 bbs.andy.com 是一個名字負載均衡集羣的名字
  17.     upstream bbs.andy.com {  
  18.         server  172.16.0.2:80;  #後端的應用服務器
  19.         server  172.16.0.3:80;
  20. server 172.16.0.4:80 weight=5; 權重
  21. server 172.16.0.5:8080 backup; 備份節點,  
  22.         ip_hash;  #調度算法
  23.         }  
  24.     server {  
  25.         listen       80;  
  26.         server_name  bbs.andy.com;  
  27.         index index.html index.htm index.php;  
  28.         location / {  
  29.             proxy_pass      http://bbs.andy.com;  #指定反代到哪個主機,或集羣列表中
  30. #如果後端服務器出現502 或504錯誤代碼的話nginx就不會請求某臺服務器了,當後端服務器又工作正常了,nginx繼續請求,這樣一來達到了後端服務器健康狀況檢測的功能,
  31. proxy_next_upstream http_502 http_504 error timeout invalid_header;  
  32.             proxy_set_header    Host    $host;  
  33.             proxy_set_header    X-Real-IP   $remote_addr;  
  34.             proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;  
  35.             proxy_connect_timeout   600;  
  36.             proxy_read_timeout  600;  
  37.             proxy_send_timeout  600;  
  38.             proxy_buffer_size   8k;  
  39.             proxy_temp_file_write_size  64k;  
  40.         }     
  41.   
  42.       
  43.         access_log      logs/bbs.log;  
  44.   
  45.         }  

 

七,URL重寫
 所謂url重寫就是將某個路徑重新定位到另一個路徑,跟查找替換差不多,格式如下
語法格式 : rewrite regex replacement [flag];   
在nginx中url重寫的處理機制有以下4種,
  last    被匹配到的url再進行匹配
  break 被匹配到的url就不在進行匹配了
  redirect 臨時重定向
  permanent 永久重定向

1,比如說訪問某站點的路徑爲/forum/ 此時想使用/bbs來訪問此站點需要做url重寫如下

  1. location / {
  2. rewrite ^/forum/?$ /bbs/ permanent; 
  3. }

2,比如說某站點有個圖片服務器(10.0.0.1/p_w_picpaths/ ) 此時訪問某站點上/p_w_picpaths/的資源時希望訪問到圖片服務器上的資源

  1. location / {
  2. rewrite ^/p_w_picpaths/(.*\.jpg)$  /p_w_picpaths2/$1 break;

3, 域名跳轉

  1. server 
  2. listen 80; 
  3. server_name andy.com; 
  4. rewrite ^/ http://www.andy.com/; 

4,域名鏡像

  1. server 
  2. listen 80; 
  3. server_name  andy.com; 
  4. rewrite ^/(.*)$ http://www.andy.com/$1 last; 

*********************************************************************************************************************************************
在nginx的url重寫中還支持if判斷語句,
語法 if ( 條件 ) { ..... }
應用環境 server  ,location 
if 判斷的條件如下
1、變量名; false values are: empty string ("", or any string starting with "0";)
2、對於變量進行的比較表達式,可使用=或!=進行測試;
3、正則表達式的模式匹配:
  ~  區分大小的模式匹配
  ~* 不區分字母大小寫的模式匹配
 !~ 和 !~* 分別對上面的兩種測試取反
4、測試文件是否存在-f或!-f
5、測試目錄是否存在-d或!-d
6、測試目錄、文件或鏈接文件的存在性-e或!-e
7、檢查一個文件的執行權限-x或!-x

*********************************************************************************************************************************************
nginx 的一些內置變量,
http://wiki.nginx.org/HttpCoreModule#Variables   官方文檔
$arg_PARAMETER
$args
$binary_remote_addr
$body_bytes_sent
$content_length
$content_type
$cookie_COOKIE
$document_root
$document_uri
$host
$hostname
$http_HEADER
$sent_http_HEADER
$is_args
$limit_rate
$nginx_version
$query_string
$remote_addr
$remote_port
$remote_user
$request_filename
$request_body
$request_body_file
$request_completion
$request_method
$request_uri
$scheme
$server_addr
$server_name
$server_port
$server_protocol
$uri
*********************************************************************************************************************************************
5,簡單的防盜鏈

  1. location ~* \.(gif|jpg|png|swf|flv)$ { 
  2.   valid_referers none blocked www.andy.com; 
  3.   if ($invalid_referer) { 
  4.     rewrite ^/ http://www.andy.com/403.html; 
  5.   } 

6,如果用戶請求的頁面不存在則自定義跳轉

  1. if (!-f $request_filename) { 
  2.       rewrite ^(/.*)$ http://www.andy.com permanent; 

7,判斷用戶瀏覽器的類型,作出相應的跳轉,

  1. if ($http_user_agent ~* MSIE) { 
  2.   rewrite  ^(.*)$  /msie/$1  break; 

 

OK ,完工了,暫時總結了這麼多

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章