如何使用Nginx泛域名解析+反向代理+靜態(tài)資源緩存呢?
1.安裝nginx,安裝過程不再贅述,記得帶上pcre、gzip、sub、status這幾個模塊,另外如果想開通在線清理緩存功能,需要安裝ngx_cache_purge這個第三方模塊。
2.刪除nginx.conf中默認的server段,此操作不做你會讓你抱憾終身。
3.將以下代碼插入nginx.conf尾部,-t測試-s reload重啟即可。
代碼如下#定義緩存的臨時目錄以及緩存存儲目錄
proxy_temp_path /data/temp;
proxy_cache_path /data/cache levels=1:2 keys_zone=cache_one:32m inactive=1d max_size=3g;
server
{
listen 80;
#接收泛域名解析,務(wù)必保證在這之前沒有其他server段干擾。
server_name _;
root /tmp;
access_log off;
#匹配出對應(yīng)域名
if ( $host ~* (.*).(.*).(.*))
{
set $domain $1;
}
location /
{
#定義所使用的緩存以及緩存的目錄結(jié)構(gòu)。
proxy_cache cache_one;
proxy_cache_valid 200 304 12h;
proxy_cache_key $host$uri$is_args$args;
#下面這條灰常重要,告知upstream源服務(wù)器所要請求的域名是什么。
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#把請求扔給upstream,然后等著領(lǐng)賞吧。
proxy_pass ;
proxy_set_header Accept-Encoding "";
expires 1d;
}
location ~ .*.(php)?$
{
#動態(tài)請求不緩存
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass ;
proxy_set_header Accept-Encoding "";
}
}
upstream jp0129
{
server 106.187.51.139;
}
大功告成,根據(jù)自身情況上機器,每臺部署一個nginx即可,在域名管理中把vcs.xxx.com直接A記錄幾條輪詢,配合一個小腳本來實現(xiàn)檢測各個節(jié)點是否存活,節(jié)點宕掉就直接通過dnspod的api修改vcs.xxx.com的解析記錄,剔除無效節(jié)點即可。
附一個Nginx下泛域名解析配置
在Nginx下支持泛域名解析其實很簡單.只要在在編譯 Nginx的時候加上以下代碼即可
--with-http_sub_module
在配置nginx時:
代碼如下server {
# Replace this port with the right one for your requirements
listen 80;#could also be 1.2.3.4:80
# Multiple hostnames seperated by spaces. Replace these as well.
server_name *.你的域名.com;
#Alternately: _ *
root /PATH/TO/WEBROOT/$host;
error_page 404 ;
access_log logs/yourdomain.com.access.log;
location / {
root /PATH/TO/WEBROOT/$host/;
index index.php;
}
# serve static files directly
location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|html)$ {
access_log off;
expires 30d;
}
location ~ .php$ {
# By all means use a different server for the fcgi processes if you need to
fastcgi_pass 127.0.0.1:YOURFCGIPORTHERE;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /PATH/TO/WEBROOT/$host/$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
fastcgi_intercept_errors on;
}
location ~ /.ht {
deny all;
}
}
然后啟動nginx就可以實現(xiàn)泛域名解析了