Nginx配置反向代理服务器

nginx是一个高性能的web服务器,它也是一个很强的反向代理服务器。我们只要下载源码编译安装配置就可以了。

一、安装Nginx
1、安装所需的PCRE库:

cd /tmp
wget -c ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/pcre-8.13.tar.gz
tar -zxvf pcre-8.13.tar.gz
cd pcre-8.13
./configure –prefix=/usr
make
make install

2、下载nginx源码安装:

cd /tmp
wget -c http://nginx.org/download/nginx-1.0.8.tar.gz
tar -zxvf nginx-1.0.8.tar.gz
cd nginx-1.0.8
./configure –user=nginx –group=nginx –prefix=/usr/local/nginx –with-http_addition_module –with-http_perl_module –with-http_flv_module –with-http_gzip_static_module –with-http_realip_module –with-http_ssl_module –with-http_stub_status_module –with-http_sub_module –with-http_dav_module
make
make install

3、建立nginx用户:

useradd nginx -s /sbin/nologin -M

4、以下是安装后显示的一些安装路径:
nginx path prefix: “/usr/local/nginx”
nginx binary file: “/usr/local/nginx/sbin/nginx”
nginx configuration prefix: “/usr/local/nginx/conf”
nginx configuration file: “/usr/local/nginx/conf/nginx.conf”
nginx pid file: “/usr/local/nginx/logs/nginx.pid”
nginx error log file: “/usr/local/nginx/logs/error.log”
nginx http access log file: “/usr/local/nginx/logs/access.log”
nginx http client request body temporary files: “client_body_temp”
nginx http proxy temporary files: “proxy_temp”
nginx http fastcgi temporary files: “fastcgi_temp”
nginx http uwsgi temporary files: “uwsgi_temp”
nginx http scgi temporary files: “scgi_temp”

二、配置nginx
1、编辑配置文件/usr/local/nginx/conf/nginx.conf

vim /usr/local/nginx/conf/nginx.conf

2、修改以下内容
将第一行user前的#去掉,改为:

user nginx nginx;

将worker_processes改大,比如设为2:

worker_processes 2;

将以下两行前的#去掉:

error_log logs/error.log
pid logs/nginx.pid

绑定用来代替的域名或IP:

listen 80;
server_name 绑定的域名或IP;

3、配置反向代理内容,并使用HttpSubModule替换URL:
找到
location / {
root html;
index index.html index.htm;
在后加入:

sub_filter 要反向代理的网址 代替的域名或IP; #替换URL
sub_filter_once off; #搜索替换全部行
proxy_pass http://要反向代理的网址;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Accept-Encoding “”; #清除编码

3、编写nginx启动脚本,设置开机自启动:

vim /etc/init.d/nginx

启动脚本内容看这里

chmod 755 /etc/init.d/nginx
chkconfig –level 345 nginx on

4、测试反向代理
浏览器输入反向代理的域名或IP,查看能够正常打开,URL是否替换。

参考资料:
http://wiki.nginx.org/HttpProxyModule
http://wiki.nginx.org/HttpSubModule
http://kangxiaowei.com/archives/8121.aspx