- 逆向行駛 - https://520.be -

NGiNX的妙用

Logo

最近綁了不少domain在NGiNX上,一直在編輯nginx.conf同一個檔案管理起來,還真是眼花啊 = =” 心理就在想有沒有比較好的方式做管理呢?! 後來抓新的原始檔下來看,發現可以這樣做,在http區段的最後面寫上

include /usr/local/nginx/conf/conf.d/*.conf;

原先網站設定的server區段就完全移動到

/usr/local/nginx/conf/conf.d/

這個資料夾底下分別建立檔案控制,再建立一個放rewrite規則設定檔的資料夾,我的是放在

/usr/local/nginx/conf/rewrite/

這樣老子就輕鬆多了 A_A 不用一直搞nginx.conf,conf.d這個資料夾就放每個網站的設定檔,rewrite規則設定檔就通通丟在rewrite資料夾底下,有需要再載入就好了,要修改的時候就比較不會眼花撩亂的在查nginx.conf了。這樣做nginx.conf會自動讀取到conf.d資料夾底下的網站設定檔,而網站設定檔再依照需求去載入rewrite規則設定檔,出現錯誤也比較清楚是哪邊寫錯了,不會只在nginx.conf上面一直翻;而且日後要新增網站也輕鬆很多,只要摳比其他的網站設定檔改一下網址跟路徑以及rewrite規則設定檔就好了,感覺效率比較高一些~ ? 下面是我的範例,有興趣可以參考看看,注意include這個字眼唷!
nginx.conf

user  www;
worker_processes  2;
worker_rlimit_nofile 10000;
error_log   /var/log/nginx-error.log;
#error_log  /var/log/nginx-error.log  notice;
#error_log  /var/log/nginx-error.log  info;
pid        /var/run/nginx.pid;
events {
    worker_connections  12800;
    use epoll;
}
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"';
    access_log  /var/log/nginx-access.log  main;
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    server_tokens   off;
    gzip            on;
    gzip_static     on;
    gzip_comp_level 1;
		gzip_buffers     4 16k;
    gzip_min_length 1024;
		gzip_types       text/plain application/x-javascript text/css application/xml;
		gzip_vary on;
    keepalive_timeout  65;
		client_header_timeout 3m;
		client_body_timeout 3m;
		send_timeout 3m;
		fastcgi_connect_timeout 300;
		fastcgi_send_timeout 300;
		fastcgi_read_timeout 300;
		fastcgi_buffer_size 128k;
		fastcgi_buffers 8 128k;
		fastcgi_busy_buffers_size 256k;
		fastcgi_temp_file_write_size 256k;
		client_max_body_size 128m;
		client_body_buffer_size 128k;
		# 暫存資料夾
		proxy_temp_path        tmp/proxy_temp;
		fastcgi_temp_path      tmp/fastcgi_temp;
		client_body_temp_path  tmp/client_body_temp;
		# 設定一個叫做myzone的區域,大小為10MB
    limit_zone   myzone  $binary_remote_addr  10m;
		# 載入所有虛擬主機設定檔
    include /usr/local/nginx/conf/conf.d/*.conf;
}

520.be.conf

server {
listen       80;
server_name  520.be;
index index.html index.htm index.php;
root   /web/www/520.be;
include /usr/local/nginx/conf/rewrite/wordpress.conf;
# 啟用FastCGI
location ~ .*.(php|php5)?$ {
fastcgi_pass  unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fcgi.conf;
}
location ~ .*.(ico|gif|jpg|jpeg|png|bmp|flv|swf)$ {
expires      30d;
access_log off;
}
location ~ .*.(js|css)?$ {
expires      12h;
access_log off;
}
}

wordpress.conf

location / {
index index.html index.htm index.php;
if (-f $request_filename/index.html){
rewrite (.*) $1/index.html break;
}
if (-f $request_filename/index.php){
rewrite (.*) $1/index.php;
}
if (!-f $request_filename){
rewrite (.*) /index.php;
}
}