Nginx + Apache 配置反向代理和静态资源缓存

时间:2022-09-17 00:22:51

转自:http://www.icultivator.com/p/9443.html

Nginx处理静态内容是把好手,Apache虽然占用内存多了点,性能上稍逊,但一直比较稳健。倒是Nginx的FastCGI有时候会出现502 Bad Gateway错误。一个可选的方法是Nginx做前端代理,处理静态内容,动态请求统统转发给后端Apache。Nginx Server配置如下(测试环境):

server {
listen 80;
server_name test.com;

location / {
root /www/test;
index index.php index.html;

# Nginx找不到文件时,转发请求给后端Apache
error_page 404 @proxy;

# css, js 静态文件设置有效期1天
location ~ .*\.(js|css)$ {
access_log off;
expires 1d;
}

# 图片设置有效期3天
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
access_log off;
expires 3d;
}
}

# 动态文件.php请求转发给后端Apache
location ~ \.php$ {
#proxy_redirect off;
#proxy_pass_header Set-Cookie;
#proxy_set_header Cookie $http_cookie;

# 传递真实IP到后端
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_pass http://127.0.0.1:8080;
}

location @proxy {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_pass http://127.0.0.1:8080;
}
}